Instructions to use moonbox-dev/TRELLIS-text-xlarge-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/TRELLIS-text-xlarge-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Trellis
How to use moonbox-dev/TRELLIS-text-xlarge-TensorRT with Trellis:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
fp16 build of TRELLIS text-conditioned
Browse filesFiles changed (22)
- .gitattributes+10
- fp16/LICENSE-CLIP.txtAdded+22
- fp16/LICENSE-FlexiCubes.txtAdded+202
- fp16/LICENSE-TRELLIS.txtAdded+21
- fp16/clip.engineAdded+3
- fp16/device_chain.pyAdded+188
- fp16/flexicubes_tables.npzAdded+3
- fp16/mesh_dec.engineAdded+3
- fp16/pipeline.pyAdded+409
- fp16/pipeline_trt.pyAdded+79
- fp16/slat_flow_0.engineAdded+3
- fp16/slat_flow_1.engineAdded+3
- fp16/slat_flow_2.engineAdded+3
- fp16/slat_flow_3.engineAdded+3
- fp16/slat_flow_split.jsonAdded+59
- fp16/ss_dec.engineAdded+3
- fp16/ss_flow_0.engineAdded+3
- fp16/ss_flow_1.engineAdded+3
- fp16/ss_flow_2.engineAdded+3
- fp16/ss_flow_split.jsonAdded+36
- fp16/tokenizer.jsonAdded
- fp16/trt_runner.pyAdded+98
32 unmodified lines3334353637383940414243444532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfp16/clip.engine filter=lfs diff=lfs merge=lfs -textfp16/mesh_dec.engine filter=lfs diff=lfs merge=lfs -textfp16/slat_flow_0.engine filter=lfs diff=lfs merge=lfs -textfp16/slat_flow_1.engine filter=lfs diff=lfs merge=lfs -textfp16/slat_flow_2.engine filter=lfs diff=lfs merge=lfs -textfp16/slat_flow_3.engine filter=lfs diff=lfs merge=lfs -textfp16/ss_dec.engine filter=lfs diff=lfs merge=lfs -textfp16/ss_flow_0.engine filter=lfs diff=lfs merge=lfs -textfp16/ss_flow_1.engine filter=lfs diff=lfs merge=lfs -textfp16/ss_flow_2.engine filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122MIT License
Copyright (c) 2021 OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.123456789101112131415161718192021 MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE123version https://git-lfs.github.com/spec/v1oid sha256:f718ff7a9242720850cbe0c2a968424fb059a872649e842618df830f653d470bsize 541238700123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""TensorRT engines run on GPU buffers (Polygraphy's CUDA wrapper; no torch): a decoder's KV cache stays on the GPUbetween steps, and the activations between split engines (piecewise.py) never leave it.
from device_chain import Chain, Buffers step = Chain(folder, [{"engine": "gpt_step_0.engine"}, ...]) # or Chain.from_split(folder, "gpt_step") out = step({"token": np.array(...), "c_k0": cache_a["c_k0"], ...}, # numpy arrays are copied in, DeviceArrays used outputs={"n_k0": cache_b["n_k0"], ...}, # where these outputs go (else the chain's own) fetch=["logits"]) # -> {"logits": numpy array}
A tensor a call writes must not be one it reads: a cache is read from one set of buffers and written to another, andthe two sets swap after every step (Buffers.swap). Buffers are allocated at their largest shape once; a smaller shapereuses the allocation (DeviceArray.resize), so the steps allocate nothing."""from __future__ import annotations
import jsonfrom pathlib import Path
import numpy as np
def _cuda(): from polygraphy import cuda return cuda
def device_array(shape, dtype): """A DeviceArray of a numpy dtype (Polygraphy's DataType: numpy dtypes there are deprecated), which also keeps the numpy dtype (reading DeviceArray.dtype logs a deprecation warning on every call).""" from polygraphy.datatype import DataType a = _cuda().DeviceArray(shape=tuple(shape), dtype=DataType.from_dtype(np.dtype(dtype))) a.np_dtype = np.dtype(dtype) return a
def host_dtype(a) -> np.dtype: return a.np_dtype
class Engine: """One engine on device buffers. Its execution context holds device memory for the profile's largest shapes, or, with shared=True, none of its own: Chain gives all its engines one scratch buffer (they run one at a time on one stream), the size of the largest one's."""
def __init__(self, path, shared=False): import tensorrt as trt from trt_runner import lean_dlls lean_dlls() self.trt = trt runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING)) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine if shared: self.context = engine.create_execution_context(trt.ExecutionContextAllocationStrategy.USER_MANAGED) self.scratch = engine.get_device_memory_size_for_profile_v2(0) else: self.context, self.scratch = engine.create_execution_context(), 0 names = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)] self.inputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.INPUT] self.outputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT] self.dtype = {n: np.dtype(trt.nptype(engine.get_tensor_dtype(n))) for n in names}
def enqueue(self, inputs: dict, outputs: dict, stream) -> None: """inputs / outputs: name -> DeviceArray. Each output is resized to its shape for these inputs.""" c = self.context for n in self.inputs: a = inputs[n] c.set_input_shape(n, tuple(a.shape)) c.set_tensor_address(n, a.ptr) for n in self.outputs: o = outputs[n] o.resize(tuple(c.get_tensor_shape(n))) c.set_tensor_address(n, o.ptr) if not c.execute_async_v3(stream.ptr): raise RuntimeError("TensorRT execution failed")
def use_memory(self, buf) -> None: self.context.set_device_memory(buf.ptr, self.scratch)
def close(self): self.context = self.engine = None
class Chain: """Engines run in order on one CUDA stream; each reads the call's inputs and earlier engines' outputs by name."""
def __init__(self, folder, plan: list[dict], shared_memory=True): self.folder, self.plan, self.engines = Path(folder), plan, [] self.pool = {} # the chain's own buffers, by tensor name self.stream = None self.shared = shared_memory # one scratch buffer for all the engines' activations
@classmethod def from_split(cls, folder, part: str): """<part>_split.json (the engines in order) if the part was split, else <part>.engine alone.""" f = Path(folder) / f"{part}_split.json" return cls(folder, json.loads(f.read_text()) if f.exists() else [{"engine": f"{part}.engine"}])
def load(self): if not self.engines: self.stream = _cuda().Stream() self.engines = [Engine(self.folder / p["engine"], self.shared) for p in self.plan] if self.shared: scratch = self.pool["scratch"] = device_array((max(1, *(e.scratch for e in self.engines)),), np.uint8) for e in self.engines: e.use_memory(scratch) return self
def buffer(self, name: str, dtype, shape=(1,)): """The chain's own buffer for a tensor (allocated on first use, at least one element).""" b = self.pool.get(name) if b is None: b = self.pool[name] = device_array(tuple(max(1, d) for d in shape) or (1,), dtype) return b
def __call__(self, feeds: dict, outputs: dict | None = None, fetch=()) -> dict: self.load() outputs = outputs or {} env, keep = {}, [] for n, v in feeds.items(): if isinstance(v, np.ndarray): # host -> a pooled device buffer of the engine's dtype want = next((e.dtype[n] for e in self.engines if n in e.dtype), v.dtype) h = np.ascontiguousarray(v, dtype=want) b = self.buffer("in:" + n, want, h.shape) b.resize(h.shape) b.copy_from(h, self.stream) keep.append(h) # alive until the stream has copied it env[n] = b else: env[n] = v for e in self.engines: outs = {n: outputs[n] if n in outputs else self.buffer(n, e.dtype[n]) for n in e.outputs} e.enqueue(env, outs, self.stream) env.update(outs) res = {} for n in fetch: a = env[n] res[n] = np.empty(tuple(a.shape), dtype=host_dtype(a)) a.copy_to(res[n], self.stream) self.stream.synchronize() return res
def close(self): for e in self.engines: e.close() for b in self.pool.values(): b.free() self.engines, self.pool = [], {}
class Buffers: """Two sets of device buffers for a decoder's caches, each allocated at the largest shape: step k reads set A and writes set B, then swap() exchanges them."""
def __init__(self, names_in: list[str], names_out: list[str], dtype, max_shape): self.names_in, self.names_out = names_in, names_out self.a = [device_array(max_shape, dtype) for _ in names_in] self.b = [device_array(max_shape, dtype) for _ in names_in]
def reads(self) -> dict: return dict(zip(self.names_in, self.a))
def writes(self) -> dict: return dict(zip(self.names_out, self.b))
def swap(self): self.a, self.b = self.b, self.a
def reset(self, shape): """Set A as an empty cache of this shape (e.g. [1, 0, 256] before a prefill): no copy, no allocation.""" for buf in self.a: buf.resize(tuple(shape))
def load(self, arrays, stream=None): """Fill set A from host arrays (the prompt's cache).""" for buf, x in zip(self.a, arrays): x = np.ascontiguousarray(x, dtype=host_dtype(buf)) buf.resize(x.shape) buf.copy_from(x, stream)
def free(self): for b in self.a + self.b: b.free() self.a = self.b = []123version https://git-lfs.github.com/spec/v1oid sha256:1d22bf7f2ec21cf0832e550593630551071f7bd26175c896f2361f82fd44786esize 2639123version https://git-lfs.github.com/spec/v1oid sha256:f0a66b70c0c5924f9f6bc14312776e534d1af0b7c5a694135acfbdbcd2036d42size 343827412123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409"""TRELLIS text-conditioned (xlarge) with ONNX Runtime: a text prompt -> a mesh with vertex colours. The CLIP textencoder, the sparse-structure flow and decoder, the structured-latent flow and the mesh decoder as ONNX graphs; numpyaround 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 builthere 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 itertoolsfrom 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-5SLAT_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 orderWINDOW = 8
# ------------------------------------------------------------------------------------------------ the promptdef 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 tablesdef 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 runtimedef 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")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""TRELLIS text-conditioned (xlarge) with TensorRT: the ONNX build's pipeline.py (CLIP features of the prompt and theempty prompt, the sparse-structure flow and decoder, the structured-latent flow, the mesh decoder and FlexiCubes innumpy) with its graphs run as the engines in this folder:
clip.engine input_ids [1, 77] -> cond [1, 77, 768] (fp32, as the original) ss_flow_0..k.engine the sparse-structure flow (ss_flow_split.json): x [B, 8, 16, 16, 16], t [B], cond [B, 77, 768] -> velocity (B <= 2: the guided step's two rows in one batch) ss_dec.engine z [1, 8, 16, 16, 16] -> logits [1, 1, 64, 64, 64] slat_flow_0..k.engine the structured-latent flow (slat_flow_split.json): feats [N, 8], t, cond and the voxels' index tables -> velocity [N, 8] mesh_dec.engine slat [N, 8], the window / neighbour tables -> FlexiCubes features [64 N, 101]
As in pipeline.py, a stage's engines are loaded when it starts and released when it ends. Limits of the engines: up to16,384 occupied voxels; the mesh decoder's Swin windows (8^3 voxels) up to 320 occupied windows of up to 384 voxels.Needs numpy, tokenizers, tensorrt-cu12 / tensorrt-lean-cu12 10.13 and polygraphy; trimesh to write the mesh.
python pipeline_trt.py "A chair looking like a avocado." chair.glb [--seed 1]"""
from __future__ import annotations
import sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from device_chain import Chain # noqa: E402from pipeline import TrellisText, save_mesh # noqa: E402
MAX_VOXELS = 16384MAX_WINDOWS, MAX_WINDOW_VOXELS = 320, 384 # the mesh decoder's Swin windows (8^3 voxels)
class TrellisTextTrt(TrellisText): def __init__(self, folder=HERE): self.folder = Path(folder) self.s = {} self.tables = dict(np.load(self.folder / "flexicubes_tables.npz"))
def session(self, name): if name not in self.s: c = Chain.from_split(self.folder, name).load() c.inputs = {n for e in c.engines for n in e.inputs} c.output = c.engines[-1].outputs[0] self.s[name] = c return self.s[name]
def release(self, *names): for n in names: c = self.s.pop(n, None) if c is not None: c.close()
def run(self, name, feed): if name in ("slat_flow", "mesh_dec") and len(feed.get("feats", feed.get("slat"))) > MAX_VOXELS: raise ValueError(f"{len(feed.get('feats', feed.get('slat')))} voxels; the engines take up to {MAX_VOXELS}") if name == "mesh_dec": for k in ("win0_fwd", "win4_fwd"): w, l = feed[k].shape if w > MAX_WINDOWS or l > MAX_WINDOW_VOXELS: raise ValueError(f"{w} windows of up to {l} voxels; the mesh decoder engine takes up to " f"{MAX_WINDOWS} of up to {MAX_WINDOW_VOXELS}") c = self.session(name) return c({k: v for k, v in feed.items() if k in c.inputs}, fetch=[c.output])[c.output]
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(HERE)) a = ap.parse_args() v, f, attrs = TrellisTextTrt(a.dir)(a.prompt, a.seed) save_mesh(a.out, v, f, attrs) print(len(v), "vertices,", len(f), "faces")123version https://git-lfs.github.com/spec/v1oid sha256:68c6df2aaa3582a79727ebb69e556a3f4fd085d8b7c682b7069812cbfab4b9fasize 768464932123version https://git-lfs.github.com/spec/v1oid sha256:24eb5d28274154fc6a5d420204fc6f821e0b5abd8010cd53dde17016fed21263size 762027428123version https://git-lfs.github.com/spec/v1oid sha256:042823d65d09d82c7d8ad692a8adfcde1fc0fc46db5d1358837ead3efe0f053bsize 762114748123version https://git-lfs.github.com/spec/v1oid sha256:32789e8ce5bb70890bb4c411a008e0fe41d15497003ed3d8ecf7951e550c8041size 1188939401234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859[
{
"engine": "slat_flow_0.engine",
"inputs": [
"feats",
"t",
"cond",
"nbr64",
"coords32",
"nbr32",
"down_child",
"down_cnt"
],
"outputs": [
"/m/blocks.7/Add_7_output_0",
"/m/input_blocks.0/Add_3_output_0",
"/m/input_blocks.0/emb_layers/emb_layers.0/Mul_output_0",
"/m/input_blocks.1/Add_3_output_0",
"/m/input_blocks.2/Add_3_output_0"
]
},
{
"engine": "slat_flow_1.engine",
"inputs": [
"cond",
"/m/blocks.7/Add_7_output_0",
"/m/input_blocks.0/emb_layers/emb_layers.0/Mul_output_0"
],
"outputs": [
"/m/blocks.17/Add_7_output_0"
]
},
{
"engine": "slat_flow_2.engine",
"inputs": [
"cond",
"/m/blocks.17/Add_7_output_0",
"/m/input_blocks.0/emb_layers/emb_layers.0/Mul_output_0",
"/m/input_blocks.2/Add_3_output_0"
],
"outputs": [
"/m/Concat_output_0"
]
},
{
"engine": "slat_flow_3.engine",
"inputs": [
"nbr64",
"up_idx",
"/m/Concat_output_0",
"/m/input_blocks.0/Add_3_output_0",
"/m/input_blocks.0/emb_layers/emb_layers.0/Mul_output_0",
"/m/input_blocks.1/Add_3_output_0"
],
"outputs": [
"velocity"
]
}
]123version https://git-lfs.github.com/spec/v1oid sha256:89a8879dd781e6788272ccf145a6d02344154fd0cd52076cc910a31b467e962fsize 201668036123version https://git-lfs.github.com/spec/v1oid sha256:628eb7c298590783f29e8705173cba4d0ff4ba4d3f72aca41b8d9ac5ce4ecb0esize 732121492123version https://git-lfs.github.com/spec/v1oid sha256:3734f34e212d27a80f622959eb323677311dc524314a8d2c980ec5f708ee0af9size 775508972123version https://git-lfs.github.com/spec/v1oid sha256:f4fffb196bea0367c617012f292816b574c29cff5db64296133f0d6fb5b31496size 703077044123456789101112131415161718192021222324252627282930313233343536[
{
"engine": "ss_flow_0.engine",
"inputs": [
"x",
"t",
"cond"
],
"outputs": [
"/m/blocks.0/adaLN_modulation/adaLN_modulation.0/Mul_output_0",
"/m/blocks.8/Add_7_output_0"
]
},
{
"engine": "ss_flow_1.engine",
"inputs": [
"cond",
"/m/blocks.0/adaLN_modulation/adaLN_modulation.0/Mul_output_0",
"/m/blocks.8/Add_7_output_0"
],
"outputs": [
"/m/blocks.18/Add_7_output_0"
]
},
{
"engine": "ss_flow_2.engine",
"inputs": [
"cond",
"/m/blocks.0/adaLN_modulation/adaLN_modulation.0/Mul_output_0",
"/m/blocks.18/Add_7_output_0"
],
"outputs": [
"velocity"
]
}
]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).
from trt_runner import Engine e = Engine("model.engine") out = e({"input": x}) # dict of output name -> numpy array"""from __future__ import annotations
from pathlib import Path
import numpy as np
def lean_dlls(): """Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12): put its DLL folder on the search path (Windows).""" import importlib.util import os spec = importlib.util.find_spec("tensorrt_lean_libs") if spec and spec.submodule_search_locations: d = list(spec.submodule_search_locations)[0] os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") if hasattr(os, "add_dll_directory"): os.add_dll_directory(d)
class Engine: """allocation: "static" (memory for the profiles' largest shapes, reserved once) or "runtime" (sized to each call's shapes: for pipelines of many engines with wide profiles, which would otherwise reserve every engine's maximum)."""
def __init__(self, path, allocation="static"): lean_dlls() import tensorrt as trt from polygraphy.backend.trt import TrtRunner self.trt = trt logger = trt.Logger(trt.Logger.WARNING) runtime = trt.Runtime(logger) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine self.runner = TrtRunner(engine, allocation_strategy=allocation) self.runner.activate() self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors) if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]
def __call__(self, feed: dict) -> dict: feed = {k: np.ascontiguousarray(v) for k, v in feed.items() if k in self.inputs} out = self.runner.infer(feed, check_inputs=True) return {k: np.array(v) for k, v in out.items()}
def close(self): """Release the engine's device memory and weights now (deactivating the runner alone keeps the weights on the GPU until the engine object is collected).""" runner = getattr(self, "runner", None) if runner is not None and runner.is_active: runner.deactivate() self.runner = self.engine = None
def __del__(self): try: self.close() except Exception: pass
class OrtLike: """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the ONNX graph listed them (pass `outputs`), else in the engine's order."""
def __init__(self, path, outputs=None, allocation="static"): self.e = Engine(path, allocation) eng = self.e.engine names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)] self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]
def get_inputs(self): """name, type ("tensor(float16)" etc., as onnxruntime spells it) and shape (-1 for dynamic dimensions).""" from types import SimpleNamespace eng, trt = self.e.engine, self.e.trt names = {trt.float16: "float16", trt.float32: "float", trt.int64: "int64", trt.int32: "int32", trt.bool: "bool", trt.int8: "int8", trt.bfloat16: "bfloat16"} return [SimpleNamespace(name=n, type=f"tensor({names.get(eng.get_tensor_dtype(n), 'float')})", shape=list(eng.get_tensor_shape(n))) for n in self.e.inputs]
def get_outputs(self): from types import SimpleNamespace return [SimpleNamespace(name=n) for n in self.outs]
def get_providers(self): return ["TensorRT"]
def run(self, names, feed, run_options=None): out = self.e(feed) return [out[n] for n in (names or self.outs)].gitattributes+10
fp16/LICENSE-CLIP.txtAdded+22
fp16/LICENSE-FlexiCubes.txtAdded+202
fp16/LICENSE-TRELLIS.txtAdded+21
fp16/clip.engineAdded+3
fp16/device_chain.pyAdded+188
fp16/flexicubes_tables.npzAdded+3
fp16/mesh_dec.engineAdded+3
fp16/pipeline.pyAdded+409
fp16/pipeline_trt.pyAdded+79
fp16/slat_flow_0.engineAdded+3
fp16/slat_flow_1.engineAdded+3
fp16/slat_flow_2.engineAdded+3
fp16/slat_flow_3.engineAdded+3
fp16/slat_flow_split.jsonAdded+59
fp16/ss_dec.engineAdded+3
fp16/ss_flow_0.engineAdded+3
fp16/ss_flow_1.engineAdded+3
fp16/ss_flow_2.engineAdded+3
fp16/ss_flow_split.jsonAdded+36
fp16/tokenizer.jsonAdded
fp16/trt_runner.pyAdded+98