Spaces:
Running
on
Zero
Running
on
Zero
Upload 9 files
Browse files- trellis/pipelines/__init__.py +25 -0
- trellis/pipelines/base.py +68 -0
- trellis/pipelines/samplers/__init__.py +2 -0
- trellis/pipelines/samplers/base.py +20 -0
- trellis/pipelines/samplers/classifier_free_guidance_mixin.py +12 -0
- trellis/pipelines/samplers/flow_euler.py +201 -0
- trellis/pipelines/samplers/guidance_interval_mixin.py +15 -0
- trellis/pipelines/trellis_image_to_3d.py +375 -0
- trellis/pipelines/trellis_text_to_3d.py +278 -0
trellis/pipelines/__init__.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from . import samplers
|
2 |
+
from .trellis_image_to_3d import TrellisImageTo3DPipeline
|
3 |
+
from .trellis_text_to_3d import TrellisTextTo3DPipeline
|
4 |
+
|
5 |
+
|
6 |
+
def from_pretrained(path: str):
|
7 |
+
"""
|
8 |
+
Load a pipeline from a model folder or a Hugging Face model hub.
|
9 |
+
|
10 |
+
Args:
|
11 |
+
path: The path to the model. Can be either local path or a Hugging Face model name.
|
12 |
+
"""
|
13 |
+
import os
|
14 |
+
import json
|
15 |
+
is_local = os.path.exists(f"{path}/pipeline.json")
|
16 |
+
|
17 |
+
if is_local:
|
18 |
+
config_file = f"{path}/pipeline.json"
|
19 |
+
else:
|
20 |
+
from huggingface_hub import hf_hub_download
|
21 |
+
config_file = hf_hub_download(path, "pipeline.json")
|
22 |
+
|
23 |
+
with open(config_file, 'r') as f:
|
24 |
+
config = json.load(f)
|
25 |
+
return globals()[config['name']].from_pretrained(path)
|
trellis/pipelines/base.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from .. import models
|
5 |
+
|
6 |
+
|
7 |
+
class Pipeline:
|
8 |
+
"""
|
9 |
+
A base class for pipelines.
|
10 |
+
"""
|
11 |
+
def __init__(
|
12 |
+
self,
|
13 |
+
models: dict[str, nn.Module] = None,
|
14 |
+
):
|
15 |
+
if models is None:
|
16 |
+
return
|
17 |
+
self.models = models
|
18 |
+
for model in self.models.values():
|
19 |
+
model.eval()
|
20 |
+
|
21 |
+
@staticmethod
|
22 |
+
def from_pretrained(path: str) -> "Pipeline":
|
23 |
+
"""
|
24 |
+
Load a pretrained model.
|
25 |
+
"""
|
26 |
+
import os
|
27 |
+
import json
|
28 |
+
is_local = os.path.exists(f"{path}/pipeline.json")
|
29 |
+
|
30 |
+
if is_local:
|
31 |
+
config_file = f"{path}/pipeline.json"
|
32 |
+
else:
|
33 |
+
from huggingface_hub import hf_hub_download
|
34 |
+
config_file = hf_hub_download(path, "pipeline.json")
|
35 |
+
|
36 |
+
with open(config_file, 'r') as f:
|
37 |
+
args = json.load(f)['args']
|
38 |
+
|
39 |
+
_models = {}
|
40 |
+
for k, v in args['models'].items():
|
41 |
+
try:
|
42 |
+
_models[k] = models.from_pretrained(f"{path}/{v}")
|
43 |
+
except:
|
44 |
+
_models[k] = models.from_pretrained(v)
|
45 |
+
|
46 |
+
new_pipeline = Pipeline(_models)
|
47 |
+
new_pipeline._pretrained_args = args
|
48 |
+
return new_pipeline
|
49 |
+
|
50 |
+
@property
|
51 |
+
def device(self) -> torch.device:
|
52 |
+
for model in self.models.values():
|
53 |
+
if hasattr(model, 'device'):
|
54 |
+
return model.device
|
55 |
+
for model in self.models.values():
|
56 |
+
if hasattr(model, 'parameters'):
|
57 |
+
return next(model.parameters()).device
|
58 |
+
raise RuntimeError("No device found.")
|
59 |
+
|
60 |
+
def to(self, device: torch.device) -> None:
|
61 |
+
for model in self.models.values():
|
62 |
+
model.to(device)
|
63 |
+
|
64 |
+
def cuda(self) -> None:
|
65 |
+
self.to(torch.device("cuda"))
|
66 |
+
|
67 |
+
def cpu(self) -> None:
|
68 |
+
self.to(torch.device("cpu"))
|
trellis/pipelines/samplers/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .base import Sampler
|
2 |
+
from .flow_euler import FlowEulerSampler, FlowEulerCfgSampler, FlowEulerGuidanceIntervalSampler
|
trellis/pipelines/samplers/base.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
from abc import ABC, abstractmethod
|
3 |
+
|
4 |
+
|
5 |
+
class Sampler(ABC):
|
6 |
+
"""
|
7 |
+
A base class for samplers.
|
8 |
+
"""
|
9 |
+
|
10 |
+
@abstractmethod
|
11 |
+
def sample(
|
12 |
+
self,
|
13 |
+
model,
|
14 |
+
**kwargs
|
15 |
+
):
|
16 |
+
"""
|
17 |
+
Sample from a model.
|
18 |
+
"""
|
19 |
+
pass
|
20 |
+
|
trellis/pipelines/samplers/classifier_free_guidance_mixin.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
|
3 |
+
|
4 |
+
class ClassifierFreeGuidanceSamplerMixin:
|
5 |
+
"""
|
6 |
+
A mixin class for samplers that apply classifier-free guidance.
|
7 |
+
"""
|
8 |
+
|
9 |
+
def _inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, **kwargs):
|
10 |
+
pred = super()._inference_model(model, x_t, t, cond, **kwargs)
|
11 |
+
neg_pred = super()._inference_model(model, x_t, t, neg_cond, **kwargs)
|
12 |
+
return (1 + cfg_strength) * pred - cfg_strength * neg_pred
|
trellis/pipelines/samplers/flow_euler.py
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
from tqdm import tqdm
|
5 |
+
from easydict import EasyDict as edict
|
6 |
+
from .base import Sampler
|
7 |
+
from .classifier_free_guidance_mixin import ClassifierFreeGuidanceSamplerMixin
|
8 |
+
from .guidance_interval_mixin import GuidanceIntervalSamplerMixin
|
9 |
+
|
10 |
+
|
11 |
+
class FlowEulerSampler(Sampler):
|
12 |
+
"""
|
13 |
+
Generate samples from a flow-matching model using Euler sampling.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
sigma_min: The minimum scale of noise in flow.
|
17 |
+
"""
|
18 |
+
def __init__(
|
19 |
+
self,
|
20 |
+
sigma_min: float,
|
21 |
+
):
|
22 |
+
self.sigma_min = sigma_min
|
23 |
+
|
24 |
+
def _eps_to_xstart(self, x_t, t, eps):
|
25 |
+
assert x_t.shape == eps.shape
|
26 |
+
return (x_t - (self.sigma_min + (1 - self.sigma_min) * t) * eps) / (1 - t)
|
27 |
+
|
28 |
+
def _xstart_to_eps(self, x_t, t, x_0):
|
29 |
+
assert x_t.shape == x_0.shape
|
30 |
+
return (x_t - (1 - t) * x_0) / (self.sigma_min + (1 - self.sigma_min) * t)
|
31 |
+
|
32 |
+
def _v_to_xstart_eps(self, x_t, t, v):
|
33 |
+
assert x_t.shape == v.shape
|
34 |
+
eps = (1 - t) * v + x_t
|
35 |
+
x_0 = (1 - self.sigma_min) * x_t - (self.sigma_min + (1 - self.sigma_min) * t) * v
|
36 |
+
return x_0, eps
|
37 |
+
|
38 |
+
def _inference_model(self, model, x_t, t, cond=None, **kwargs):
|
39 |
+
t = torch.tensor([1000 * t] * x_t.shape[0], device=x_t.device, dtype=torch.float32)
|
40 |
+
if cond is not None and cond.shape[0] == 1 and x_t.shape[0] > 1:
|
41 |
+
cond = cond.repeat(x_t.shape[0], *([1] * (len(cond.shape) - 1)))
|
42 |
+
return model(x_t, t, cond, **kwargs)
|
43 |
+
|
44 |
+
def _get_model_prediction(self, model, x_t, t, cond=None, **kwargs):
|
45 |
+
pred_v = self._inference_model(model, x_t, t, cond, **kwargs)
|
46 |
+
pred_x_0, pred_eps = self._v_to_xstart_eps(x_t=x_t, t=t, v=pred_v)
|
47 |
+
return pred_x_0, pred_eps, pred_v
|
48 |
+
|
49 |
+
@torch.no_grad()
|
50 |
+
def sample_once(
|
51 |
+
self,
|
52 |
+
model,
|
53 |
+
x_t,
|
54 |
+
t: float,
|
55 |
+
t_prev: float,
|
56 |
+
cond: Optional[Any] = None,
|
57 |
+
**kwargs
|
58 |
+
):
|
59 |
+
"""
|
60 |
+
Sample x_{t-1} from the model using Euler method.
|
61 |
+
|
62 |
+
Args:
|
63 |
+
model: The model to sample from.
|
64 |
+
x_t: The [N x C x ...] tensor of noisy inputs at time t.
|
65 |
+
t: The current timestep.
|
66 |
+
t_prev: The previous timestep.
|
67 |
+
cond: conditional information.
|
68 |
+
**kwargs: Additional arguments for model inference.
|
69 |
+
|
70 |
+
Returns:
|
71 |
+
a dict containing the following
|
72 |
+
- 'pred_x_prev': x_{t-1}.
|
73 |
+
- 'pred_x_0': a prediction of x_0.
|
74 |
+
"""
|
75 |
+
pred_x_0, pred_eps, pred_v = self._get_model_prediction(model, x_t, t, cond, **kwargs)
|
76 |
+
pred_x_prev = x_t - (t - t_prev) * pred_v
|
77 |
+
return edict({"pred_x_prev": pred_x_prev, "pred_x_0": pred_x_0})
|
78 |
+
|
79 |
+
@torch.no_grad()
|
80 |
+
def sample(
|
81 |
+
self,
|
82 |
+
model,
|
83 |
+
noise,
|
84 |
+
cond: Optional[Any] = None,
|
85 |
+
steps: int = 50,
|
86 |
+
rescale_t: float = 1.0,
|
87 |
+
verbose: bool = True,
|
88 |
+
**kwargs
|
89 |
+
):
|
90 |
+
"""
|
91 |
+
Generate samples from the model using Euler method.
|
92 |
+
|
93 |
+
Args:
|
94 |
+
model: The model to sample from.
|
95 |
+
noise: The initial noise tensor.
|
96 |
+
cond: conditional information.
|
97 |
+
steps: The number of steps to sample.
|
98 |
+
rescale_t: The rescale factor for t.
|
99 |
+
verbose: If True, show a progress bar.
|
100 |
+
**kwargs: Additional arguments for model_inference.
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
a dict containing the following
|
104 |
+
- 'samples': the model samples.
|
105 |
+
- 'pred_x_t': a list of prediction of x_t.
|
106 |
+
- 'pred_x_0': a list of prediction of x_0.
|
107 |
+
"""
|
108 |
+
sample = noise
|
109 |
+
t_seq = np.linspace(1, 0, steps + 1)
|
110 |
+
t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq)
|
111 |
+
t_pairs = list((t_seq[i], t_seq[i + 1]) for i in range(steps))
|
112 |
+
ret = edict({"samples": None, "pred_x_t": [], "pred_x_0": []})
|
113 |
+
for t, t_prev in tqdm(t_pairs, desc="Sampling", disable=not verbose):
|
114 |
+
out = self.sample_once(model, sample, t, t_prev, cond, **kwargs)
|
115 |
+
sample = out.pred_x_prev
|
116 |
+
ret.pred_x_t.append(out.pred_x_prev)
|
117 |
+
ret.pred_x_0.append(out.pred_x_0)
|
118 |
+
ret.samples = sample
|
119 |
+
return ret
|
120 |
+
|
121 |
+
|
122 |
+
class FlowEulerCfgSampler(ClassifierFreeGuidanceSamplerMixin, FlowEulerSampler):
|
123 |
+
"""
|
124 |
+
Generate samples from a flow-matching model using Euler sampling with classifier-free guidance.
|
125 |
+
"""
|
126 |
+
@torch.no_grad()
|
127 |
+
def sample(
|
128 |
+
self,
|
129 |
+
model,
|
130 |
+
noise,
|
131 |
+
cond,
|
132 |
+
neg_cond,
|
133 |
+
steps: int = 50,
|
134 |
+
rescale_t: float = 1.0,
|
135 |
+
cfg_strength: float = 3.0,
|
136 |
+
verbose: bool = True,
|
137 |
+
**kwargs
|
138 |
+
):
|
139 |
+
"""
|
140 |
+
Generate samples from the model using Euler method.
|
141 |
+
|
142 |
+
Args:
|
143 |
+
model: The model to sample from.
|
144 |
+
noise: The initial noise tensor.
|
145 |
+
cond: conditional information.
|
146 |
+
neg_cond: negative conditional information.
|
147 |
+
steps: The number of steps to sample.
|
148 |
+
rescale_t: The rescale factor for t.
|
149 |
+
cfg_strength: The strength of classifier-free guidance.
|
150 |
+
verbose: If True, show a progress bar.
|
151 |
+
**kwargs: Additional arguments for model_inference.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
a dict containing the following
|
155 |
+
- 'samples': the model samples.
|
156 |
+
- 'pred_x_t': a list of prediction of x_t.
|
157 |
+
- 'pred_x_0': a list of prediction of x_0.
|
158 |
+
"""
|
159 |
+
return super().sample(model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, cfg_strength=cfg_strength, **kwargs)
|
160 |
+
|
161 |
+
|
162 |
+
class FlowEulerGuidanceIntervalSampler(GuidanceIntervalSamplerMixin, FlowEulerSampler):
|
163 |
+
"""
|
164 |
+
Generate samples from a flow-matching model using Euler sampling with classifier-free guidance and interval.
|
165 |
+
"""
|
166 |
+
@torch.no_grad()
|
167 |
+
def sample(
|
168 |
+
self,
|
169 |
+
model,
|
170 |
+
noise,
|
171 |
+
cond,
|
172 |
+
neg_cond,
|
173 |
+
steps: int = 50,
|
174 |
+
rescale_t: float = 1.0,
|
175 |
+
cfg_strength: float = 3.0,
|
176 |
+
cfg_interval: Tuple[float, float] = (0.0, 1.0),
|
177 |
+
verbose: bool = True,
|
178 |
+
**kwargs
|
179 |
+
):
|
180 |
+
"""
|
181 |
+
Generate samples from the model using Euler method.
|
182 |
+
|
183 |
+
Args:
|
184 |
+
model: The model to sample from.
|
185 |
+
noise: The initial noise tensor.
|
186 |
+
cond: conditional information.
|
187 |
+
neg_cond: negative conditional information.
|
188 |
+
steps: The number of steps to sample.
|
189 |
+
rescale_t: The rescale factor for t.
|
190 |
+
cfg_strength: The strength of classifier-free guidance.
|
191 |
+
cfg_interval: The interval for classifier-free guidance.
|
192 |
+
verbose: If True, show a progress bar.
|
193 |
+
**kwargs: Additional arguments for model_inference.
|
194 |
+
|
195 |
+
Returns:
|
196 |
+
a dict containing the following
|
197 |
+
- 'samples': the model samples.
|
198 |
+
- 'pred_x_t': a list of prediction of x_t.
|
199 |
+
- 'pred_x_0': a list of prediction of x_0.
|
200 |
+
"""
|
201 |
+
return super().sample(model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, cfg_strength=cfg_strength, cfg_interval=cfg_interval, **kwargs)
|
trellis/pipelines/samplers/guidance_interval_mixin.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
|
3 |
+
|
4 |
+
class GuidanceIntervalSamplerMixin:
|
5 |
+
"""
|
6 |
+
A mixin class for samplers that apply classifier-free guidance with interval.
|
7 |
+
"""
|
8 |
+
|
9 |
+
def _inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, cfg_interval, **kwargs):
|
10 |
+
if cfg_interval[0] <= t <= cfg_interval[1]:
|
11 |
+
pred = super()._inference_model(model, x_t, t, cond, **kwargs)
|
12 |
+
neg_pred = super()._inference_model(model, x_t, t, neg_cond, **kwargs)
|
13 |
+
return (1 + cfg_strength) * pred - cfg_strength * neg_pred
|
14 |
+
else:
|
15 |
+
return super()._inference_model(model, x_t, t, cond, **kwargs)
|
trellis/pipelines/trellis_image_to_3d.py
ADDED
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
from contextlib import contextmanager
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
import numpy as np
|
7 |
+
from torchvision import transforms
|
8 |
+
from PIL import Image
|
9 |
+
import rembg
|
10 |
+
from .base import Pipeline
|
11 |
+
from . import samplers
|
12 |
+
from ..modules import sparse as sp
|
13 |
+
|
14 |
+
|
15 |
+
class TrellisImageTo3DPipeline(Pipeline):
|
16 |
+
"""
|
17 |
+
Pipeline for inferring Trellis image-to-3D models.
|
18 |
+
|
19 |
+
Args:
|
20 |
+
models (dict[str, nn.Module]): The models to use in the pipeline.
|
21 |
+
sparse_structure_sampler (samplers.Sampler): The sampler for the sparse structure.
|
22 |
+
slat_sampler (samplers.Sampler): The sampler for the structured latent.
|
23 |
+
slat_normalization (dict): The normalization parameters for the structured latent.
|
24 |
+
image_cond_model (str): The name of the image conditioning model.
|
25 |
+
"""
|
26 |
+
def __init__(
|
27 |
+
self,
|
28 |
+
models: dict[str, nn.Module] = None,
|
29 |
+
sparse_structure_sampler: samplers.Sampler = None,
|
30 |
+
slat_sampler: samplers.Sampler = None,
|
31 |
+
slat_normalization: dict = None,
|
32 |
+
image_cond_model: str = None,
|
33 |
+
):
|
34 |
+
if models is None:
|
35 |
+
return
|
36 |
+
super().__init__(models)
|
37 |
+
self.sparse_structure_sampler = sparse_structure_sampler
|
38 |
+
self.slat_sampler = slat_sampler
|
39 |
+
self.sparse_structure_sampler_params = {}
|
40 |
+
self.slat_sampler_params = {}
|
41 |
+
self.slat_normalization = slat_normalization
|
42 |
+
self.rembg_session = None
|
43 |
+
self._init_image_cond_model(image_cond_model)
|
44 |
+
|
45 |
+
@staticmethod
|
46 |
+
def from_pretrained(path: str) -> "TrellisImageTo3DPipeline":
|
47 |
+
"""
|
48 |
+
Load a pretrained model.
|
49 |
+
|
50 |
+
Args:
|
51 |
+
path (str): The path to the model. Can be either local path or a Hugging Face repository.
|
52 |
+
"""
|
53 |
+
pipeline = super(TrellisImageTo3DPipeline, TrellisImageTo3DPipeline).from_pretrained(path)
|
54 |
+
new_pipeline = TrellisImageTo3DPipeline()
|
55 |
+
new_pipeline.__dict__ = pipeline.__dict__
|
56 |
+
args = pipeline._pretrained_args
|
57 |
+
|
58 |
+
new_pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args'])
|
59 |
+
new_pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params']
|
60 |
+
|
61 |
+
new_pipeline.slat_sampler = getattr(samplers, args['slat_sampler']['name'])(**args['slat_sampler']['args'])
|
62 |
+
new_pipeline.slat_sampler_params = args['slat_sampler']['params']
|
63 |
+
|
64 |
+
new_pipeline.slat_normalization = args['slat_normalization']
|
65 |
+
|
66 |
+
new_pipeline._init_image_cond_model(args['image_cond_model'])
|
67 |
+
|
68 |
+
return new_pipeline
|
69 |
+
|
70 |
+
def _init_image_cond_model(self, name: str):
|
71 |
+
"""
|
72 |
+
Initialize the image conditioning model.
|
73 |
+
"""
|
74 |
+
dinov2_model = torch.hub.load('facebookresearch/dinov2', name, pretrained=True)
|
75 |
+
dinov2_model.eval()
|
76 |
+
self.models['image_cond_model'] = dinov2_model
|
77 |
+
transform = transforms.Compose([
|
78 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
79 |
+
])
|
80 |
+
self.image_cond_model_transform = transform
|
81 |
+
|
82 |
+
def preprocess_image(self, input: Image.Image) -> Image.Image:
|
83 |
+
"""
|
84 |
+
Preprocess the input image.
|
85 |
+
"""
|
86 |
+
# if has alpha channel, use it directly; otherwise, remove background
|
87 |
+
has_alpha = False
|
88 |
+
if input.mode == 'RGBA':
|
89 |
+
alpha = np.array(input)[:, :, 3]
|
90 |
+
if not np.all(alpha == 255):
|
91 |
+
has_alpha = True
|
92 |
+
if has_alpha:
|
93 |
+
output = input
|
94 |
+
else:
|
95 |
+
input = input.convert('RGB')
|
96 |
+
max_size = max(input.size)
|
97 |
+
scale = min(1, 1024 / max_size)
|
98 |
+
if scale < 1:
|
99 |
+
input = input.resize((int(input.width * scale), int(input.height * scale)), Image.Resampling.LANCZOS)
|
100 |
+
if getattr(self, 'rembg_session', None) is None:
|
101 |
+
self.rembg_session = rembg.new_session('u2net')
|
102 |
+
output = rembg.remove(input, session=self.rembg_session)
|
103 |
+
output_np = np.array(output)
|
104 |
+
alpha = output_np[:, :, 3]
|
105 |
+
bbox = np.argwhere(alpha > 0.8 * 255)
|
106 |
+
bbox = np.min(bbox[:, 1]), np.min(bbox[:, 0]), np.max(bbox[:, 1]), np.max(bbox[:, 0])
|
107 |
+
center = (bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2
|
108 |
+
size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
109 |
+
size = int(size * 1.2)
|
110 |
+
bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2
|
111 |
+
output = output.crop(bbox) # type: ignore
|
112 |
+
output = output.resize((518, 518), Image.Resampling.LANCZOS)
|
113 |
+
output = np.array(output).astype(np.float32) / 255
|
114 |
+
output = output[:, :, :3] * output[:, :, 3:4]
|
115 |
+
output = Image.fromarray((output * 255).astype(np.uint8))
|
116 |
+
return output
|
117 |
+
|
118 |
+
@torch.no_grad()
|
119 |
+
def encode_image(self, image: Union[torch.Tensor, list[Image.Image]]) -> torch.Tensor:
|
120 |
+
"""
|
121 |
+
Encode the image.
|
122 |
+
|
123 |
+
Args:
|
124 |
+
image (Union[torch.Tensor, list[Image.Image]]): The image to encode
|
125 |
+
|
126 |
+
Returns:
|
127 |
+
torch.Tensor: The encoded features.
|
128 |
+
"""
|
129 |
+
if isinstance(image, torch.Tensor):
|
130 |
+
assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)"
|
131 |
+
elif isinstance(image, list):
|
132 |
+
assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images"
|
133 |
+
image = [i.resize((518, 518), Image.LANCZOS) for i in image]
|
134 |
+
image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image]
|
135 |
+
image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image]
|
136 |
+
image = torch.stack(image).to(self.device)
|
137 |
+
else:
|
138 |
+
raise ValueError(f"Unsupported type of image: {type(image)}")
|
139 |
+
|
140 |
+
image = self.image_cond_model_transform(image).to(self.device)
|
141 |
+
features = self.models['image_cond_model'](image, is_training=True)['x_prenorm']
|
142 |
+
patchtokens = F.layer_norm(features, features.shape[-1:])
|
143 |
+
return patchtokens
|
144 |
+
|
145 |
+
def get_cond(self, image: Union[torch.Tensor, list[Image.Image]]) -> dict:
|
146 |
+
"""
|
147 |
+
Get the conditioning information for the model.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
image (Union[torch.Tensor, list[Image.Image]]): The image prompts.
|
151 |
+
|
152 |
+
Returns:
|
153 |
+
dict: The conditioning information
|
154 |
+
"""
|
155 |
+
cond = self.encode_image(image)
|
156 |
+
neg_cond = torch.zeros_like(cond)
|
157 |
+
return {
|
158 |
+
'cond': cond,
|
159 |
+
'neg_cond': neg_cond,
|
160 |
+
}
|
161 |
+
|
162 |
+
def sample_sparse_structure(
|
163 |
+
self,
|
164 |
+
cond: dict,
|
165 |
+
num_samples: int = 1,
|
166 |
+
sampler_params: dict = {},
|
167 |
+
) -> torch.Tensor:
|
168 |
+
"""
|
169 |
+
Sample sparse structures with the given conditioning.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
cond (dict): The conditioning information.
|
173 |
+
num_samples (int): The number of samples to generate.
|
174 |
+
sampler_params (dict): Additional parameters for the sampler.
|
175 |
+
"""
|
176 |
+
# Sample occupancy latent
|
177 |
+
flow_model = self.models['sparse_structure_flow_model']
|
178 |
+
reso = flow_model.resolution
|
179 |
+
noise = torch.randn(num_samples, flow_model.in_channels, reso, reso, reso).to(self.device)
|
180 |
+
sampler_params = {**self.sparse_structure_sampler_params, **sampler_params}
|
181 |
+
z_s = self.sparse_structure_sampler.sample(
|
182 |
+
flow_model,
|
183 |
+
noise,
|
184 |
+
**cond,
|
185 |
+
**sampler_params,
|
186 |
+
verbose=True
|
187 |
+
).samples
|
188 |
+
|
189 |
+
# Decode occupancy latent
|
190 |
+
decoder = self.models['sparse_structure_decoder']
|
191 |
+
coords = torch.argwhere(decoder(z_s)>0)[:, [0, 2, 3, 4]].int()
|
192 |
+
|
193 |
+
return coords
|
194 |
+
|
195 |
+
def decode_slat(
|
196 |
+
self,
|
197 |
+
slat: sp.SparseTensor,
|
198 |
+
formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],
|
199 |
+
) -> dict:
|
200 |
+
"""
|
201 |
+
Decode the structured latent.
|
202 |
+
|
203 |
+
Args:
|
204 |
+
slat (sp.SparseTensor): The structured latent.
|
205 |
+
formats (List[str]): The formats to decode the structured latent to.
|
206 |
+
|
207 |
+
Returns:
|
208 |
+
dict: The decoded structured latent.
|
209 |
+
"""
|
210 |
+
ret = {}
|
211 |
+
if 'mesh' in formats:
|
212 |
+
ret['mesh'] = self.models['slat_decoder_mesh'](slat)
|
213 |
+
if 'gaussian' in formats:
|
214 |
+
ret['gaussian'] = self.models['slat_decoder_gs'](slat)
|
215 |
+
if 'radiance_field' in formats:
|
216 |
+
ret['radiance_field'] = self.models['slat_decoder_rf'](slat)
|
217 |
+
return ret
|
218 |
+
|
219 |
+
def sample_slat(
|
220 |
+
self,
|
221 |
+
cond: dict,
|
222 |
+
coords: torch.Tensor,
|
223 |
+
sampler_params: dict = {},
|
224 |
+
) -> sp.SparseTensor:
|
225 |
+
"""
|
226 |
+
Sample structured latent with the given conditioning.
|
227 |
+
|
228 |
+
Args:
|
229 |
+
cond (dict): The conditioning information.
|
230 |
+
coords (torch.Tensor): The coordinates of the sparse structure.
|
231 |
+
sampler_params (dict): Additional parameters for the sampler.
|
232 |
+
"""
|
233 |
+
# Sample structured latent
|
234 |
+
flow_model = self.models['slat_flow_model']
|
235 |
+
noise = sp.SparseTensor(
|
236 |
+
feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device),
|
237 |
+
coords=coords,
|
238 |
+
)
|
239 |
+
sampler_params = {**self.slat_sampler_params, **sampler_params}
|
240 |
+
slat = self.slat_sampler.sample(
|
241 |
+
flow_model,
|
242 |
+
noise,
|
243 |
+
**cond,
|
244 |
+
**sampler_params,
|
245 |
+
verbose=True
|
246 |
+
).samples
|
247 |
+
|
248 |
+
std = torch.tensor(self.slat_normalization['std'])[None].to(slat.device)
|
249 |
+
mean = torch.tensor(self.slat_normalization['mean'])[None].to(slat.device)
|
250 |
+
slat = slat * std + mean
|
251 |
+
|
252 |
+
return slat
|
253 |
+
|
254 |
+
@torch.no_grad()
|
255 |
+
def run(
|
256 |
+
self,
|
257 |
+
image: Image.Image,
|
258 |
+
num_samples: int = 1,
|
259 |
+
seed: int = 42,
|
260 |
+
sparse_structure_sampler_params: dict = {},
|
261 |
+
slat_sampler_params: dict = {},
|
262 |
+
formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],
|
263 |
+
preprocess_image: bool = True,
|
264 |
+
) -> dict:
|
265 |
+
"""
|
266 |
+
Run the pipeline.
|
267 |
+
|
268 |
+
Args:
|
269 |
+
image (Image.Image): The image prompt.
|
270 |
+
num_samples (int): The number of samples to generate.
|
271 |
+
seed (int): The random seed.
|
272 |
+
sparse_structure_sampler_params (dict): Additional parameters for the sparse structure sampler.
|
273 |
+
slat_sampler_params (dict): Additional parameters for the structured latent sampler.
|
274 |
+
formats (List[str]): The formats to decode the structured latent to.
|
275 |
+
preprocess_image (bool): Whether to preprocess the image.
|
276 |
+
"""
|
277 |
+
if preprocess_image:
|
278 |
+
image = self.preprocess_image(image)
|
279 |
+
cond = self.get_cond([image])
|
280 |
+
torch.manual_seed(seed)
|
281 |
+
coords = self.sample_sparse_structure(cond, num_samples, sparse_structure_sampler_params)
|
282 |
+
slat = self.sample_slat(cond, coords, slat_sampler_params)
|
283 |
+
return self.decode_slat(slat, formats)
|
284 |
+
|
285 |
+
@contextmanager
|
286 |
+
def inject_sampler_multi_image(
|
287 |
+
self,
|
288 |
+
sampler_name: str,
|
289 |
+
num_images: int,
|
290 |
+
num_steps: int,
|
291 |
+
mode: Literal['stochastic', 'multidiffusion'] = 'stochastic',
|
292 |
+
):
|
293 |
+
"""
|
294 |
+
Inject a sampler with multiple images as condition.
|
295 |
+
|
296 |
+
Args:
|
297 |
+
sampler_name (str): The name of the sampler to inject.
|
298 |
+
num_images (int): The number of images to condition on.
|
299 |
+
num_steps (int): The number of steps to run the sampler for.
|
300 |
+
"""
|
301 |
+
sampler = getattr(self, sampler_name)
|
302 |
+
setattr(sampler, f'_old_inference_model', sampler._inference_model)
|
303 |
+
|
304 |
+
if mode == 'stochastic':
|
305 |
+
if num_images > num_steps:
|
306 |
+
print(f"\033[93mWarning: number of conditioning images is greater than number of steps for {sampler_name}. "
|
307 |
+
"This may lead to performance degradation.\033[0m")
|
308 |
+
|
309 |
+
cond_indices = (np.arange(num_steps) % num_images).tolist()
|
310 |
+
def _new_inference_model(self, model, x_t, t, cond, **kwargs):
|
311 |
+
cond_idx = cond_indices.pop(0)
|
312 |
+
cond_i = cond[cond_idx:cond_idx+1]
|
313 |
+
return self._old_inference_model(model, x_t, t, cond=cond_i, **kwargs)
|
314 |
+
|
315 |
+
elif mode =='multidiffusion':
|
316 |
+
from .samplers import FlowEulerSampler
|
317 |
+
def _new_inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, cfg_interval, **kwargs):
|
318 |
+
if cfg_interval[0] <= t <= cfg_interval[1]:
|
319 |
+
preds = []
|
320 |
+
for i in range(len(cond)):
|
321 |
+
preds.append(FlowEulerSampler._inference_model(self, model, x_t, t, cond[i:i+1], **kwargs))
|
322 |
+
pred = sum(preds) / len(preds)
|
323 |
+
neg_pred = FlowEulerSampler._inference_model(self, model, x_t, t, neg_cond, **kwargs)
|
324 |
+
return (1 + cfg_strength) * pred - cfg_strength * neg_pred
|
325 |
+
else:
|
326 |
+
preds = []
|
327 |
+
for i in range(len(cond)):
|
328 |
+
preds.append(FlowEulerSampler._inference_model(self, model, x_t, t, cond[i:i+1], **kwargs))
|
329 |
+
pred = sum(preds) / len(preds)
|
330 |
+
return pred
|
331 |
+
|
332 |
+
else:
|
333 |
+
raise ValueError(f"Unsupported mode: {mode}")
|
334 |
+
|
335 |
+
sampler._inference_model = _new_inference_model.__get__(sampler, type(sampler))
|
336 |
+
|
337 |
+
yield
|
338 |
+
|
339 |
+
sampler._inference_model = sampler._old_inference_model
|
340 |
+
delattr(sampler, f'_old_inference_model')
|
341 |
+
|
342 |
+
@torch.no_grad()
|
343 |
+
def run_multi_image(
|
344 |
+
self,
|
345 |
+
images: List[Image.Image],
|
346 |
+
num_samples: int = 1,
|
347 |
+
seed: int = 42,
|
348 |
+
sparse_structure_sampler_params: dict = {},
|
349 |
+
slat_sampler_params: dict = {},
|
350 |
+
formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],
|
351 |
+
preprocess_image: bool = True,
|
352 |
+
mode: Literal['stochastic', 'multidiffusion'] = 'stochastic',
|
353 |
+
) -> dict:
|
354 |
+
"""
|
355 |
+
Run the pipeline with multiple images as condition
|
356 |
+
|
357 |
+
Args:
|
358 |
+
images (List[Image.Image]): The multi-view images of the assets
|
359 |
+
num_samples (int): The number of samples to generate.
|
360 |
+
sparse_structure_sampler_params (dict): Additional parameters for the sparse structure sampler.
|
361 |
+
slat_sampler_params (dict): Additional parameters for the structured latent sampler.
|
362 |
+
preprocess_image (bool): Whether to preprocess the image.
|
363 |
+
"""
|
364 |
+
if preprocess_image:
|
365 |
+
images = [self.preprocess_image(image) for image in images]
|
366 |
+
cond = self.get_cond(images)
|
367 |
+
cond['neg_cond'] = cond['neg_cond'][:1]
|
368 |
+
torch.manual_seed(seed)
|
369 |
+
ss_steps = {**self.sparse_structure_sampler_params, **sparse_structure_sampler_params}.get('steps')
|
370 |
+
with self.inject_sampler_multi_image('sparse_structure_sampler', len(images), ss_steps, mode=mode):
|
371 |
+
coords = self.sample_sparse_structure(cond, num_samples, sparse_structure_sampler_params)
|
372 |
+
slat_steps = {**self.slat_sampler_params, **slat_sampler_params}.get('steps')
|
373 |
+
with self.inject_sampler_multi_image('slat_sampler', len(images), slat_steps, mode=mode):
|
374 |
+
slat = self.sample_slat(cond, coords, slat_sampler_params)
|
375 |
+
return self.decode_slat(slat, formats)
|
trellis/pipelines/trellis_text_to_3d.py
ADDED
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import *
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import numpy as np
|
5 |
+
from transformers import CLIPTextModel, AutoTokenizer
|
6 |
+
import open3d as o3d
|
7 |
+
from .base import Pipeline
|
8 |
+
from . import samplers
|
9 |
+
from ..modules import sparse as sp
|
10 |
+
|
11 |
+
|
12 |
+
class TrellisTextTo3DPipeline(Pipeline):
|
13 |
+
"""
|
14 |
+
Pipeline for inferring Trellis text-to-3D models.
|
15 |
+
|
16 |
+
Args:
|
17 |
+
models (dict[str, nn.Module]): The models to use in the pipeline.
|
18 |
+
sparse_structure_sampler (samplers.Sampler): The sampler for the sparse structure.
|
19 |
+
slat_sampler (samplers.Sampler): The sampler for the structured latent.
|
20 |
+
slat_normalization (dict): The normalization parameters for the structured latent.
|
21 |
+
text_cond_model (str): The name of the text conditioning model.
|
22 |
+
"""
|
23 |
+
def __init__(
|
24 |
+
self,
|
25 |
+
models: dict[str, nn.Module] = None,
|
26 |
+
sparse_structure_sampler: samplers.Sampler = None,
|
27 |
+
slat_sampler: samplers.Sampler = None,
|
28 |
+
slat_normalization: dict = None,
|
29 |
+
text_cond_model: str = None,
|
30 |
+
):
|
31 |
+
if models is None:
|
32 |
+
return
|
33 |
+
super().__init__(models)
|
34 |
+
self.sparse_structure_sampler = sparse_structure_sampler
|
35 |
+
self.slat_sampler = slat_sampler
|
36 |
+
self.sparse_structure_sampler_params = {}
|
37 |
+
self.slat_sampler_params = {}
|
38 |
+
self.slat_normalization = slat_normalization
|
39 |
+
self._init_text_cond_model(text_cond_model)
|
40 |
+
|
41 |
+
@staticmethod
|
42 |
+
def from_pretrained(path: str) -> "TrellisTextTo3DPipeline":
|
43 |
+
"""
|
44 |
+
Load a pretrained model.
|
45 |
+
|
46 |
+
Args:
|
47 |
+
path (str): The path to the model. Can be either local path or a Hugging Face repository.
|
48 |
+
"""
|
49 |
+
pipeline = super(TrellisTextTo3DPipeline, TrellisTextTo3DPipeline).from_pretrained(path)
|
50 |
+
new_pipeline = TrellisTextTo3DPipeline()
|
51 |
+
new_pipeline.__dict__ = pipeline.__dict__
|
52 |
+
args = pipeline._pretrained_args
|
53 |
+
|
54 |
+
new_pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args'])
|
55 |
+
new_pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params']
|
56 |
+
|
57 |
+
new_pipeline.slat_sampler = getattr(samplers, args['slat_sampler']['name'])(**args['slat_sampler']['args'])
|
58 |
+
new_pipeline.slat_sampler_params = args['slat_sampler']['params']
|
59 |
+
|
60 |
+
new_pipeline.slat_normalization = args['slat_normalization']
|
61 |
+
|
62 |
+
new_pipeline._init_text_cond_model(args['text_cond_model'])
|
63 |
+
|
64 |
+
return new_pipeline
|
65 |
+
|
66 |
+
def _init_text_cond_model(self, name: str):
|
67 |
+
"""
|
68 |
+
Initialize the text conditioning model.
|
69 |
+
"""
|
70 |
+
# load model
|
71 |
+
model = CLIPTextModel.from_pretrained(name)
|
72 |
+
tokenizer = AutoTokenizer.from_pretrained(name)
|
73 |
+
model.eval()
|
74 |
+
model = model.cuda()
|
75 |
+
self.text_cond_model = {
|
76 |
+
'model': model,
|
77 |
+
'tokenizer': tokenizer,
|
78 |
+
}
|
79 |
+
self.text_cond_model['null_cond'] = self.encode_text([''])
|
80 |
+
|
81 |
+
@torch.no_grad()
|
82 |
+
def encode_text(self, text: List[str]) -> torch.Tensor:
|
83 |
+
"""
|
84 |
+
Encode the text.
|
85 |
+
"""
|
86 |
+
assert isinstance(text, list) and all(isinstance(t, str) for t in text), "text must be a list of strings"
|
87 |
+
encoding = self.text_cond_model['tokenizer'](text, max_length=77, padding='max_length', truncation=True, return_tensors='pt')
|
88 |
+
tokens = encoding['input_ids'].cuda()
|
89 |
+
embeddings = self.text_cond_model['model'](input_ids=tokens).last_hidden_state
|
90 |
+
|
91 |
+
return embeddings
|
92 |
+
|
93 |
+
def get_cond(self, prompt: List[str]) -> dict:
|
94 |
+
"""
|
95 |
+
Get the conditioning information for the model.
|
96 |
+
|
97 |
+
Args:
|
98 |
+
prompt (List[str]): The text prompt.
|
99 |
+
|
100 |
+
Returns:
|
101 |
+
dict: The conditioning information
|
102 |
+
"""
|
103 |
+
cond = self.encode_text(prompt)
|
104 |
+
neg_cond = self.text_cond_model['null_cond']
|
105 |
+
return {
|
106 |
+
'cond': cond,
|
107 |
+
'neg_cond': neg_cond,
|
108 |
+
}
|
109 |
+
|
110 |
+
def sample_sparse_structure(
|
111 |
+
self,
|
112 |
+
cond: dict,
|
113 |
+
num_samples: int = 1,
|
114 |
+
sampler_params: dict = {},
|
115 |
+
) -> torch.Tensor:
|
116 |
+
"""
|
117 |
+
Sample sparse structures with the given conditioning.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
cond (dict): The conditioning information.
|
121 |
+
num_samples (int): The number of samples to generate.
|
122 |
+
sampler_params (dict): Additional parameters for the sampler.
|
123 |
+
"""
|
124 |
+
# Sample occupancy latent
|
125 |
+
flow_model = self.models['sparse_structure_flow_model']
|
126 |
+
reso = flow_model.resolution
|
127 |
+
noise = torch.randn(num_samples, flow_model.in_channels, reso, reso, reso).to(self.device)
|
128 |
+
sampler_params = {**self.sparse_structure_sampler_params, **sampler_params}
|
129 |
+
z_s = self.sparse_structure_sampler.sample(
|
130 |
+
flow_model,
|
131 |
+
noise,
|
132 |
+
**cond,
|
133 |
+
**sampler_params,
|
134 |
+
verbose=True
|
135 |
+
).samples
|
136 |
+
|
137 |
+
# Decode occupancy latent
|
138 |
+
decoder = self.models['sparse_structure_decoder']
|
139 |
+
coords = torch.argwhere(decoder(z_s)>0)[:, [0, 2, 3, 4]].int()
|
140 |
+
|
141 |
+
return coords
|
142 |
+
|
143 |
+
def decode_slat(
|
144 |
+
self,
|
145 |
+
slat: sp.SparseTensor,
|
146 |
+
formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],
|
147 |
+
) -> dict:
|
148 |
+
"""
|
149 |
+
Decode the structured latent.
|
150 |
+
|
151 |
+
Args:
|
152 |
+
slat (sp.SparseTensor): The structured latent.
|
153 |
+
formats (List[str]): The formats to decode the structured latent to.
|
154 |
+
|
155 |
+
Returns:
|
156 |
+
dict: The decoded structured latent.
|
157 |
+
"""
|
158 |
+
ret = {}
|
159 |
+
if 'mesh' in formats:
|
160 |
+
ret['mesh'] = self.models['slat_decoder_mesh'](slat)
|
161 |
+
if 'gaussian' in formats:
|
162 |
+
ret['gaussian'] = self.models['slat_decoder_gs'](slat)
|
163 |
+
if 'radiance_field' in formats:
|
164 |
+
ret['radiance_field'] = self.models['slat_decoder_rf'](slat)
|
165 |
+
return ret
|
166 |
+
|
167 |
+
def sample_slat(
|
168 |
+
self,
|
169 |
+
cond: dict,
|
170 |
+
coords: torch.Tensor,
|
171 |
+
sampler_params: dict = {},
|
172 |
+
) -> sp.SparseTensor:
|
173 |
+
"""
|
174 |
+
Sample structured latent with the given conditioning.
|
175 |
+
|
176 |
+
Args:
|
177 |
+
cond (dict): The conditioning information.
|
178 |
+
coords (torch.Tensor): The coordinates of the sparse structure.
|
179 |
+
sampler_params (dict): Additional parameters for the sampler.
|
180 |
+
"""
|
181 |
+
# Sample structured latent
|
182 |
+
flow_model = self.models['slat_flow_model']
|
183 |
+
noise = sp.SparseTensor(
|
184 |
+
feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device),
|
185 |
+
coords=coords,
|
186 |
+
)
|
187 |
+
sampler_params = {**self.slat_sampler_params, **sampler_params}
|
188 |
+
slat = self.slat_sampler.sample(
|
189 |
+
flow_model,
|
190 |
+
noise,
|
191 |
+
**cond,
|
192 |
+
**sampler_params,
|
193 |
+
verbose=True
|
194 |
+
).samples
|
195 |
+
|
196 |
+
std = torch.tensor(self.slat_normalization['std'])[None].to(slat.device)
|
197 |
+
mean = torch.tensor(self.slat_normalization['mean'])[None].to(slat.device)
|
198 |
+
slat = slat * std + mean
|
199 |
+
|
200 |
+
return slat
|
201 |
+
|
202 |
+
@torch.no_grad()
|
203 |
+
def run(
|
204 |
+
self,
|
205 |
+
prompt: str,
|
206 |
+
num_samples: int = 1,
|
207 |
+
seed: int = 42,
|
208 |
+
sparse_structure_sampler_params: dict = {},
|
209 |
+
slat_sampler_params: dict = {},
|
210 |
+
formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],
|
211 |
+
) -> dict:
|
212 |
+
"""
|
213 |
+
Run the pipeline.
|
214 |
+
|
215 |
+
Args:
|
216 |
+
prompt (str): The text prompt.
|
217 |
+
num_samples (int): The number of samples to generate.
|
218 |
+
seed (int): The random seed.
|
219 |
+
sparse_structure_sampler_params (dict): Additional parameters for the sparse structure sampler.
|
220 |
+
slat_sampler_params (dict): Additional parameters for the structured latent sampler.
|
221 |
+
formats (List[str]): The formats to decode the structured latent to.
|
222 |
+
"""
|
223 |
+
cond = self.get_cond([prompt])
|
224 |
+
torch.manual_seed(seed)
|
225 |
+
coords = self.sample_sparse_structure(cond, num_samples, sparse_structure_sampler_params)
|
226 |
+
slat = self.sample_slat(cond, coords, slat_sampler_params)
|
227 |
+
return self.decode_slat(slat, formats)
|
228 |
+
|
229 |
+
def voxelize(self, mesh: o3d.geometry.TriangleMesh) -> torch.Tensor:
|
230 |
+
"""
|
231 |
+
Voxelize a mesh.
|
232 |
+
|
233 |
+
Args:
|
234 |
+
mesh (o3d.geometry.TriangleMesh): The mesh to voxelize.
|
235 |
+
sha256 (str): The SHA256 hash of the mesh.
|
236 |
+
output_dir (str): The output directory.
|
237 |
+
"""
|
238 |
+
vertices = np.asarray(mesh.vertices)
|
239 |
+
aabb = np.stack([vertices.min(0), vertices.max(0)])
|
240 |
+
center = (aabb[0] + aabb[1]) / 2
|
241 |
+
scale = (aabb[1] - aabb[0]).max()
|
242 |
+
vertices = (vertices - center) / scale
|
243 |
+
vertices = np.clip(vertices, -0.5 + 1e-6, 0.5 - 1e-6)
|
244 |
+
mesh.vertices = o3d.utility.Vector3dVector(vertices)
|
245 |
+
voxel_grid = o3d.geometry.VoxelGrid.create_from_triangle_mesh_within_bounds(mesh, voxel_size=1/64, min_bound=(-0.5, -0.5, -0.5), max_bound=(0.5, 0.5, 0.5))
|
246 |
+
vertices = np.array([voxel.grid_index for voxel in voxel_grid.get_voxels()])
|
247 |
+
return torch.tensor(vertices).int().cuda()
|
248 |
+
|
249 |
+
@torch.no_grad()
|
250 |
+
def run_variant(
|
251 |
+
self,
|
252 |
+
mesh: o3d.geometry.TriangleMesh,
|
253 |
+
prompt: str,
|
254 |
+
num_samples: int = 1,
|
255 |
+
seed: int = 42,
|
256 |
+
slat_sampler_params: dict = {},
|
257 |
+
formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],
|
258 |
+
) -> dict:
|
259 |
+
"""
|
260 |
+
Run the pipeline for making variants of an asset.
|
261 |
+
|
262 |
+
Args:
|
263 |
+
mesh (o3d.geometry.TriangleMesh): The base mesh.
|
264 |
+
prompt (str): The text prompt.
|
265 |
+
num_samples (int): The number of samples to generate.
|
266 |
+
seed (int): The random seed
|
267 |
+
slat_sampler_params (dict): Additional parameters for the structured latent sampler.
|
268 |
+
formats (List[str]): The formats to decode the structured latent to.
|
269 |
+
"""
|
270 |
+
cond = self.get_cond([prompt])
|
271 |
+
coords = self.voxelize(mesh)
|
272 |
+
coords = torch.cat([
|
273 |
+
torch.arange(num_samples).repeat_interleave(coords.shape[0], 0)[:, None].int().cuda(),
|
274 |
+
coords.repeat(num_samples, 1)
|
275 |
+
], 1)
|
276 |
+
torch.manual_seed(seed)
|
277 |
+
slat = self.sample_slat(cond, coords, slat_sampler_params)
|
278 |
+
return self.decode_slat(slat, formats)
|