opsiclear-admin commited on
Commit
b8db3e2
·
verified ·
1 Parent(s): 7a919c6

Add trellis2

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. trellis2/__init__.py +6 -0
  2. trellis2/__pycache__/__init__.cpython-311.pyc +0 -0
  3. trellis2/datasets/__init__.py +46 -0
  4. trellis2/datasets/components.py +192 -0
  5. trellis2/datasets/flexi_dual_grid.py +173 -0
  6. trellis2/datasets/sparse_structure_latent.py +160 -0
  7. trellis2/datasets/sparse_voxel_pbr.py +298 -0
  8. trellis2/datasets/structured_latent.py +210 -0
  9. trellis2/datasets/structured_latent_shape.py +96 -0
  10. trellis2/datasets/structured_latent_svpbr.py +290 -0
  11. trellis2/models/__init__.py +78 -0
  12. trellis2/models/__pycache__/__init__.cpython-311.pyc +0 -0
  13. trellis2/models/__pycache__/sparse_elastic_mixin.cpython-311.pyc +0 -0
  14. trellis2/models/__pycache__/sparse_structure_flow.cpython-311.pyc +0 -0
  15. trellis2/models/__pycache__/sparse_structure_vae.cpython-311.pyc +0 -0
  16. trellis2/models/__pycache__/structured_latent_flow.cpython-311.pyc +0 -0
  17. trellis2/models/sc_vaes/__pycache__/fdg_vae.cpython-311.pyc +0 -0
  18. trellis2/models/sc_vaes/__pycache__/sparse_unet_vae.cpython-311.pyc +0 -0
  19. trellis2/models/sc_vaes/fdg_vae.py +110 -0
  20. trellis2/models/sc_vaes/sparse_unet_vae.py +522 -0
  21. trellis2/models/sparse_elastic_mixin.py +24 -0
  22. trellis2/models/sparse_structure_flow.py +247 -0
  23. trellis2/models/sparse_structure_vae.py +306 -0
  24. trellis2/models/structured_latent_flow.py +207 -0
  25. trellis2/modules/__pycache__/image_feature_extractor.cpython-311.pyc +0 -0
  26. trellis2/modules/__pycache__/norm.cpython-311.pyc +0 -0
  27. trellis2/modules/__pycache__/spatial.cpython-311.pyc +0 -0
  28. trellis2/modules/__pycache__/utils.cpython-311.pyc +0 -0
  29. trellis2/modules/attention/__init__.py +3 -0
  30. trellis2/modules/attention/__pycache__/__init__.cpython-311.pyc +0 -0
  31. trellis2/modules/attention/__pycache__/config.cpython-311.pyc +0 -0
  32. trellis2/modules/attention/__pycache__/full_attn.cpython-311.pyc +0 -0
  33. trellis2/modules/attention/__pycache__/modules.cpython-311.pyc +0 -0
  34. trellis2/modules/attention/__pycache__/rope.cpython-311.pyc +0 -0
  35. trellis2/modules/attention/config.py +34 -0
  36. trellis2/modules/attention/full_attn.py +145 -0
  37. trellis2/modules/attention/modules.py +102 -0
  38. trellis2/modules/attention/rope.py +48 -0
  39. trellis2/modules/image_feature_extractor.py +123 -0
  40. trellis2/modules/norm.py +32 -0
  41. trellis2/modules/sparse/__init__.py +69 -0
  42. trellis2/modules/sparse/__pycache__/__init__.cpython-311.pyc +0 -0
  43. trellis2/modules/sparse/__pycache__/basic.cpython-311.pyc +0 -0
  44. trellis2/modules/sparse/__pycache__/config.cpython-311.pyc +0 -0
  45. trellis2/modules/sparse/__pycache__/linear.cpython-311.pyc +0 -0
  46. trellis2/modules/sparse/__pycache__/nonlinearity.cpython-311.pyc +0 -0
  47. trellis2/modules/sparse/attention/__init__.py +3 -0
  48. trellis2/modules/sparse/attention/__pycache__/__init__.cpython-311.pyc +0 -0
  49. trellis2/modules/sparse/attention/__pycache__/full_attn.cpython-311.pyc +0 -0
  50. trellis2/modules/sparse/attention/__pycache__/modules.cpython-311.pyc +0 -0
trellis2/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from . import models
2
+ from . import modules
3
+ from . import pipelines
4
+ from . import renderers
5
+ from . import representations
6
+ from . import utils
trellis2/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (484 Bytes). View file
 
trellis2/datasets/__init__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ __attributes = {
4
+ 'FlexiDualGridDataset': 'flexi_dual_grid',
5
+ 'SparseVoxelPbrDataset':'sparse_voxel_pbr',
6
+
7
+ 'SparseStructureLatent': 'sparse_structure_latent',
8
+ 'TextConditionedSparseStructureLatent': 'sparse_structure_latent',
9
+ 'ImageConditionedSparseStructureLatent': 'sparse_structure_latent',
10
+
11
+ 'SLat': 'structured_latent',
12
+ 'ImageConditionedSLat': 'structured_latent',
13
+ 'SLatShape': 'structured_latent_shape',
14
+ 'ImageConditionedSLatShape': 'structured_latent_shape',
15
+ 'SLatPbr': 'structured_latent_svpbr',
16
+ 'ImageConditionedSLatPbr': 'structured_latent_svpbr',
17
+ }
18
+
19
+ __submodules = []
20
+
21
+ __all__ = list(__attributes.keys()) + __submodules
22
+
23
+ def __getattr__(name):
24
+ if name not in globals():
25
+ if name in __attributes:
26
+ module_name = __attributes[name]
27
+ module = importlib.import_module(f".{module_name}", __name__)
28
+ globals()[name] = getattr(module, name)
29
+ elif name in __submodules:
30
+ module = importlib.import_module(f".{name}", __name__)
31
+ globals()[name] = module
32
+ else:
33
+ raise AttributeError(f"module {__name__} has no attribute {name}")
34
+ return globals()[name]
35
+
36
+
37
+ # For Pylance
38
+ if __name__ == '__main__':
39
+ from .flexi_dual_grid import FlexiDualGridDataset
40
+ from .sparse_voxel_pbr import SparseVoxelPbrDataset
41
+
42
+ from .sparse_structure_latent import SparseStructureLatent, ImageConditionedSparseStructureLatent
43
+ from .structured_latent import SLat, ImageConditionedSLat
44
+ from .structured_latent_shape import SLatShape, ImageConditionedSLatShape
45
+ from .structured_latent_svpbr import SLatPbr, ImageConditionedSLatPbr
46
+
trellis2/datasets/components.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import json
3
+ from abc import abstractmethod
4
+ import os
5
+ import json
6
+ import torch
7
+ import numpy as np
8
+ import pandas as pd
9
+ from PIL import Image
10
+ from torch.utils.data import Dataset
11
+
12
+
13
+ class StandardDatasetBase(Dataset):
14
+ """
15
+ Base class for standard datasets.
16
+
17
+ Args:
18
+ roots (str): paths to the dataset
19
+ """
20
+
21
+ def __init__(self,
22
+ roots: str,
23
+ ):
24
+ super().__init__()
25
+ try:
26
+ self.roots = json.loads(roots)
27
+ root_type = 'obj'
28
+ except:
29
+ self.roots = roots.split(',')
30
+ root_type = 'list'
31
+ self.instances = []
32
+ self.metadata = pd.DataFrame()
33
+
34
+ self._stats = {}
35
+ if root_type == 'obj':
36
+ for key, root in self.roots.items():
37
+ self._stats[key] = {}
38
+ metadata = pd.DataFrame(columns=['sha256']).set_index('sha256')
39
+ for _, r in root.items():
40
+ metadata = metadata.combine_first(pd.read_csv(os.path.join(r, 'metadata.csv')).set_index('sha256'))
41
+ self._stats[key]['Total'] = len(metadata)
42
+ metadata, stats = self.filter_metadata(metadata)
43
+ self._stats[key].update(stats)
44
+ self.instances.extend([(root, sha256) for sha256 in metadata.index.values])
45
+ self.metadata = pd.concat([self.metadata, metadata])
46
+ else:
47
+ for root in self.roots:
48
+ key = os.path.basename(root)
49
+ self._stats[key] = {}
50
+ metadata = pd.read_csv(os.path.join(root, 'metadata.csv'))
51
+ self._stats[key]['Total'] = len(metadata)
52
+ metadata, stats = self.filter_metadata(metadata)
53
+ self._stats[key].update(stats)
54
+ self.instances.extend([(root, sha256) for sha256 in metadata['sha256'].values])
55
+ metadata.set_index('sha256', inplace=True)
56
+ self.metadata = pd.concat([self.metadata, metadata])
57
+
58
+ @abstractmethod
59
+ def filter_metadata(self, metadata: pd.DataFrame) -> Tuple[pd.DataFrame, Dict[str, int]]:
60
+ pass
61
+
62
+ @abstractmethod
63
+ def get_instance(self, root, instance: str) -> Dict[str, Any]:
64
+ pass
65
+
66
+ def __len__(self):
67
+ return len(self.instances)
68
+
69
+ def __getitem__(self, index) -> Dict[str, Any]:
70
+ try:
71
+ root, instance = self.instances[index]
72
+ return self.get_instance(root, instance)
73
+ except Exception as e:
74
+ print(f'Error loading {instance}: {e}')
75
+ return self.__getitem__(np.random.randint(0, len(self)))
76
+
77
+ def __str__(self):
78
+ lines = []
79
+ lines.append(self.__class__.__name__)
80
+ lines.append(f' - Total instances: {len(self)}')
81
+ lines.append(f' - Sources:')
82
+ for key, stats in self._stats.items():
83
+ lines.append(f' - {key}:')
84
+ for k, v in stats.items():
85
+ lines.append(f' - {k}: {v}')
86
+ return '\n'.join(lines)
87
+
88
+
89
+ class ImageConditionedMixin:
90
+ def __init__(self, roots, *, image_size=518, **kwargs):
91
+ self.image_size = image_size
92
+ super().__init__(roots, **kwargs)
93
+
94
+ def filter_metadata(self, metadata):
95
+ metadata, stats = super().filter_metadata(metadata)
96
+ metadata = metadata[metadata['cond_rendered'].notna()]
97
+ stats['Cond rendered'] = len(metadata)
98
+ return metadata, stats
99
+
100
+ def get_instance(self, root, instance):
101
+ pack = super().get_instance(root, instance)
102
+
103
+ image_root = os.path.join(root['render_cond'], instance)
104
+ with open(os.path.join(image_root, 'transforms.json')) as f:
105
+ metadata = json.load(f)
106
+ n_views = len(metadata['frames'])
107
+ view = np.random.randint(n_views)
108
+ metadata = metadata['frames'][view]
109
+
110
+ image_path = os.path.join(image_root, metadata['file_path'])
111
+ image = Image.open(image_path)
112
+
113
+ alpha = np.array(image.getchannel(3))
114
+ bbox = np.array(alpha).nonzero()
115
+ bbox = [bbox[1].min(), bbox[0].min(), bbox[1].max(), bbox[0].max()]
116
+ center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
117
+ hsize = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 2
118
+ aug_hsize = hsize
119
+ aug_center_offset = [0, 0]
120
+ aug_center = [center[0] + aug_center_offset[0], center[1] + aug_center_offset[1]]
121
+ aug_bbox = [int(aug_center[0] - aug_hsize), int(aug_center[1] - aug_hsize), int(aug_center[0] + aug_hsize), int(aug_center[1] + aug_hsize)]
122
+ image = image.crop(aug_bbox)
123
+
124
+ image = image.resize((self.image_size, self.image_size), Image.Resampling.LANCZOS)
125
+ alpha = image.getchannel(3)
126
+ image = image.convert('RGB')
127
+ image = torch.tensor(np.array(image)).permute(2, 0, 1).float() / 255.0
128
+ alpha = torch.tensor(np.array(alpha)).float() / 255.0
129
+ image = image * alpha.unsqueeze(0)
130
+ pack['cond'] = image
131
+
132
+ return pack
133
+
134
+
135
+ class MultiImageConditionedMixin:
136
+ def __init__(self, roots, *, image_size=518, max_image_cond_view = 4, **kwargs):
137
+ self.image_size = image_size
138
+ self.max_image_cond_view = max_image_cond_view
139
+ super().__init__(roots, **kwargs)
140
+
141
+ def filter_metadata(self, metadata):
142
+ metadata, stats = super().filter_metadata(metadata)
143
+ metadata = metadata[metadata['cond_rendered'].notna()]
144
+ stats['Cond rendered'] = len(metadata)
145
+ return metadata, stats
146
+
147
+ def get_instance(self, root, instance):
148
+ pack = super().get_instance(root, instance)
149
+
150
+ image_root = os.path.join(root['render_cond'], instance)
151
+ with open(os.path.join(image_root, 'transforms.json')) as f:
152
+ metadata = json.load(f)
153
+
154
+ n_views = len(metadata['frames'])
155
+ n_sample_views = np.random.randint(1, self.max_image_cond_view+1)
156
+
157
+ assert n_views >= n_sample_views, f'Not enough views to sample {n_sample_views} unique images.'
158
+
159
+ sampled_views = np.random.choice(n_views, size=n_sample_views, replace=False)
160
+
161
+ cond_images = []
162
+ for v in sampled_views:
163
+ frame_info = metadata['frames'][v]
164
+ image_path = os.path.join(image_root, frame_info['file_path'])
165
+ image = Image.open(image_path)
166
+
167
+ alpha = np.array(image.getchannel(3))
168
+ bbox = np.array(alpha).nonzero()
169
+ bbox = [bbox[1].min(), bbox[0].min(), bbox[1].max(), bbox[0].max()]
170
+ center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
171
+ hsize = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 2
172
+ aug_hsize = hsize
173
+ aug_center = center
174
+ aug_bbox = [
175
+ int(aug_center[0] - aug_hsize),
176
+ int(aug_center[1] - aug_hsize),
177
+ int(aug_center[0] + aug_hsize),
178
+ int(aug_center[1] + aug_hsize),
179
+ ]
180
+
181
+ img = image.crop(aug_bbox)
182
+ img = img.resize((self.image_size, self.image_size), Image.Resampling.LANCZOS)
183
+ alpha = img.getchannel(3)
184
+ img = img.convert('RGB')
185
+ img = torch.tensor(np.array(img)).permute(2, 0, 1).float() / 255.0
186
+ alpha = torch.tensor(np.array(alpha)).float() / 255.0
187
+ img = img * alpha.unsqueeze(0)
188
+
189
+ cond_images.append(img)
190
+
191
+ pack['cond'] = [torch.stack(cond_images, dim=0)] # (V,3,H,W)
192
+ return pack
trellis2/datasets/flexi_dual_grid.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import pickle
4
+ import torch
5
+ import utils3d
6
+ from .components import StandardDatasetBase
7
+ from ..modules import sparse as sp
8
+ from ..renderers import MeshRenderer
9
+ from ..representations import Mesh
10
+ from ..utils.data_utils import load_balanced_group_indices
11
+ import o_voxel
12
+
13
+
14
+ class FlexiDualGridVisMixin:
15
+ @torch.no_grad()
16
+ def visualize_sample(self, x: dict):
17
+ mesh = x['mesh']
18
+
19
+ renderer = MeshRenderer({'near': 1, 'far': 3})
20
+ renderer.rendering_options.resolution = 512
21
+ renderer.rendering_options.ssaa = 4
22
+
23
+ # Build camera
24
+ yaws = [0, np.pi / 2, np.pi, 3 * np.pi / 2]
25
+ yaws_offset = np.random.uniform(-np.pi / 4, np.pi / 4)
26
+ yaws = [y + yaws_offset for y in yaws]
27
+ pitch = [np.random.uniform(-np.pi / 4, np.pi / 4) for _ in range(4)]
28
+
29
+ exts = []
30
+ ints = []
31
+ for yaw, pitch in zip(yaws, pitch):
32
+ orig = torch.tensor([
33
+ np.sin(yaw) * np.cos(pitch),
34
+ np.cos(yaw) * np.cos(pitch),
35
+ np.sin(pitch),
36
+ ]).float().cuda() * 2
37
+ fov = torch.deg2rad(torch.tensor(30)).cuda()
38
+ extrinsics = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda())
39
+ intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov)
40
+ exts.append(extrinsics)
41
+ ints.append(intrinsics)
42
+
43
+ # Build each representation
44
+ images = []
45
+ for m in mesh:
46
+ image = torch.zeros(3, 1024, 1024).cuda()
47
+ tile = [2, 2]
48
+ for j, (ext, intr) in enumerate(zip(exts, ints)):
49
+ image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = \
50
+ renderer.render(m.cuda(), ext, intr)['normal']
51
+ images.append(image)
52
+ images = torch.stack(images)
53
+
54
+ return images
55
+
56
+
57
+ class FlexiDualGridDataset(FlexiDualGridVisMixin, StandardDatasetBase):
58
+ """
59
+ Flexible Dual Grid Dataset
60
+
61
+ Args:
62
+ roots (str): path to the dataset
63
+ resolution (int): resolution of the voxel grid
64
+ min_aesthetic_score (float): minimum aesthetic score of the instances to be included in the dataset
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ roots,
70
+ resolution: int = 1024,
71
+ max_active_voxels: int = 1000000,
72
+ max_num_faces: int = None,
73
+ min_aesthetic_score: float = 5.0,
74
+ ):
75
+ self.resolution = resolution
76
+ self.min_aesthetic_score = min_aesthetic_score
77
+ self.max_active_voxels = max_active_voxels
78
+ self.max_num_faces = max_num_faces
79
+ self.value_range = (0, 1)
80
+
81
+ super().__init__(roots)
82
+
83
+ self.loads = [self.metadata.loc[sha256, f'dual_grid_size'] for _, sha256 in self.instances]
84
+
85
+ def __str__(self):
86
+ lines = [
87
+ super().__str__(),
88
+ f' - Resolution: {self.resolution}',
89
+ ]
90
+ return '\n'.join(lines)
91
+
92
+ def filter_metadata(self, metadata):
93
+ stats = {}
94
+ metadata = metadata[metadata[f'dual_grid_converted'] == True]
95
+ stats['Dual Grid Converted'] = len(metadata)
96
+ if self.min_aesthetic_score is not None:
97
+ metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score]
98
+ stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata)
99
+ metadata = metadata[metadata[f'dual_grid_size'] <= self.max_active_voxels]
100
+ stats[f'Active Voxels <= {self.max_active_voxels}'] = len(metadata)
101
+ if self.max_num_faces is not None:
102
+ metadata = metadata[metadata['num_faces'] <= self.max_num_faces]
103
+ stats[f'Faces <= {self.max_num_faces}'] = len(metadata)
104
+ return metadata, stats
105
+
106
+ def read_mesh(self, root, instance):
107
+ with open(os.path.join(root, f'{instance}.pickle'), 'rb') as f:
108
+ dump = pickle.load(f)
109
+ start = 0
110
+ vertices = []
111
+ faces = []
112
+ for obj in dump['objects']:
113
+ if obj['vertices'].size == 0 or obj['faces'].size == 0:
114
+ continue
115
+ vertices.append(obj['vertices'])
116
+ faces.append(obj['faces'] + start)
117
+ start += len(obj['vertices'])
118
+ vertices = torch.from_numpy(np.concatenate(vertices, axis=0)).float()
119
+ faces = torch.from_numpy(np.concatenate(faces, axis=0)).long()
120
+ vertices_min = vertices.min(dim=0)[0]
121
+ vertices_max = vertices.max(dim=0)[0]
122
+ center = (vertices_min + vertices_max) / 2
123
+ scale = 0.99999 / (vertices_max - vertices_min).max()
124
+ vertices = (vertices - center) * scale
125
+ assert torch.all(vertices >= -0.5) and torch.all(vertices <= 0.5), 'vertices out of range'
126
+ return {'mesh': [Mesh(vertices=vertices, faces=faces)]}
127
+
128
+ def read_dual_grid(self, root, instance):
129
+ coords, attr = o_voxel.io.read_vxz(os.path.join(root, f'{instance}.vxz'), num_threads=4)
130
+ vertices = sp.SparseTensor(
131
+ (attr['vertices'] / 255.0).float(),
132
+ torch.cat([torch.zeros_like(coords[:, 0:1]), coords], dim=-1),
133
+ )
134
+ intersected = vertices.replace(torch.cat([
135
+ attr['intersected'] % 2,
136
+ attr['intersected'] // 2 % 2,
137
+ attr['intersected'] // 4 % 2,
138
+ ], dim=-1).bool())
139
+ return {'vertices': vertices, 'intersected': intersected}
140
+
141
+ def get_instance(self, root, instance):
142
+ mesh = self.read_mesh(root['mesh_dump'], instance)
143
+ dual_grid = self.read_dual_grid(root['dual_grid'], instance)
144
+ return {**mesh, **dual_grid}
145
+
146
+ @staticmethod
147
+ def collate_fn(batch, split_size=None):
148
+ if split_size is None:
149
+ group_idx = [list(range(len(batch)))]
150
+ else:
151
+ group_idx = load_balanced_group_indices([b['vertices'].feats.shape[0] for b in batch], split_size)
152
+ packs = []
153
+ for group in group_idx:
154
+ sub_batch = [batch[i] for i in group]
155
+ pack = {}
156
+
157
+ keys = [k for k in sub_batch[0].keys()]
158
+ for k in keys:
159
+ if isinstance(sub_batch[0][k], torch.Tensor):
160
+ pack[k] = torch.stack([b[k] for b in sub_batch])
161
+ elif isinstance(sub_batch[0][k], sp.SparseTensor):
162
+ pack[k] = sp.sparse_cat([b[k] for b in sub_batch], dim=0)
163
+ elif isinstance(sub_batch[0][k], list):
164
+ pack[k] = sum([b[k] for b in sub_batch], [])
165
+ else:
166
+ pack[k] = [b[k] for b in sub_batch]
167
+
168
+ packs.append(pack)
169
+
170
+ if split_size is None:
171
+ return packs[0]
172
+ return packs
173
+
trellis2/datasets/sparse_structure_latent.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from typing import *
4
+ import numpy as np
5
+ import torch
6
+ from ..representations import Voxel
7
+ from ..renderers import VoxelRenderer
8
+ from .components import StandardDatasetBase, ImageConditionedMixin
9
+ from .. import models
10
+ from ..utils.render_utils import yaw_pitch_r_fov_to_extrinsics_intrinsics
11
+
12
+
13
+ class SparseStructureLatentVisMixin:
14
+ def __init__(
15
+ self,
16
+ *args,
17
+ pretrained_ss_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16.json',
18
+ ss_dec_path: Optional[str] = None,
19
+ ss_dec_ckpt: Optional[str] = None,
20
+ **kwargs
21
+ ):
22
+ super().__init__(*args, **kwargs)
23
+ self.ss_dec = None
24
+ self.pretrained_ss_dec = pretrained_ss_dec
25
+ self.ss_dec_path = ss_dec_path
26
+ self.ss_dec_ckpt = ss_dec_ckpt
27
+
28
+ def _loading_ss_dec(self):
29
+ if self.ss_dec is not None:
30
+ return
31
+ if self.ss_dec_path is not None:
32
+ cfg = json.load(open(os.path.join(self.ss_dec_path, 'config.json'), 'r'))
33
+ decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args'])
34
+ ckpt_path = os.path.join(self.ss_dec_path, 'ckpts', f'decoder_{self.ss_dec_ckpt}.pt')
35
+ decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True))
36
+ else:
37
+ decoder = models.from_pretrained(self.pretrained_ss_dec)
38
+ self.ss_dec = decoder.cuda().eval()
39
+
40
+ def _delete_ss_dec(self):
41
+ del self.ss_dec
42
+ self.ss_dec = None
43
+
44
+ @torch.no_grad()
45
+ def decode_latent(self, z, batch_size=4):
46
+ self._loading_ss_dec()
47
+ ss = []
48
+ if self.normalization:
49
+ z = z * self.std.to(z.device) + self.mean.to(z.device)
50
+ for i in range(0, z.shape[0], batch_size):
51
+ ss.append(self.ss_dec(z[i:i+batch_size]))
52
+ ss = torch.cat(ss, dim=0)
53
+ self._delete_ss_dec()
54
+ return ss
55
+
56
+ @torch.no_grad()
57
+ def visualize_sample(self, x_0: Union[torch.Tensor, dict]):
58
+ x_0 = x_0 if isinstance(x_0, torch.Tensor) else x_0['x_0']
59
+ x_0 = self.decode_latent(x_0.cuda())
60
+
61
+ renderer = VoxelRenderer()
62
+ renderer.rendering_options.resolution = 512
63
+ renderer.rendering_options.ssaa = 4
64
+
65
+ # build camera
66
+ yaw = [0, np.pi/2, np.pi, 3*np.pi/2]
67
+ yaw_offset = -16 / 180 * np.pi
68
+ yaw = [y + yaw_offset for y in yaw]
69
+ pitch = [20 / 180 * np.pi for _ in range(4)]
70
+ exts, ints = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, 2, 30)
71
+
72
+ images = []
73
+
74
+ # Build each representation
75
+ x_0 = x_0.cuda()
76
+ for i in range(x_0.shape[0]):
77
+ coords = torch.nonzero(x_0[i, 0] > 0, as_tuple=False)
78
+ resolution = x_0.shape[-1]
79
+ color = coords / resolution
80
+ rep = Voxel(
81
+ origin=[-0.5, -0.5, -0.5],
82
+ voxel_size=1/resolution,
83
+ coords=coords,
84
+ attrs=color,
85
+ layout={
86
+ 'color': slice(0, 3),
87
+ }
88
+ )
89
+ image = torch.zeros(3, 1024, 1024).cuda()
90
+ tile = [2, 2]
91
+ for j, (ext, intr) in enumerate(zip(exts, ints)):
92
+ res = renderer.render(rep, ext, intr, colors_overwrite=color)
93
+ image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['color']
94
+ images.append(image)
95
+
96
+ return torch.stack(images)
97
+
98
+
99
+ class SparseStructureLatent(SparseStructureLatentVisMixin, StandardDatasetBase):
100
+ """
101
+ Sparse structure latent dataset
102
+
103
+ Args:
104
+ roots (str): path to the dataset
105
+ min_aesthetic_score (float): minimum aesthetic score
106
+ normalization (dict): normalization stats
107
+ pretrained_ss_dec (str): name of the pretrained sparse structure decoder
108
+ ss_dec_path (str): path to the sparse structure decoder, if given, will override the pretrained_ss_dec
109
+ ss_dec_ckpt (str): name of the sparse structure decoder checkpoint
110
+ """
111
+ def __init__(self,
112
+ roots: str,
113
+ *,
114
+ min_aesthetic_score: float = 5.0,
115
+ normalization: Optional[dict] = None,
116
+ pretrained_ss_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16',
117
+ ss_dec_path: Optional[str] = None,
118
+ ss_dec_ckpt: Optional[str] = None,
119
+ ):
120
+ self.min_aesthetic_score = min_aesthetic_score
121
+ self.normalization = normalization
122
+ self.value_range = (0, 1)
123
+
124
+ super().__init__(
125
+ roots,
126
+ pretrained_ss_dec=pretrained_ss_dec,
127
+ ss_dec_path=ss_dec_path,
128
+ ss_dec_ckpt=ss_dec_ckpt,
129
+ )
130
+
131
+ if self.normalization is not None:
132
+ self.mean = torch.tensor(self.normalization['mean']).reshape(-1, 1, 1, 1)
133
+ self.std = torch.tensor(self.normalization['std']).reshape(-1, 1, 1, 1)
134
+
135
+ def filter_metadata(self, metadata):
136
+ stats = {}
137
+ metadata = metadata[metadata['ss_latent_encoded'] == True]
138
+ stats['With latent'] = len(metadata)
139
+ metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score]
140
+ stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata)
141
+ return metadata, stats
142
+
143
+ def get_instance(self, root, instance):
144
+ latent = np.load(os.path.join(root['ss_latent'], f'{instance}.npz'))
145
+ z = torch.tensor(latent['z']).float()
146
+ if self.normalization is not None:
147
+ z = (z - self.mean) / self.std
148
+
149
+ pack = {
150
+ 'x_0': z,
151
+ }
152
+ return pack
153
+
154
+
155
+ class ImageConditionedSparseStructureLatent(ImageConditionedMixin, SparseStructureLatent):
156
+ """
157
+ Image-conditioned sparse structure dataset
158
+ """
159
+ pass
160
+
trellis2/datasets/sparse_voxel_pbr.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ from typing import Union
4
+ import numpy as np
5
+ import pickle
6
+ import torch
7
+ from PIL import Image
8
+ import o_voxel
9
+ import utils3d
10
+ from .components import StandardDatasetBase
11
+ from ..modules import sparse as sp
12
+ from ..renderers import VoxelRenderer
13
+ from ..representations import Voxel
14
+ from ..representations.mesh import MeshWithPbrMaterial, TextureFilterMode, TextureWrapMode, AlphaMode, PbrMaterial, Texture
15
+
16
+ from ..utils.data_utils import load_balanced_group_indices
17
+
18
+
19
+ def is_power_of_two(n: int) -> bool:
20
+ return n > 0 and (n & (n - 1)) == 0
21
+
22
+
23
+ def nearest_power_of_two(n: int) -> int:
24
+ if n < 1:
25
+ raise ValueError("n must be >= 1")
26
+ if is_power_of_two(n):
27
+ return n
28
+ lower = 2 ** (n.bit_length() - 1)
29
+ upper = 2 ** n.bit_length()
30
+ if n - lower < upper - n:
31
+ return lower
32
+ else:
33
+ return upper
34
+
35
+
36
+ class SparseVoxelPbrVisMixin:
37
+ @torch.no_grad()
38
+ def visualize_sample(self, x: Union[sp.SparseTensor, dict]):
39
+ x = x if isinstance(x, sp.SparseTensor) else x['x']
40
+
41
+ renderer = VoxelRenderer()
42
+ renderer.rendering_options.resolution = 512
43
+ renderer.rendering_options.ssaa = 4
44
+
45
+ # Build camera
46
+ yaws = [0, np.pi / 2, np.pi, 3 * np.pi / 2]
47
+ yaws_offset = np.random.uniform(-np.pi / 4, np.pi / 4)
48
+ yaws = [y + yaws_offset for y in yaws]
49
+ pitch = [np.random.uniform(-np.pi / 4, np.pi / 4) for _ in range(4)]
50
+
51
+ exts = []
52
+ ints = []
53
+ for yaw, pitch in zip(yaws, pitch):
54
+ orig = torch.tensor([
55
+ np.sin(yaw) * np.cos(pitch),
56
+ np.cos(yaw) * np.cos(pitch),
57
+ np.sin(pitch),
58
+ ]).float().cuda() * 2
59
+ fov = torch.deg2rad(torch.tensor(30)).cuda()
60
+ extrinsics = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda())
61
+ intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov)
62
+ exts.append(extrinsics)
63
+ ints.append(intrinsics)
64
+
65
+ images = {k: [] for k in self.layout}
66
+
67
+ # Build each representation
68
+ x = x.cuda()
69
+ for i in range(x.shape[0]):
70
+ rep = Voxel(
71
+ origin=[-0.5, -0.5, -0.5],
72
+ voxel_size=1/self.resolution,
73
+ coords=x[i].coords[:, 1:].contiguous(),
74
+ attrs=None,
75
+ layout={
76
+ 'color': slice(0, 3),
77
+ }
78
+ )
79
+ for k in self.layout:
80
+ image = torch.zeros(3, 1024, 1024).cuda()
81
+ tile = [2, 2]
82
+ for j, (ext, intr) in enumerate(zip(exts, ints)):
83
+ attr = x[i].feats[:, self.layout[k]].expand(-1, 3)
84
+ res = renderer.render(rep, ext, intr, colors_overwrite=attr)
85
+ image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['color']
86
+ images[k].append(image)
87
+
88
+ for k in self.layout:
89
+ images[k] = torch.stack(images[k])
90
+
91
+ return images
92
+
93
+
94
+ class SparseVoxelPbrDataset(SparseVoxelPbrVisMixin, StandardDatasetBase):
95
+ """
96
+ Sparse Voxel PBR dataset.
97
+
98
+ Args:
99
+ roots (str): path to the dataset
100
+ resolution (int): resolution of the voxel grid
101
+ min_aesthetic_score (float): minimum aesthetic score of the instances to be included in the dataset
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ roots,
107
+ resolution: int = 1024,
108
+ max_active_voxels: int = 1000000,
109
+ max_num_faces: int = None,
110
+ min_aesthetic_score: float = 5.0,
111
+ attrs: list[str] = ['base_color', 'metallic', 'roughness', 'emissive', 'alpha'],
112
+ with_mesh: bool = True,
113
+ ):
114
+ self.resolution = resolution
115
+ self.min_aesthetic_score = min_aesthetic_score
116
+ self.max_active_voxels = max_active_voxels
117
+ self.max_num_faces = max_num_faces
118
+ self.with_mesh = with_mesh
119
+ self.value_range = (-1, 1)
120
+ self.channels = {
121
+ 'base_color': 3,
122
+ 'metallic': 1,
123
+ 'roughness': 1,
124
+ 'emissive': 3,
125
+ 'alpha': 1,
126
+ }
127
+ self.layout = {}
128
+ start = 0
129
+ for attr in attrs:
130
+ self.layout[attr] = slice(start, start + self.channels[attr])
131
+ start += self.channels[attr]
132
+
133
+ super().__init__(roots)
134
+
135
+ self.loads = [self.metadata.loc[sha256, f'num_pbr_voxels'] for _, sha256 in self.instances]
136
+
137
+ def __str__(self):
138
+ lines = [
139
+ super().__str__(),
140
+ f' - Resolution: {self.resolution}',
141
+ f' - Attributes: {list(self.layout.keys())}',
142
+ ]
143
+ return '\n'.join(lines)
144
+
145
+ def filter_metadata(self, metadata):
146
+ stats = {}
147
+ metadata = metadata[metadata['pbr_voxelized'] == True]
148
+ stats['PBR Voxelized'] = len(metadata)
149
+ if self.min_aesthetic_score is not None:
150
+ metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score]
151
+ stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata)
152
+ metadata = metadata[metadata['num_pbr_voxels'] <= self.max_active_voxels]
153
+ stats[f'Active voxels <= {self.max_active_voxels}'] = len(metadata)
154
+ if self.max_num_faces is not None:
155
+ metadata = metadata[metadata['num_faces'] <= self.max_num_faces]
156
+ stats[f'Faces <= {self.max_num_faces}'] = len(metadata)
157
+ return metadata, stats
158
+
159
+ @staticmethod
160
+ def _texture_from_dump(pack) -> Texture:
161
+ png_bytes = pack['image']
162
+ image = Image.open(io.BytesIO(png_bytes))
163
+ if image.width != image.height or not is_power_of_two(image.width):
164
+ size = nearest_power_of_two(max(image.width, image.height))
165
+ image = image.resize((size, size), Image.LANCZOS)
166
+ texture = torch.tensor(np.array(image) / 255.0, dtype=torch.float32).reshape(image.height, image.width, -1)
167
+ filter_mode = {
168
+ 'Linear': TextureFilterMode.LINEAR,
169
+ 'Closest': TextureFilterMode.CLOSEST,
170
+ 'Cubic': TextureFilterMode.LINEAR,
171
+ 'Smart': TextureFilterMode.LINEAR,
172
+ }[pack['interpolation']]
173
+ wrap_mode = {
174
+ 'REPEAT': TextureWrapMode.REPEAT,
175
+ 'EXTEND': TextureWrapMode.CLAMP_TO_EDGE,
176
+ 'CLIP': TextureWrapMode.CLAMP_TO_EDGE,
177
+ 'MIRROR': TextureWrapMode.MIRRORED_REPEAT,
178
+ }[pack['extension']]
179
+ return Texture(texture, filter_mode=filter_mode, wrap_mode=wrap_mode)
180
+
181
+ def read_mesh_with_texture(self, root, instance):
182
+ with open(os.path.join(root, f'{instance}.pickle'), 'rb') as f:
183
+ dump = pickle.load(f)
184
+
185
+ # Fix dump alpha map
186
+ for mat in dump['materials']:
187
+ if mat['alphaTexture'] is not None and mat['alphaMode'] == 'OPAQUE':
188
+ mat['alphaMode'] = 'BLEND'
189
+
190
+ # process material
191
+ materials = []
192
+ for mat in dump['materials']:
193
+ materials.append(PbrMaterial(
194
+ base_color_texture=self._texture_from_dump(mat['baseColorTexture']) if mat['baseColorTexture'] is not None else None,
195
+ base_color_factor=mat['baseColorFactor'],
196
+ metallic_texture=self._texture_from_dump(mat['metallicTexture']) if mat['metallicTexture'] is not None else None,
197
+ metallic_factor=mat['metallicFactor'],
198
+ roughness_texture=self._texture_from_dump(mat['roughnessTexture']) if mat['roughnessTexture'] is not None else None,
199
+ roughness_factor=mat['roughnessFactor'],
200
+ alpha_texture=self._texture_from_dump(mat['alphaTexture']) if mat['alphaTexture'] is not None else None,
201
+ alpha_factor=mat['alphaFactor'],
202
+ alpha_mode={
203
+ 'OPAQUE': AlphaMode.OPAQUE,
204
+ 'MASK': AlphaMode.MASK,
205
+ 'BLEND': AlphaMode.BLEND,
206
+ }[mat['alphaMode']],
207
+ alpha_cutoff=mat['alphaCutoff'],
208
+ ))
209
+ materials.append(PbrMaterial(
210
+ base_color_factor=[0.8, 0.8, 0.8],
211
+ alpha_factor=1.0,
212
+ metallic_factor=0.0,
213
+ roughness_factor=0.5,
214
+ alpha_mode=AlphaMode.OPAQUE,
215
+ alpha_cutoff=0.5,
216
+ )) # append default material
217
+
218
+ # process mesh
219
+ start = 0
220
+ vertices = []
221
+ faces = []
222
+ material_ids = []
223
+ uv_coords = []
224
+ for obj in dump['objects']:
225
+ if obj['vertices'].size == 0 or obj['faces'].size == 0:
226
+ continue
227
+ vertices.append(obj['vertices'])
228
+ faces.append(obj['faces'] + start)
229
+ obj['mat_ids'][obj['mat_ids'] == -1] = len(materials) - 1
230
+ material_ids.append(obj['mat_ids'])
231
+ uv_coords.append(obj['uvs'] if obj['uvs'] is not None else np.zeros((obj['faces'].shape[0], 3, 2), dtype=np.float32))
232
+ start += len(obj['vertices'])
233
+
234
+ vertices = torch.from_numpy(np.concatenate(vertices, axis=0)).float()
235
+ faces = torch.from_numpy(np.concatenate(faces, axis=0)).long()
236
+ material_ids = torch.from_numpy(np.concatenate(material_ids, axis=0)).long()
237
+ uv_coords = torch.from_numpy(np.concatenate(uv_coords, axis=0)).float()
238
+
239
+ # Normalize vertices
240
+ vertices_min = vertices.min(dim=0)[0]
241
+ vertices_max = vertices.max(dim=0)[0]
242
+ center = (vertices_min + vertices_max) / 2
243
+ scale = 0.99999 / (vertices_max - vertices_min).max()
244
+ vertices = (vertices - center) * scale
245
+ assert torch.all(vertices >= -0.5) and torch.all(vertices <= 0.5), 'vertices out of range'
246
+
247
+ return {'mesh': [MeshWithPbrMaterial(
248
+ vertices=vertices,
249
+ faces=faces,
250
+ material_ids=material_ids,
251
+ uv_coords=uv_coords,
252
+ materials=materials,
253
+ )]}
254
+
255
+ def read_pbr_voxel(self, root, instance):
256
+ coords, attr = o_voxel.io.read_vxz(os.path.join(root, f'{instance}.vxz'), num_threads=4)
257
+ feats = torch.concat([attr[k] for k in self.layout], dim=-1) / 255.0 * 2 - 1
258
+ x = sp.SparseTensor(
259
+ feats.float(),
260
+ torch.cat([torch.zeros_like(coords[:, 0:1]), coords], dim=-1),
261
+ )
262
+ return {'x': x}
263
+
264
+ def get_instance(self, root, instance):
265
+ if self.with_mesh:
266
+ mesh = self.read_mesh_with_texture(root['pbr_dump'], instance)
267
+ pbr_voxel = self.read_pbr_voxel(root['pbr_voxel'], instance)
268
+ return {**mesh, **pbr_voxel}
269
+ else:
270
+ return self.read_pbr_voxel(root['pbr_voxel'], instance)
271
+
272
+ @staticmethod
273
+ def collate_fn(batch, split_size=None):
274
+ if split_size is None:
275
+ group_idx = [list(range(len(batch)))]
276
+ else:
277
+ group_idx = load_balanced_group_indices([b['x'].feats.shape[0] for b in batch], split_size)
278
+ packs = []
279
+ for group in group_idx:
280
+ sub_batch = [batch[i] for i in group]
281
+ pack = {}
282
+
283
+ keys = [k for k in sub_batch[0].keys()]
284
+ for k in keys:
285
+ if isinstance(sub_batch[0][k], torch.Tensor):
286
+ pack[k] = torch.stack([b[k] for b in sub_batch])
287
+ elif isinstance(sub_batch[0][k], sp.SparseTensor):
288
+ pack[k] = sp.sparse_cat([b[k] for b in sub_batch], dim=0)
289
+ elif isinstance(sub_batch[0][k], list):
290
+ pack[k] = sum([b[k] for b in sub_batch], [])
291
+ else:
292
+ pack[k] = [b[k] for b in sub_batch]
293
+
294
+ packs.append(pack)
295
+
296
+ if split_size is None:
297
+ return packs[0]
298
+ return packs
trellis2/datasets/structured_latent.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import *
4
+ import numpy as np
5
+ import torch
6
+ import utils3d.torch
7
+ from .components import StandardDatasetBase, ImageConditionedMixin
8
+ from ..modules.sparse.basic import SparseTensor
9
+ from .. import models
10
+ from ..utils.render_utils import get_renderer
11
+ from ..utils.data_utils import load_balanced_group_indices
12
+
13
+
14
+ class SLatVisMixin:
15
+ def __init__(
16
+ self,
17
+ *args,
18
+ pretrained_slat_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/slat_dec_gs_swin8_B_64l8gs32_fp16',
19
+ slat_dec_path: Optional[str] = None,
20
+ slat_dec_ckpt: Optional[str] = None,
21
+ **kwargs
22
+ ):
23
+ super().__init__(*args, **kwargs)
24
+ self.slat_dec = None
25
+ self.pretrained_slat_dec = pretrained_slat_dec
26
+ self.slat_dec_path = slat_dec_path
27
+ self.slat_dec_ckpt = slat_dec_ckpt
28
+
29
+ def _loading_slat_dec(self):
30
+ if self.slat_dec is not None:
31
+ return
32
+ if self.slat_dec_path is not None:
33
+ cfg = json.load(open(os.path.join(self.slat_dec_path, 'config.json'), 'r'))
34
+ decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args'])
35
+ ckpt_path = os.path.join(self.slat_dec_path, 'ckpts', f'decoder_{self.slat_dec_ckpt}.pt')
36
+ decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True))
37
+ else:
38
+ decoder = models.from_pretrained(self.pretrained_slat_dec)
39
+ self.slat_dec = decoder.cuda().eval()
40
+
41
+ def _delete_slat_dec(self):
42
+ del self.slat_dec
43
+ self.slat_dec = None
44
+
45
+ @torch.no_grad()
46
+ def decode_latent(self, z, batch_size=4):
47
+ self._loading_slat_dec()
48
+ reps = []
49
+ if self.normalization is not None:
50
+ z = z * self.std.to(z.device) + self.mean.to(z.device)
51
+ for i in range(0, z.shape[0], batch_size):
52
+ reps.append(self.slat_dec(z[i:i+batch_size]))
53
+ reps = sum(reps, [])
54
+ self._delete_slat_dec()
55
+ return reps
56
+
57
+ @torch.no_grad()
58
+ def visualize_sample(self, x_0: Union[SparseTensor, dict]):
59
+ x_0 = x_0 if isinstance(x_0, SparseTensor) else x_0['x_0']
60
+ reps = self.decode_latent(x_0.cuda())
61
+
62
+ # Build camera
63
+ yaws = [0, np.pi / 2, np.pi, 3 * np.pi / 2]
64
+ yaws_offset = np.random.uniform(-np.pi / 4, np.pi / 4)
65
+ yaws = [y + yaws_offset for y in yaws]
66
+ pitch = [np.random.uniform(-np.pi / 4, np.pi / 4) for _ in range(4)]
67
+
68
+ exts = []
69
+ ints = []
70
+ for yaw, pitch in zip(yaws, pitch):
71
+ orig = torch.tensor([
72
+ np.sin(yaw) * np.cos(pitch),
73
+ np.cos(yaw) * np.cos(pitch),
74
+ np.sin(pitch),
75
+ ]).float().cuda() * 2
76
+ fov = torch.deg2rad(torch.tensor(40)).cuda()
77
+ extrinsics = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda())
78
+ intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov)
79
+ exts.append(extrinsics)
80
+ ints.append(intrinsics)
81
+
82
+ renderer = get_renderer(reps[0])
83
+ images = []
84
+ for representation in reps:
85
+ image = torch.zeros(3, 1024, 1024).cuda()
86
+ tile = [2, 2]
87
+ for j, (ext, intr) in enumerate(zip(exts, ints)):
88
+ res = renderer.render(representation, ext, intr)
89
+ image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['color']
90
+ images.append(image)
91
+ images = torch.stack(images)
92
+
93
+ return images
94
+
95
+
96
+ class SLat(SLatVisMixin, StandardDatasetBase):
97
+ """
98
+ structured latent V2 dataset
99
+
100
+ Args:
101
+ roots (str): path to the dataset
102
+ min_aesthetic_score (float): minimum aesthetic score
103
+ max_tokens (int): maximum number of tokens
104
+ latent_key (str): key of the latent to be used
105
+ normalization (dict): normalization stats
106
+ pretrained_slat_dec (str): name of the pretrained slat decoder
107
+ slat_dec_path (str): path to the slat decoder, if given, will override the pretrained_slat_dec
108
+ slat_dec_ckpt (str): name of the slat decoder checkpoint
109
+ """
110
+ def __init__(self,
111
+ roots: str,
112
+ *,
113
+ min_aesthetic_score: float = 5.0,
114
+ max_tokens: int = 32768,
115
+ latent_key: str = 'shape_latent',
116
+ normalization: Optional[dict] = None,
117
+ pretrained_slat_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/slat_dec_gs_swin8_B_64l8gs32_fp16',
118
+ slat_dec_path: Optional[str] = None,
119
+ slat_dec_ckpt: Optional[str] = None,
120
+ ):
121
+ self.normalization = normalization
122
+ self.min_aesthetic_score = min_aesthetic_score
123
+ self.max_tokens = max_tokens
124
+ self.latent_key = latent_key
125
+ self.value_range = (0, 1)
126
+
127
+ super().__init__(
128
+ roots,
129
+ pretrained_slat_dec=pretrained_slat_dec,
130
+ slat_dec_path=slat_dec_path,
131
+ slat_dec_ckpt=slat_dec_ckpt,
132
+ )
133
+
134
+ self.loads = [self.metadata.loc[sha256, f'{latent_key}_tokens'] for _, sha256 in self.instances]
135
+
136
+ if self.normalization is not None:
137
+ self.mean = torch.tensor(self.normalization['mean']).reshape(1, -1)
138
+ self.std = torch.tensor(self.normalization['std']).reshape(1, -1)
139
+
140
+ def filter_metadata(self, metadata):
141
+ stats = {}
142
+ metadata = metadata[metadata[f'{self.latent_key}_encoded'] == True]
143
+ stats['With latent'] = len(metadata)
144
+ metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score]
145
+ stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata)
146
+ metadata = metadata[metadata[f'{self.latent_key}_tokens'] <= self.max_tokens]
147
+ stats[f'Num tokens <= {self.max_tokens}'] = len(metadata)
148
+ return metadata, stats
149
+
150
+ def get_instance(self, root, instance):
151
+ data = np.load(os.path.join(root[self.latent_key], f'{instance}.npz'))
152
+ coords = torch.tensor(data['coords']).int()
153
+ feats = torch.tensor(data['feats']).float()
154
+ if self.normalization is not None:
155
+ feats = (feats - self.mean) / self.std
156
+ return {
157
+ 'coords': coords,
158
+ 'feats': feats,
159
+ }
160
+
161
+ @staticmethod
162
+ def collate_fn(batch, split_size=None):
163
+ if split_size is None:
164
+ group_idx = [list(range(len(batch)))]
165
+ else:
166
+ group_idx = load_balanced_group_indices([b['coords'].shape[0] for b in batch], split_size)
167
+ packs = []
168
+ for group in group_idx:
169
+ sub_batch = [batch[i] for i in group]
170
+ pack = {}
171
+ coords = []
172
+ feats = []
173
+ layout = []
174
+ start = 0
175
+ for i, b in enumerate(sub_batch):
176
+ coords.append(torch.cat([torch.full((b['coords'].shape[0], 1), i, dtype=torch.int32), b['coords']], dim=-1))
177
+ feats.append(b['feats'])
178
+ layout.append(slice(start, start + b['coords'].shape[0]))
179
+ start += b['coords'].shape[0]
180
+ coords = torch.cat(coords)
181
+ feats = torch.cat(feats)
182
+ pack['x_0'] = SparseTensor(
183
+ coords=coords,
184
+ feats=feats,
185
+ )
186
+ pack['x_0']._shape = torch.Size([len(group), *sub_batch[0]['feats'].shape[1:]])
187
+ pack['x_0'].register_spatial_cache('layout', layout)
188
+
189
+ # collate other data
190
+ keys = [k for k in sub_batch[0].keys() if k not in ['coords', 'feats']]
191
+ for k in keys:
192
+ if isinstance(sub_batch[0][k], torch.Tensor):
193
+ pack[k] = torch.stack([b[k] for b in sub_batch])
194
+ elif isinstance(sub_batch[0][k], list):
195
+ pack[k] = sum([b[k] for b in sub_batch], [])
196
+ else:
197
+ pack[k] = [b[k] for b in sub_batch]
198
+
199
+ packs.append(pack)
200
+
201
+ if split_size is None:
202
+ return packs[0]
203
+ return packs
204
+
205
+
206
+ class ImageConditionedSLat(ImageConditionedMixin, SLat):
207
+ """
208
+ Image conditioned structured latent dataset
209
+ """
210
+ pass
trellis2/datasets/structured_latent_shape.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from typing import *
4
+ import numpy as np
5
+ import torch
6
+ from .. import models
7
+ from .components import ImageConditionedMixin
8
+ from ..modules.sparse import SparseTensor
9
+ from .structured_latent import SLatVisMixin, SLat
10
+ from ..utils.render_utils import get_renderer, yaw_pitch_r_fov_to_extrinsics_intrinsics
11
+
12
+
13
+ class SLatShapeVisMixin(SLatVisMixin):
14
+ def _loading_slat_dec(self):
15
+ if self.slat_dec is not None:
16
+ return
17
+ if self.slat_dec_path is not None:
18
+ cfg = json.load(open(os.path.join(self.slat_dec_path, 'config.json'), 'r'))
19
+ decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args'])
20
+ ckpt_path = os.path.join(self.slat_dec_path, 'ckpts', f'decoder_{self.slat_dec_ckpt}.pt')
21
+ decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True))
22
+ else:
23
+ decoder = models.from_pretrained(self.pretrained_slat_dec)
24
+ decoder.set_resolution(self.resolution)
25
+ self.slat_dec = decoder.cuda().eval()
26
+
27
+ @torch.no_grad()
28
+ def visualize_sample(self, x_0: Union[SparseTensor, dict]):
29
+ x_0 = x_0 if isinstance(x_0, SparseTensor) else x_0['x_0']
30
+ reps = self.decode_latent(x_0.cuda())
31
+
32
+ # build camera
33
+ yaw = [0, np.pi/2, np.pi, 3*np.pi/2]
34
+ yaw_offset = -16 / 180 * np.pi
35
+ yaw = [y + yaw_offset for y in yaw]
36
+ pitch = [20 / 180 * np.pi for _ in range(4)]
37
+ exts, ints = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, 2, 30)
38
+
39
+ # render
40
+ renderer = get_renderer(reps[0])
41
+ images = []
42
+ for representation in reps:
43
+ image = torch.zeros(3, 1024, 1024).cuda()
44
+ tile = [2, 2]
45
+ for j, (ext, intr) in enumerate(zip(exts, ints)):
46
+ res = renderer.render(representation, ext, intr)
47
+ image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['normal']
48
+ images.append(image)
49
+ images = torch.stack(images)
50
+ return images
51
+
52
+
53
+ class SLatShape(SLatShapeVisMixin, SLat):
54
+ """
55
+ structured latent for shape generation
56
+
57
+ Args:
58
+ roots (str): path to the dataset
59
+ resolution (int): resolution of the shape
60
+ min_aesthetic_score (float): minimum aesthetic score
61
+ max_tokens (int): maximum number of tokens
62
+ latent_key (str): key of the latent to be used
63
+ normalization (dict): normalization stats
64
+ pretrained_slat_dec (str): name of the pretrained slat decoder
65
+ slat_dec_path (str): path to the slat decoder, if given, will override the pretrained_slat_dec
66
+ slat_dec_ckpt (str): name of the slat decoder checkpoint
67
+ """
68
+ def __init__(self,
69
+ roots: str,
70
+ *,
71
+ resolution: int,
72
+ min_aesthetic_score: float = 5.0,
73
+ max_tokens: int = 32768,
74
+ normalization: Optional[dict] = None,
75
+ pretrained_slat_dec: str = 'microsoft/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16',
76
+ slat_dec_path: Optional[str] = None,
77
+ slat_dec_ckpt: Optional[str] = None,
78
+ ):
79
+ super().__init__(
80
+ roots,
81
+ min_aesthetic_score=min_aesthetic_score,
82
+ max_tokens=max_tokens,
83
+ latent_key='shape_latent',
84
+ normalization=normalization,
85
+ pretrained_slat_dec=pretrained_slat_dec,
86
+ slat_dec_path=slat_dec_path,
87
+ slat_dec_ckpt=slat_dec_ckpt,
88
+ )
89
+ self.resolution = resolution
90
+
91
+
92
+ class ImageConditionedSLatShape(ImageConditionedMixin, SLatShape):
93
+ """
94
+ Image conditioned structured latent for shape generation
95
+ """
96
+ pass
trellis2/datasets/structured_latent_svpbr.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ['OPENCV_IO_ENABLE_OPENEXR'] = '1'
3
+ import json
4
+ from typing import *
5
+ import numpy as np
6
+ import torch
7
+ import cv2
8
+ from .. import models
9
+ from .components import StandardDatasetBase, ImageConditionedMixin
10
+ from ..modules.sparse import SparseTensor, sparse_cat
11
+ from ..representations import MeshWithVoxel
12
+ from ..renderers import PbrMeshRenderer, EnvMap
13
+ from ..utils.data_utils import load_balanced_group_indices
14
+ from ..utils.render_utils import yaw_pitch_r_fov_to_extrinsics_intrinsics
15
+
16
+
17
+ class SLatPbrVisMixin:
18
+ def __init__(
19
+ self,
20
+ *args,
21
+ pretrained_pbr_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/tex_dec_next_dc_f16c32_fp16',
22
+ pbr_slat_dec_path: Optional[str] = None,
23
+ pbr_slat_dec_ckpt: Optional[str] = None,
24
+ pretrained_shape_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16',
25
+ shape_slat_dec_path: Optional[str] = None,
26
+ shape_slat_dec_ckpt: Optional[str] = None,
27
+ **kwargs
28
+ ):
29
+ super().__init__(*args, **kwargs)
30
+ self.pbr_slat_dec = None
31
+ self.pretrained_pbr_slat_dec = pretrained_pbr_slat_dec
32
+ self.pbr_slat_dec_path = pbr_slat_dec_path
33
+ self.pbr_slat_dec_ckpt = pbr_slat_dec_ckpt
34
+ self.shape_slat_dec = None
35
+ self.pretrained_shape_slat_dec = pretrained_shape_slat_dec
36
+ self.shape_slat_dec_path = shape_slat_dec_path
37
+ self.shape_slat_dec_ckpt = shape_slat_dec_ckpt
38
+
39
+ def _loading_slat_dec(self):
40
+ if self.pbr_slat_dec is not None and self.shape_slat_dec is not None:
41
+ return
42
+ if self.pbr_slat_dec_path is not None:
43
+ cfg = json.load(open(os.path.join(self.pbr_slat_dec_path, 'config.json'), 'r'))
44
+ decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args'])
45
+ ckpt_path = os.path.join(self.pbr_slat_dec_path, 'ckpts', f'decoder_{self.pbr_slat_dec_ckpt}.pt')
46
+ decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True))
47
+ else:
48
+ decoder = models.from_pretrained(self.pretrained_pbr_slat_dec)
49
+ self.pbr_slat_dec = decoder.cuda().eval()
50
+
51
+ if self.shape_slat_dec_path is not None:
52
+ cfg = json.load(open(os.path.join(self.shape_slat_dec_path, 'config.json'), 'r'))
53
+ decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args'])
54
+ ckpt_path = os.path.join(self.shape_slat_dec_path, 'ckpts', f'decoder_{self.shape_slat_dec_ckpt}.pt')
55
+ decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True))
56
+ else:
57
+ decoder = models.from_pretrained(self.pretrained_shape_slat_dec)
58
+ decoder.set_resolution(self.resolution)
59
+ self.shape_slat_dec = decoder.cuda().eval()
60
+
61
+ def _delete_slat_dec(self):
62
+ del self.pbr_slat_dec
63
+ self.pbr_slat_dec = None
64
+ del self.shape_slat_dec
65
+ self.shape_slat_dec = None
66
+
67
+ @torch.no_grad()
68
+ def decode_latent(self, z, shape_z, batch_size=4):
69
+ self._loading_slat_dec()
70
+ reps = []
71
+ if self.shape_slat_normalization is not None:
72
+ shape_z = shape_z * self.shape_slat_std.to(z.device) + self.shape_slat_mean.to(z.device)
73
+ if self.pbr_slat_normalization is not None:
74
+ z = z * self.pbr_slat_std.to(z.device) + self.pbr_slat_mean.to(z.device)
75
+ for i in range(0, z.shape[0], batch_size):
76
+ mesh, subs = self.shape_slat_dec(shape_z[i:i+batch_size], return_subs=True)
77
+ vox = self.pbr_slat_dec(z[i:i+batch_size], guide_subs=subs) * 0.5 + 0.5
78
+ reps.extend([
79
+ MeshWithVoxel(
80
+ m.vertices, m.faces,
81
+ origin = [-0.5, -0.5, -0.5],
82
+ voxel_size = 1 / self.resolution,
83
+ coords = v.coords[:, 1:],
84
+ attrs = v.feats,
85
+ voxel_shape = torch.Size([*v.shape, *v.spatial_shape]),
86
+ layout = self.layout,
87
+ )
88
+ for m, v in zip(mesh, vox)
89
+ ])
90
+ self._delete_slat_dec()
91
+ return reps
92
+
93
+ @torch.no_grad()
94
+ def visualize_sample(self, sample: dict):
95
+ shape_z = sample['concat_cond'].cuda()
96
+ z = sample['x_0'].cuda()
97
+ reps = self.decode_latent(z, shape_z)
98
+
99
+ # build camera
100
+ yaw = [0, np.pi/2, np.pi, 3*np.pi/2]
101
+ yaw_offset = -16 / 180 * np.pi
102
+ yaw = [y + yaw_offset for y in yaw]
103
+ pitch = [20 / 180 * np.pi for _ in range(4)]
104
+ exts, ints = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, 2, 30)
105
+
106
+ # render
107
+ renderer = PbrMeshRenderer()
108
+ renderer.rendering_options.resolution = 512
109
+ renderer.rendering_options.near = 1
110
+ renderer.rendering_options.far = 100
111
+ renderer.rendering_options.ssaa = 2
112
+ renderer.rendering_options.peel_layers = 8
113
+ envmap = EnvMap(torch.tensor(
114
+ cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB),
115
+ dtype=torch.float32, device='cuda'
116
+ ))
117
+
118
+ images = {}
119
+ for representation in reps:
120
+ image = {}
121
+ tile = [2, 2]
122
+ for j, (ext, intr) in enumerate(zip(exts, ints)):
123
+ res = renderer.render(representation, ext, intr, envmap=envmap)
124
+ for k, v in res.items():
125
+ if k not in images:
126
+ images[k] = []
127
+ if k not in image:
128
+ image[k] = torch.zeros(3, 1024, 1024).cuda()
129
+ image[k][:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = v
130
+ for k in images.keys():
131
+ images[k].append(image[k])
132
+ for k in images.keys():
133
+ images[k] = torch.stack(images[k], dim=0)
134
+ return images
135
+
136
+
137
+ class SLatPbr(SLatPbrVisMixin, StandardDatasetBase):
138
+ """
139
+ structured latent for sparse voxel pbr dataset
140
+
141
+ Args:
142
+ roots (str): path to the dataset
143
+ latent_key (str): key of the latent to be used
144
+ min_aesthetic_score (float): minimum aesthetic score
145
+ normalization (dict): normalization stats
146
+ resolution (int): resolution of decoded sparse voxel
147
+ attrs (list): attributes to be decoded
148
+ pretained_slat_dec (str): name of the pretrained slat decoder
149
+ slat_dec_path (str): path to the slat decoder, if given, will override the pretrained_slat_dec
150
+ slat_dec_ckpt (str): name of the slat decoder checkpoint
151
+ """
152
+ def __init__(self,
153
+ roots: str,
154
+ *,
155
+ resolution: int,
156
+ min_aesthetic_score: float = 5.0,
157
+ max_tokens: int = 32768,
158
+ full_pbr: bool = False,
159
+ pbr_slat_normalization: Optional[dict] = None,
160
+ shape_slat_normalization: Optional[dict] = None,
161
+ attrs: list[str] = ['base_color', 'metallic', 'roughness', 'emissive', 'alpha'],
162
+ pretrained_pbr_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/tex_dec_next_dc_f16c32_fp16',
163
+ pbr_slat_dec_path: Optional[str] = None,
164
+ pbr_slat_dec_ckpt: Optional[str] = None,
165
+ pretrained_shape_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16',
166
+ shape_slat_dec_path: Optional[str] = None,
167
+ shape_slat_dec_ckpt: Optional[str] = None,
168
+ **kwargs
169
+ ):
170
+ self.resolution = resolution
171
+ self.pbr_slat_normalization = pbr_slat_normalization
172
+ self.shape_slat_normalization = shape_slat_normalization
173
+ self.min_aesthetic_score = min_aesthetic_score
174
+ self.max_tokens = max_tokens
175
+ self.full_pbr = full_pbr
176
+ self.value_range = (0, 1)
177
+
178
+ super().__init__(
179
+ roots,
180
+ pretrained_pbr_slat_dec=pretrained_pbr_slat_dec,
181
+ pbr_slat_dec_path=pbr_slat_dec_path,
182
+ pbr_slat_dec_ckpt=pbr_slat_dec_ckpt,
183
+ pretrained_shape_slat_dec=pretrained_shape_slat_dec,
184
+ shape_slat_dec_path=shape_slat_dec_path,
185
+ shape_slat_dec_ckpt=shape_slat_dec_ckpt,
186
+ **kwargs
187
+ )
188
+
189
+ self.loads = [self.metadata.loc[sha256, 'pbr_latent_tokens'] for _, sha256 in self.instances]
190
+
191
+ if self.pbr_slat_normalization is not None:
192
+ self.pbr_slat_mean = torch.tensor(self.pbr_slat_normalization['mean']).reshape(1, -1)
193
+ self.pbr_slat_std = torch.tensor(self.pbr_slat_normalization['std']).reshape(1, -1)
194
+
195
+ if self.shape_slat_normalization is not None:
196
+ self.shape_slat_mean = torch.tensor(self.shape_slat_normalization['mean']).reshape(1, -1)
197
+ self.shape_slat_std = torch.tensor(self.shape_slat_normalization['std']).reshape(1, -1)
198
+
199
+ self.attrs = attrs
200
+ self.channels = {
201
+ 'base_color': 3,
202
+ 'metallic': 1,
203
+ 'roughness': 1,
204
+ 'emissive': 3,
205
+ 'alpha': 1,
206
+ }
207
+ self.layout = {}
208
+ start = 0
209
+ for attr in attrs:
210
+ self.layout[attr] = slice(start, start + self.channels[attr])
211
+ start += self.channels[attr]
212
+
213
+ def filter_metadata(self, metadata):
214
+ stats = {}
215
+ metadata = metadata[metadata['pbr_latent_encoded'] == True]
216
+ stats['With PBR latent'] = len(metadata)
217
+ metadata = metadata[metadata['shape_latent_encoded'] == True]
218
+ stats['With shape latent'] = len(metadata)
219
+ metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score]
220
+ stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata)
221
+ metadata = metadata[metadata['pbr_latent_tokens'] <= self.max_tokens]
222
+ stats[f'Num tokens <= {self.max_tokens}'] = len(metadata)
223
+ if self.full_pbr:
224
+ metadata = metadata[metadata['num_basecolor_tex'] > 0]
225
+ metadata = metadata[metadata['num_metallic_tex'] > 0]
226
+ metadata = metadata[metadata['num_roughness_tex'] > 0]
227
+ stats['Full PBR'] = len(metadata)
228
+ return metadata, stats
229
+
230
+ def get_instance(self, root, instance):
231
+ # PBR latent
232
+ data = np.load(os.path.join(root['pbr_latent'], f'{instance}.npz'))
233
+ coords = torch.tensor(data['coords']).int()
234
+ coords = torch.cat([torch.zeros_like(coords)[:, :1], coords], dim=1)
235
+ feats = torch.tensor(data['feats']).float()
236
+ if self.pbr_slat_normalization is not None:
237
+ feats = (feats - self.pbr_slat_mean) / self.pbr_slat_std
238
+ pbr_z = SparseTensor(feats, coords)
239
+
240
+ # Shape latent
241
+ data = np.load(os.path.join(root['shape_latent'], f'{instance}.npz'))
242
+ coords = torch.tensor(data['coords']).int()
243
+ coords = torch.cat([torch.zeros_like(coords)[:, :1], coords], dim=1)
244
+ feats = torch.tensor(data['feats']).float()
245
+ if self.shape_slat_normalization is not None:
246
+ feats = (feats - self.shape_slat_mean) / self.shape_slat_std
247
+ shape_z = SparseTensor(feats, coords)
248
+
249
+ assert torch.equal(shape_z.coords, pbr_z.coords), \
250
+ f"Shape latent and PBR latent have different coordinates: {shape_z.coords.shape} vs {pbr_z.coords.shape}"
251
+
252
+ return {
253
+ 'x_0': pbr_z,
254
+ 'concat_cond': shape_z,
255
+ }
256
+
257
+ @staticmethod
258
+ def collate_fn(batch, split_size=None):
259
+ if split_size is None:
260
+ group_idx = [list(range(len(batch)))]
261
+ else:
262
+ group_idx = load_balanced_group_indices([b['x_0'].feats.shape[0] for b in batch], split_size)
263
+ packs = []
264
+ for group in group_idx:
265
+ sub_batch = [batch[i] for i in group]
266
+ pack = {}
267
+
268
+ keys = [k for k in sub_batch[0].keys()]
269
+ for k in keys:
270
+ if isinstance(sub_batch[0][k], torch.Tensor):
271
+ pack[k] = torch.stack([b[k] for b in sub_batch])
272
+ elif isinstance(sub_batch[0][k], SparseTensor):
273
+ pack[k] = sparse_cat([b[k] for b in sub_batch], dim=0)
274
+ elif isinstance(sub_batch[0][k], list):
275
+ pack[k] = sum([b[k] for b in sub_batch], [])
276
+ else:
277
+ pack[k] = [b[k] for b in sub_batch]
278
+
279
+ packs.append(pack)
280
+
281
+ if split_size is None:
282
+ return packs[0]
283
+ return packs
284
+
285
+
286
+ class ImageConditionedSLatPbr(ImageConditionedMixin, SLatPbr):
287
+ """
288
+ Image conditioned structured latent dataset
289
+ """
290
+ pass
trellis2/models/__init__.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ __attributes = {
4
+ # Sparse Structure
5
+ 'SparseStructureEncoder': 'sparse_structure_vae',
6
+ 'SparseStructureDecoder': 'sparse_structure_vae',
7
+ 'SparseStructureFlowModel': 'sparse_structure_flow',
8
+
9
+ # SLat Generation
10
+ 'SLatFlowModel': 'structured_latent_flow',
11
+ 'ElasticSLatFlowModel': 'structured_latent_flow',
12
+
13
+ # SC-VAEs
14
+ 'SparseUnetVaeEncoder': 'sc_vaes.sparse_unet_vae',
15
+ 'SparseUnetVaeDecoder': 'sc_vaes.sparse_unet_vae',
16
+ 'FlexiDualGridVaeEncoder': 'sc_vaes.fdg_vae',
17
+ 'FlexiDualGridVaeDecoder': 'sc_vaes.fdg_vae'
18
+ }
19
+
20
+ __submodules = []
21
+
22
+ __all__ = list(__attributes.keys()) + __submodules
23
+
24
+ def __getattr__(name):
25
+ if name not in globals():
26
+ if name in __attributes:
27
+ module_name = __attributes[name]
28
+ module = importlib.import_module(f".{module_name}", __name__)
29
+ globals()[name] = getattr(module, name)
30
+ elif name in __submodules:
31
+ module = importlib.import_module(f".{name}", __name__)
32
+ globals()[name] = module
33
+ else:
34
+ raise AttributeError(f"module {__name__} has no attribute {name}")
35
+ return globals()[name]
36
+
37
+
38
+ def from_pretrained(path: str, **kwargs):
39
+ """
40
+ Load a model from a pretrained checkpoint.
41
+
42
+ Args:
43
+ path: The path to the checkpoint. Can be either local path or a Hugging Face model name.
44
+ NOTE: config file and model file should take the name f'{path}.json' and f'{path}.safetensors' respectively.
45
+ **kwargs: Additional arguments for the model constructor.
46
+ """
47
+ import os
48
+ import json
49
+ from safetensors.torch import load_file
50
+ is_local = os.path.exists(f"{path}.json") and os.path.exists(f"{path}.safetensors")
51
+
52
+ if is_local:
53
+ config_file = f"{path}.json"
54
+ model_file = f"{path}.safetensors"
55
+ else:
56
+ from huggingface_hub import hf_hub_download
57
+ path_parts = path.split('/')
58
+ repo_id = f'{path_parts[0]}/{path_parts[1]}'
59
+ model_name = '/'.join(path_parts[2:])
60
+ config_file = hf_hub_download(repo_id, f"{model_name}.json")
61
+ model_file = hf_hub_download(repo_id, f"{model_name}.safetensors")
62
+
63
+ with open(config_file, 'r') as f:
64
+ config = json.load(f)
65
+ model = __getattr__(config['name'])(**config['args'], **kwargs)
66
+ model.load_state_dict(load_file(model_file), strict=False)
67
+
68
+ return model
69
+
70
+
71
+ # For Pylance
72
+ if __name__ == '__main__':
73
+ from .sparse_structure_vae import SparseStructureEncoder, SparseStructureDecoder
74
+ from .sparse_structure_flow import SparseStructureFlowModel
75
+ from .structured_latent_flow import SLatFlowModel, ElasticSLatFlowModel
76
+
77
+ from .sc_vaes.sparse_unet_vae import SparseUnetVaeEncoder, SparseUnetVaeDecoder
78
+ from .sc_vaes.fdg_vae import FlexiDualGridVaeEncoder, FlexiDualGridVaeDecoder
trellis2/models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (3.97 kB). View file
 
trellis2/models/__pycache__/sparse_elastic_mixin.cpython-311.pyc ADDED
Binary file (1.94 kB). View file
 
trellis2/models/__pycache__/sparse_structure_flow.cpython-311.pyc ADDED
Binary file (16.9 kB). View file
 
trellis2/models/__pycache__/sparse_structure_vae.cpython-311.pyc ADDED
Binary file (17.3 kB). View file
 
trellis2/models/__pycache__/structured_latent_flow.cpython-311.pyc ADDED
Binary file (12.9 kB). View file
 
trellis2/models/sc_vaes/__pycache__/fdg_vae.cpython-311.pyc ADDED
Binary file (7.2 kB). View file
 
trellis2/models/sc_vaes/__pycache__/sparse_unet_vae.cpython-311.pyc ADDED
Binary file (34.6 kB). View file
 
trellis2/models/sc_vaes/fdg_vae.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from ...modules import sparse as sp
6
+ from .sparse_unet_vae import (
7
+ SparseResBlock3d,
8
+ SparseConvNeXtBlock3d,
9
+
10
+ SparseResBlockDownsample3d,
11
+ SparseResBlockUpsample3d,
12
+ SparseResBlockS2C3d,
13
+ SparseResBlockC2S3d,
14
+ )
15
+ from .sparse_unet_vae import (
16
+ SparseUnetVaeEncoder,
17
+ SparseUnetVaeDecoder,
18
+ )
19
+ from ...representations import Mesh
20
+ from o_voxel.convert import flexible_dual_grid_to_mesh
21
+
22
+
23
+ class FlexiDualGridVaeEncoder(SparseUnetVaeEncoder):
24
+ def __init__(
25
+ self,
26
+ model_channels: List[int],
27
+ latent_channels: int,
28
+ num_blocks: List[int],
29
+ block_type: List[str],
30
+ down_block_type: List[str],
31
+ block_args: List[Dict[str, Any]],
32
+ use_fp16: bool = False,
33
+ ):
34
+ super().__init__(
35
+ 6,
36
+ model_channels,
37
+ latent_channels,
38
+ num_blocks,
39
+ block_type,
40
+ down_block_type,
41
+ block_args,
42
+ use_fp16,
43
+ )
44
+
45
+ def forward(self, vertices: sp.SparseTensor, intersected: sp.SparseTensor, sample_posterior=False, return_raw=False):
46
+ x = vertices.replace(torch.cat([
47
+ vertices.feats - 0.5,
48
+ intersected.feats.float() - 0.5,
49
+ ], dim=1))
50
+ return super().forward(x, sample_posterior, return_raw)
51
+
52
+
53
+ class FlexiDualGridVaeDecoder(SparseUnetVaeDecoder):
54
+ def __init__(
55
+ self,
56
+ resolution: int,
57
+ model_channels: List[int],
58
+ latent_channels: int,
59
+ num_blocks: List[int],
60
+ block_type: List[str],
61
+ up_block_type: List[str],
62
+ block_args: List[Dict[str, Any]],
63
+ voxel_margin: float = 0.5,
64
+ use_fp16: bool = False,
65
+ ):
66
+ self.resolution = resolution
67
+ self.voxel_margin = voxel_margin
68
+
69
+ super().__init__(
70
+ 7,
71
+ model_channels,
72
+ latent_channels,
73
+ num_blocks,
74
+ block_type,
75
+ up_block_type,
76
+ block_args,
77
+ use_fp16,
78
+ )
79
+
80
+ def set_resolution(self, resolution: int) -> None:
81
+ self.resolution = resolution
82
+
83
+ def forward(self, x: sp.SparseTensor, gt_intersected: sp.SparseTensor = None, **kwargs):
84
+ decoded = super().forward(x, **kwargs)
85
+ if self.training:
86
+ h, subs_gt, subs = decoded
87
+ vertices = h.replace((1 + 2 * self.voxel_margin) * F.sigmoid(h.feats[..., 0:3]) - self.voxel_margin)
88
+ intersected_logits = h.replace(h.feats[..., 3:6])
89
+ quad_lerp = h.replace(F.softplus(h.feats[..., 6:7]))
90
+ mesh = [Mesh(*flexible_dual_grid_to_mesh(
91
+ v.coords[:, 1:], v.feats, i.feats, q.feats,
92
+ aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],
93
+ grid_size=self.resolution,
94
+ train=True
95
+ )) for v, i, q in zip(vertices, gt_intersected, quad_lerp)]
96
+ return mesh, vertices, intersected_logits, subs_gt, subs
97
+ else:
98
+ out_list = list(decoded) if isinstance(decoded, tuple) else [decoded]
99
+ h = out_list[0]
100
+ vertices = h.replace((1 + 2 * self.voxel_margin) * F.sigmoid(h.feats[..., 0:3]) - self.voxel_margin)
101
+ intersected = h.replace(h.feats[..., 3:6] > 0)
102
+ quad_lerp = h.replace(F.softplus(h.feats[..., 6:7]))
103
+ mesh = [Mesh(*flexible_dual_grid_to_mesh(
104
+ v.coords[:, 1:], v.feats, i.feats, q.feats,
105
+ aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]],
106
+ grid_size=self.resolution,
107
+ train=False
108
+ )) for v, i, q in zip(vertices, intersected, quad_lerp)]
109
+ out_list[0] = mesh
110
+ return out_list[0] if len(out_list) == 1 else tuple(out_list)
trellis2/models/sc_vaes/sparse_unet_vae.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import torch.utils.checkpoint
6
+ from ...modules.utils import convert_module_to_f16, convert_module_to_f32, zero_module
7
+ from ...modules import sparse as sp
8
+ from ...modules.norm import LayerNorm32
9
+
10
+
11
+ class SparseResBlock3d(nn.Module):
12
+ def __init__(
13
+ self,
14
+ channels: int,
15
+ out_channels: Optional[int] = None,
16
+ downsample: bool = False,
17
+ upsample: bool = False,
18
+ resample_mode: Literal['nearest', 'spatial2channel'] = 'nearest',
19
+ use_checkpoint: bool = False,
20
+ ):
21
+ super().__init__()
22
+ self.channels = channels
23
+ self.out_channels = out_channels or channels
24
+ self.downsample = downsample
25
+ self.upsample = upsample
26
+ self.resample_mode = resample_mode
27
+ self.use_checkpoint = use_checkpoint
28
+
29
+ assert not (downsample and upsample), "Cannot downsample and upsample at the same time"
30
+
31
+ self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
32
+ self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6)
33
+ if resample_mode == 'nearest':
34
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3)
35
+ elif resample_mode =='spatial2channel' and not self.downsample:
36
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels * 8, 3)
37
+ elif resample_mode =='spatial2channel' and self.downsample:
38
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels // 8, 3)
39
+ self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3))
40
+ if resample_mode == 'nearest':
41
+ self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity()
42
+ elif resample_mode =='spatial2channel' and self.downsample:
43
+ self.skip_connection = lambda x: x.replace(x.feats.reshape(x.feats.shape[0], out_channels, channels * 8 // out_channels).mean(dim=-1))
44
+ elif resample_mode =='spatial2channel' and not self.downsample:
45
+ self.skip_connection = lambda x: x.replace(x.feats.repeat_interleave(out_channels // (channels // 8), dim=1))
46
+ self.updown = None
47
+ if self.downsample:
48
+ if resample_mode == 'nearest':
49
+ self.updown = sp.SparseDownsample(2)
50
+ elif resample_mode =='spatial2channel':
51
+ self.updown = sp.SparseSpatial2Channel(2)
52
+ elif self.upsample:
53
+ self.to_subdiv = sp.SparseLinear(channels, 8)
54
+ if resample_mode == 'nearest':
55
+ self.updown = sp.SparseUpsample(2)
56
+ elif resample_mode =='spatial2channel':
57
+ self.updown = sp.SparseChannel2Spatial(2)
58
+
59
+ def _updown(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor:
60
+ if self.downsample:
61
+ x = self.updown(x)
62
+ elif self.upsample:
63
+ x = self.updown(x, subdiv.replace(subdiv.feats > 0))
64
+ return x
65
+
66
+ def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
67
+ subdiv = None
68
+ if self.upsample:
69
+ subdiv = self.to_subdiv(x)
70
+ h = x.replace(self.norm1(x.feats))
71
+ h = h.replace(F.silu(h.feats))
72
+ if self.resample_mode == 'spatial2channel':
73
+ h = self.conv1(h)
74
+ h = self._updown(h, subdiv)
75
+ x = self._updown(x, subdiv)
76
+ if self.resample_mode == 'nearest':
77
+ h = self.conv1(h)
78
+ h = h.replace(self.norm2(h.feats))
79
+ h = h.replace(F.silu(h.feats))
80
+ h = self.conv2(h)
81
+ h = h + self.skip_connection(x)
82
+ if self.upsample:
83
+ return h, subdiv
84
+ return h
85
+
86
+ def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
87
+ if self.use_checkpoint:
88
+ return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False)
89
+ else:
90
+ return self._forward(x)
91
+
92
+
93
+ class SparseResBlockDownsample3d(nn.Module):
94
+ def __init__(
95
+ self,
96
+ channels: int,
97
+ out_channels: Optional[int] = None,
98
+ use_checkpoint: bool = False,
99
+ ):
100
+ super().__init__()
101
+ self.channels = channels
102
+ self.out_channels = out_channels or channels
103
+ self.use_checkpoint = use_checkpoint
104
+
105
+ self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
106
+ self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6)
107
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3)
108
+ self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3))
109
+ self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity()
110
+ self.updown = sp.SparseDownsample(2)
111
+
112
+ def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
113
+ h = x.replace(self.norm1(x.feats))
114
+ h = h.replace(F.silu(h.feats))
115
+ h = self.updown(h)
116
+ x = self.updown(x)
117
+ h = self.conv1(h)
118
+ h = h.replace(self.norm2(h.feats))
119
+ h = h.replace(F.silu(h.feats))
120
+ h = self.conv2(h)
121
+ h = h + self.skip_connection(x)
122
+ return h
123
+
124
+ def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
125
+ if self.use_checkpoint:
126
+ return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False)
127
+ else:
128
+ return self._forward(x)
129
+
130
+
131
+ class SparseResBlockUpsample3d(nn.Module):
132
+ def __init__(
133
+ self,
134
+ channels: int,
135
+ out_channels: Optional[int] = None,
136
+ use_checkpoint: bool = False,
137
+ pred_subdiv: bool = True,
138
+ ):
139
+ super().__init__()
140
+ self.channels = channels
141
+ self.out_channels = out_channels or channels
142
+ self.use_checkpoint = use_checkpoint
143
+ self.pred_subdiv = pred_subdiv
144
+
145
+ self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
146
+ self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6)
147
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3)
148
+ self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3))
149
+ self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity()
150
+ if self.pred_subdiv:
151
+ self.to_subdiv = sp.SparseLinear(channels, 8)
152
+ self.updown = sp.SparseUpsample(2)
153
+
154
+ def _forward(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor:
155
+ if self.pred_subdiv:
156
+ subdiv = self.to_subdiv(x)
157
+ h = x.replace(self.norm1(x.feats))
158
+ h = h.replace(F.silu(h.feats))
159
+ subdiv_binarized = subdiv.replace(subdiv.feats > 0) if subdiv is not None else None
160
+ h = self.updown(h, subdiv_binarized)
161
+ x = self.updown(x, subdiv_binarized)
162
+ h = self.conv1(h)
163
+ h = h.replace(self.norm2(h.feats))
164
+ h = h.replace(F.silu(h.feats))
165
+ h = self.conv2(h)
166
+ h = h + self.skip_connection(x)
167
+ if self.pred_subdiv:
168
+ return h, subdiv
169
+ else:
170
+ return h
171
+
172
+ def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
173
+ if self.use_checkpoint:
174
+ return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False)
175
+ else:
176
+ return self._forward(x)
177
+
178
+
179
+ class SparseResBlockS2C3d(nn.Module):
180
+ def __init__(
181
+ self,
182
+ channels: int,
183
+ out_channels: Optional[int] = None,
184
+ use_checkpoint: bool = False,
185
+ ):
186
+ super().__init__()
187
+ self.channels = channels
188
+ self.out_channels = out_channels or channels
189
+ self.use_checkpoint = use_checkpoint
190
+
191
+ self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
192
+ self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6)
193
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels // 8, 3)
194
+ self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3))
195
+ self.skip_connection = lambda x: x.replace(x.feats.reshape(x.feats.shape[0], out_channels, channels * 8 // out_channels).mean(dim=-1))
196
+ self.updown = sp.SparseSpatial2Channel(2)
197
+
198
+ def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
199
+ h = x.replace(self.norm1(x.feats))
200
+ h = h.replace(F.silu(h.feats))
201
+ h = self.conv1(h)
202
+ h = self.updown(h)
203
+ x = self.updown(x)
204
+ h = h.replace(self.norm2(h.feats))
205
+ h = h.replace(F.silu(h.feats))
206
+ h = self.conv2(h)
207
+ h = h + self.skip_connection(x)
208
+ return h
209
+
210
+ def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
211
+ if self.use_checkpoint:
212
+ return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False)
213
+ else:
214
+ return self._forward(x)
215
+
216
+
217
+ class SparseResBlockC2S3d(nn.Module):
218
+ def __init__(
219
+ self,
220
+ channels: int,
221
+ out_channels: Optional[int] = None,
222
+ use_checkpoint: bool = False,
223
+ pred_subdiv: bool = True,
224
+ ):
225
+ super().__init__()
226
+ self.channels = channels
227
+ self.out_channels = out_channels or channels
228
+ self.use_checkpoint = use_checkpoint
229
+ self.pred_subdiv = pred_subdiv
230
+
231
+ self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
232
+ self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6)
233
+ self.conv1 = sp.SparseConv3d(channels, self.out_channels * 8, 3)
234
+ self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3))
235
+ self.skip_connection = lambda x: x.replace(x.feats.repeat_interleave(out_channels // (channels // 8), dim=1))
236
+ if pred_subdiv:
237
+ self.to_subdiv = sp.SparseLinear(channels, 8)
238
+ self.updown = sp.SparseChannel2Spatial(2)
239
+
240
+ def _forward(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor:
241
+ if self.pred_subdiv:
242
+ subdiv = self.to_subdiv(x)
243
+ h = x.replace(self.norm1(x.feats))
244
+ h = h.replace(F.silu(h.feats))
245
+ h = self.conv1(h)
246
+ subdiv_binarized = subdiv.replace(subdiv.feats > 0) if subdiv is not None else None
247
+ h = self.updown(h, subdiv_binarized)
248
+ x = self.updown(x, subdiv_binarized)
249
+ h = h.replace(self.norm2(h.feats))
250
+ h = h.replace(F.silu(h.feats))
251
+ h = self.conv2(h)
252
+ h = h + self.skip_connection(x)
253
+ if self.pred_subdiv:
254
+ return h, subdiv
255
+ else:
256
+ return h
257
+
258
+ def forward(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor:
259
+ if self.use_checkpoint:
260
+ return torch.utils.checkpoint.checkpoint(self._forward, x, subdiv, use_reentrant=False)
261
+ else:
262
+ return self._forward(x, subdiv)
263
+
264
+
265
+ class SparseConvNeXtBlock3d(nn.Module):
266
+ def __init__(
267
+ self,
268
+ channels: int,
269
+ mlp_ratio: float = 4.0,
270
+ use_checkpoint: bool = False,
271
+ ):
272
+ super().__init__()
273
+ self.channels = channels
274
+ self.use_checkpoint = use_checkpoint
275
+
276
+ self.norm = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)
277
+ self.conv = sp.SparseConv3d(channels, channels, 3)
278
+ self.mlp = nn.Sequential(
279
+ nn.Linear(channels, int(channels * mlp_ratio)),
280
+ nn.SiLU(),
281
+ zero_module(nn.Linear(int(channels * mlp_ratio), channels)),
282
+ )
283
+
284
+ def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
285
+ h = self.conv(x)
286
+ h = h.replace(self.norm(h.feats))
287
+ h = h.replace(self.mlp(h.feats))
288
+ return h + x
289
+
290
+ def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
291
+ if self.use_checkpoint:
292
+ return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False)
293
+ else:
294
+ return self._forward(x)
295
+
296
+
297
+ class SparseUnetVaeEncoder(nn.Module):
298
+ """
299
+ Sparse Swin Transformer Unet VAE model.
300
+ """
301
+ def __init__(
302
+ self,
303
+ in_channels: int,
304
+ model_channels: List[int],
305
+ latent_channels: int,
306
+ num_blocks: List[int],
307
+ block_type: List[str],
308
+ down_block_type: List[str],
309
+ block_args: List[Dict[str, Any]],
310
+ use_fp16: bool = False,
311
+ ):
312
+ super().__init__()
313
+ self.in_channels = in_channels
314
+ self.model_channels = model_channels
315
+ self.num_blocks = num_blocks
316
+ self.dtype = torch.float16 if use_fp16 else torch.float32
317
+ self.dtype = torch.float16 if use_fp16 else torch.float32
318
+
319
+ self.input_layer = sp.SparseLinear(in_channels, model_channels[0])
320
+ self.to_latent = sp.SparseLinear(model_channels[-1], 2 * latent_channels)
321
+
322
+ self.blocks = nn.ModuleList([])
323
+ for i in range(len(num_blocks)):
324
+ self.blocks.append(nn.ModuleList([]))
325
+ for j in range(num_blocks[i]):
326
+ self.blocks[-1].append(
327
+ globals()[block_type[i]](
328
+ model_channels[i],
329
+ **block_args[i],
330
+ )
331
+ )
332
+ if i < len(num_blocks) - 1:
333
+ self.blocks[-1].append(
334
+ globals()[down_block_type[i]](
335
+ model_channels[i],
336
+ model_channels[i+1],
337
+ **block_args[i],
338
+ )
339
+ )
340
+
341
+ self.initialize_weights()
342
+ if use_fp16:
343
+ self.convert_to_fp16()
344
+
345
+ @property
346
+ def device(self) -> torch.device:
347
+ """
348
+ Return the device of the model.
349
+ """
350
+ return next(self.parameters()).device
351
+
352
+ def convert_to_fp16(self) -> None:
353
+ """
354
+ Convert the torso of the model to float16.
355
+ """
356
+ self.blocks.apply(convert_module_to_f16)
357
+
358
+ def convert_to_fp32(self) -> None:
359
+ """
360
+ Convert the torso of the model to float32.
361
+ """
362
+ self.blocks.apply(convert_module_to_f32)
363
+
364
+ def initialize_weights(self) -> None:
365
+ # Initialize transformer layers:
366
+ def _basic_init(module):
367
+ if isinstance(module, nn.Linear):
368
+ torch.nn.init.xavier_uniform_(module.weight)
369
+ if module.bias is not None:
370
+ nn.init.constant_(module.bias, 0)
371
+ self.apply(_basic_init)
372
+
373
+ def forward(self, x: sp.SparseTensor, sample_posterior=False, return_raw=False):
374
+ h = self.input_layer(x)
375
+ h = h.type(self.dtype)
376
+ for i, res in enumerate(self.blocks):
377
+ for j, block in enumerate(res):
378
+ h = block(h)
379
+ h = h.type(x.dtype)
380
+ h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
381
+ h = self.to_latent(h)
382
+
383
+ # Sample from the posterior distribution
384
+ mean, logvar = h.feats.chunk(2, dim=-1)
385
+ if sample_posterior:
386
+ std = torch.exp(0.5 * logvar)
387
+ z = mean + std * torch.randn_like(std)
388
+ else:
389
+ z = mean
390
+ z = h.replace(z)
391
+
392
+ if return_raw:
393
+ return z, mean, logvar
394
+ else:
395
+ return z
396
+
397
+
398
+ class SparseUnetVaeDecoder(nn.Module):
399
+ """
400
+ Sparse Swin Transformer Unet VAE model.
401
+ """
402
+ def __init__(
403
+ self,
404
+ out_channels: int,
405
+ model_channels: List[int],
406
+ latent_channels: int,
407
+ num_blocks: List[int],
408
+ block_type: List[str],
409
+ up_block_type: List[str],
410
+ block_args: List[Dict[str, Any]],
411
+ use_fp16: bool = False,
412
+ pred_subdiv: bool = True,
413
+ ):
414
+ super().__init__()
415
+ self.out_channels = out_channels
416
+ self.model_channels = model_channels
417
+ self.num_blocks = num_blocks
418
+ self.use_fp16 = use_fp16
419
+ self.pred_subdiv = pred_subdiv
420
+ self.dtype = torch.float16 if use_fp16 else torch.float32
421
+ self.low_vram = False
422
+
423
+ self.output_layer = sp.SparseLinear(model_channels[-1], out_channels)
424
+ self.from_latent = sp.SparseLinear(latent_channels, model_channels[0])
425
+
426
+ self.blocks = nn.ModuleList([])
427
+ for i in range(len(num_blocks)):
428
+ self.blocks.append(nn.ModuleList([]))
429
+ for j in range(num_blocks[i]):
430
+ self.blocks[-1].append(
431
+ globals()[block_type[i]](
432
+ model_channels[i],
433
+ **block_args[i],
434
+ )
435
+ )
436
+ if i < len(num_blocks) - 1:
437
+ self.blocks[-1].append(
438
+ globals()[up_block_type[i]](
439
+ model_channels[i],
440
+ model_channels[i+1],
441
+ pred_subdiv=pred_subdiv,
442
+ **block_args[i],
443
+ )
444
+ )
445
+
446
+ self.initialize_weights()
447
+ if use_fp16:
448
+ self.convert_to_fp16()
449
+
450
+ @property
451
+ def device(self) -> torch.device:
452
+ """
453
+ Return the device of the model.
454
+ """
455
+ return next(self.parameters()).device
456
+
457
+ def convert_to_fp16(self) -> None:
458
+ """
459
+ Convert the torso of the model to float16.
460
+ """
461
+ self.blocks.apply(convert_module_to_f16)
462
+
463
+ def convert_to_fp32(self) -> None:
464
+ """
465
+ Convert the torso of the model to float32.
466
+ """
467
+ self.blocks.apply(convert_module_to_f32)
468
+
469
+ def initialize_weights(self) -> None:
470
+ # Initialize transformer layers:
471
+ def _basic_init(module):
472
+ if isinstance(module, nn.Linear):
473
+ torch.nn.init.xavier_uniform_(module.weight)
474
+ if module.bias is not None:
475
+ nn.init.constant_(module.bias, 0)
476
+ self.apply(_basic_init)
477
+
478
+ def forward(self, x: sp.SparseTensor, guide_subs: Optional[List[sp.SparseTensor]] = None, return_subs: bool = False) -> sp.SparseTensor:
479
+ assert guide_subs is None or self.pred_subdiv == False, "Only decoders with pred_subdiv=False can be used with guide_subs"
480
+ assert return_subs == False or self.pred_subdiv == True, "Only decoders with pred_subdiv=True can be used with return_subs"
481
+
482
+ h = self.from_latent(x)
483
+ h = h.type(self.dtype)
484
+ subs_gt = []
485
+ subs = []
486
+ for i, res in enumerate(self.blocks):
487
+ for j, block in enumerate(res):
488
+ if i < len(self.blocks) - 1 and j == len(res) - 1:
489
+ if self.pred_subdiv:
490
+ if self.training:
491
+ subs_gt.append(h.get_spatial_cache('subdivision'))
492
+ h, sub = block(h)
493
+ subs.append(sub)
494
+ else:
495
+ h = block(h, subdiv=guide_subs[i] if guide_subs is not None else None)
496
+ else:
497
+ h = block(h)
498
+ h = h.type(x.dtype)
499
+ h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
500
+ h = self.output_layer(h)
501
+ if self.training and self.pred_subdiv:
502
+ return h, subs_gt, subs
503
+ else:
504
+ if return_subs:
505
+ return h, subs
506
+ else:
507
+ return h
508
+
509
+ def upsample(self, x: sp.SparseTensor, upsample_times: int) -> torch.Tensor:
510
+ assert self.pred_subdiv == True, "Only decoders with pred_subdiv=True can be used with upsampling"
511
+
512
+ h = self.from_latent(x)
513
+ h = h.type(self.dtype)
514
+ for i, res in enumerate(self.blocks):
515
+ if i == upsample_times:
516
+ return h.coords
517
+ for j, block in enumerate(res):
518
+ if i < len(self.blocks) - 1 and j == len(res) - 1:
519
+ h, sub = block(h)
520
+ else:
521
+ h = block(h)
522
+
trellis2/models/sparse_elastic_mixin.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ from typing import *
3
+ import math
4
+ from ..modules import sparse as sp
5
+ from ..utils.elastic_utils import ElasticModuleMixin
6
+
7
+
8
+ class SparseTransformerElasticMixin(ElasticModuleMixin):
9
+ def _get_input_size(self, x: sp.SparseTensor, *args, **kwargs):
10
+ return x.feats.shape[0]
11
+
12
+ @contextmanager
13
+ def with_mem_ratio(self, mem_ratio=1.0):
14
+ if mem_ratio == 1.0:
15
+ yield 1.0
16
+ return
17
+ num_blocks = len(self.blocks)
18
+ num_checkpoint_blocks = min(math.ceil((1 - mem_ratio) * num_blocks) + 1, num_blocks)
19
+ exact_mem_ratio = 1 - (num_checkpoint_blocks - 1) / num_blocks
20
+ for i in range(num_blocks):
21
+ self.blocks[i].use_checkpoint = i < num_checkpoint_blocks
22
+ yield exact_mem_ratio
23
+ for i in range(num_blocks):
24
+ self.blocks[i].use_checkpoint = False
trellis2/models/sparse_structure_flow.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ from functools import partial
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import numpy as np
7
+ from ..modules.utils import convert_module_to, manual_cast, str_to_dtype
8
+ from ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlock
9
+ from ..modules.attention import RotaryPositionEmbedder
10
+
11
+
12
+ class TimestepEmbedder(nn.Module):
13
+ """
14
+ Embeds scalar timesteps into vector representations.
15
+ """
16
+ def __init__(self, hidden_size, frequency_embedding_size=256):
17
+ super().__init__()
18
+ self.mlp = nn.Sequential(
19
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
20
+ nn.SiLU(),
21
+ nn.Linear(hidden_size, hidden_size, bias=True),
22
+ )
23
+ self.frequency_embedding_size = frequency_embedding_size
24
+
25
+ @staticmethod
26
+ def timestep_embedding(t, dim, max_period=10000):
27
+ """
28
+ Create sinusoidal timestep embeddings.
29
+
30
+ Args:
31
+ t: a 1-D Tensor of N indices, one per batch element.
32
+ These may be fractional.
33
+ dim: the dimension of the output.
34
+ max_period: controls the minimum frequency of the embeddings.
35
+
36
+ Returns:
37
+ an (N, D) Tensor of positional embeddings.
38
+ """
39
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
40
+ half = dim // 2
41
+ freqs = torch.exp(
42
+ -np.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
43
+ ).to(device=t.device)
44
+ args = t[:, None].float() * freqs[None]
45
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
46
+ if dim % 2:
47
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
48
+ return embedding
49
+
50
+ def forward(self, t):
51
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
52
+ t_emb = self.mlp(t_freq)
53
+ return t_emb
54
+
55
+
56
+ class SparseStructureFlowModel(nn.Module):
57
+ def __init__(
58
+ self,
59
+ resolution: int,
60
+ in_channels: int,
61
+ model_channels: int,
62
+ cond_channels: int,
63
+ out_channels: int,
64
+ num_blocks: int,
65
+ num_heads: Optional[int] = None,
66
+ num_head_channels: Optional[int] = 64,
67
+ mlp_ratio: float = 4,
68
+ pe_mode: Literal["ape", "rope"] = "ape",
69
+ rope_freq: Tuple[float, float] = (1.0, 10000.0),
70
+ dtype: str = 'float32',
71
+ use_checkpoint: bool = False,
72
+ share_mod: bool = False,
73
+ initialization: str = 'vanilla',
74
+ qk_rms_norm: bool = False,
75
+ qk_rms_norm_cross: bool = False,
76
+ **kwargs
77
+ ):
78
+ super().__init__()
79
+ self.resolution = resolution
80
+ self.in_channels = in_channels
81
+ self.model_channels = model_channels
82
+ self.cond_channels = cond_channels
83
+ self.out_channels = out_channels
84
+ self.num_blocks = num_blocks
85
+ self.num_heads = num_heads or model_channels // num_head_channels
86
+ self.mlp_ratio = mlp_ratio
87
+ self.pe_mode = pe_mode
88
+ self.use_checkpoint = use_checkpoint
89
+ self.share_mod = share_mod
90
+ self.initialization = initialization
91
+ self.qk_rms_norm = qk_rms_norm
92
+ self.qk_rms_norm_cross = qk_rms_norm_cross
93
+ self.dtype = str_to_dtype(dtype)
94
+
95
+ self.t_embedder = TimestepEmbedder(model_channels)
96
+ if share_mod:
97
+ self.adaLN_modulation = nn.Sequential(
98
+ nn.SiLU(),
99
+ nn.Linear(model_channels, 6 * model_channels, bias=True)
100
+ )
101
+
102
+ if pe_mode == "ape":
103
+ pos_embedder = AbsolutePositionEmbedder(model_channels, 3)
104
+ coords = torch.meshgrid(*[torch.arange(res, device=self.device) for res in [resolution] * 3], indexing='ij')
105
+ coords = torch.stack(coords, dim=-1).reshape(-1, 3)
106
+ pos_emb = pos_embedder(coords)
107
+ self.register_buffer("pos_emb", pos_emb)
108
+ elif pe_mode == "rope":
109
+ pos_embedder = RotaryPositionEmbedder(self.model_channels // self.num_heads, 3)
110
+ coords = torch.meshgrid(*[torch.arange(res, device=self.device) for res in [resolution] * 3], indexing='ij')
111
+ coords = torch.stack(coords, dim=-1).reshape(-1, 3)
112
+ rope_phases = pos_embedder(coords)
113
+ self.register_buffer("rope_phases", rope_phases)
114
+
115
+ if pe_mode != "rope":
116
+ self.rope_phases = None
117
+
118
+ self.input_layer = nn.Linear(in_channels, model_channels)
119
+
120
+ self.blocks = nn.ModuleList([
121
+ ModulatedTransformerCrossBlock(
122
+ model_channels,
123
+ cond_channels,
124
+ num_heads=self.num_heads,
125
+ mlp_ratio=self.mlp_ratio,
126
+ attn_mode='full',
127
+ use_checkpoint=self.use_checkpoint,
128
+ use_rope=(pe_mode == "rope"),
129
+ rope_freq=rope_freq,
130
+ share_mod=share_mod,
131
+ qk_rms_norm=self.qk_rms_norm,
132
+ qk_rms_norm_cross=self.qk_rms_norm_cross,
133
+ )
134
+ for _ in range(num_blocks)
135
+ ])
136
+
137
+ self.out_layer = nn.Linear(model_channels, out_channels)
138
+
139
+ self.initialize_weights()
140
+ self.convert_to(self.dtype)
141
+
142
+ @property
143
+ def device(self) -> torch.device:
144
+ """
145
+ Return the device of the model.
146
+ """
147
+ return next(self.parameters()).device
148
+
149
+ def convert_to(self, dtype: torch.dtype) -> None:
150
+ """
151
+ Convert the torso of the model to the specified dtype.
152
+ """
153
+ self.dtype = dtype
154
+ self.blocks.apply(partial(convert_module_to, dtype=dtype))
155
+
156
+ def initialize_weights(self) -> None:
157
+ if self.initialization == 'vanilla':
158
+ # Initialize transformer layers:
159
+ def _basic_init(module):
160
+ if isinstance(module, nn.Linear):
161
+ torch.nn.init.xavier_uniform_(module.weight)
162
+ if module.bias is not None:
163
+ nn.init.constant_(module.bias, 0)
164
+ self.apply(_basic_init)
165
+
166
+ # Initialize timestep embedding MLP:
167
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
168
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
169
+
170
+ # Zero-out adaLN modulation layers in DiT blocks:
171
+ if self.share_mod:
172
+ nn.init.constant_(self.adaLN_modulation[-1].weight, 0)
173
+ nn.init.constant_(self.adaLN_modulation[-1].bias, 0)
174
+ else:
175
+ for block in self.blocks:
176
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
177
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
178
+
179
+ # Zero-out output layers:
180
+ nn.init.constant_(self.out_layer.weight, 0)
181
+ nn.init.constant_(self.out_layer.bias, 0)
182
+
183
+ elif self.initialization == 'scaled':
184
+ # Initialize transformer layers:
185
+ def _basic_init(module):
186
+ if isinstance(module, nn.Linear):
187
+ torch.nn.init.normal_(module.weight, std=np.sqrt(2.0 / (5.0 * self.model_channels)))
188
+ if module.bias is not None:
189
+ nn.init.constant_(module.bias, 0)
190
+ self.apply(_basic_init)
191
+
192
+ # Scaled init for to_out and ffn2
193
+ def _scaled_init(module):
194
+ if isinstance(module, nn.Linear):
195
+ torch.nn.init.normal_(module.weight, std=1.0 / np.sqrt(5 * self.num_blocks * self.model_channels))
196
+ if module.bias is not None:
197
+ nn.init.constant_(module.bias, 0)
198
+ for block in self.blocks:
199
+ block.self_attn.to_out.apply(_scaled_init)
200
+ block.cross_attn.to_out.apply(_scaled_init)
201
+ block.mlp.mlp[2].apply(_scaled_init)
202
+
203
+ # Initialize input layer to make the initial representation have variance 1
204
+ nn.init.normal_(self.input_layer.weight, std=1.0 / np.sqrt(self.in_channels))
205
+ nn.init.zeros_(self.input_layer.bias)
206
+
207
+ # Initialize timestep embedding MLP:
208
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
209
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
210
+
211
+ # Zero-out adaLN modulation layers in DiT blocks:
212
+ if self.share_mod:
213
+ nn.init.constant_(self.adaLN_modulation[-1].weight, 0)
214
+ nn.init.constant_(self.adaLN_modulation[-1].bias, 0)
215
+ else:
216
+ for block in self.blocks:
217
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
218
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
219
+
220
+ # Zero-out output layers:
221
+ nn.init.constant_(self.out_layer.weight, 0)
222
+ nn.init.constant_(self.out_layer.bias, 0)
223
+
224
+ def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor:
225
+ assert [*x.shape] == [x.shape[0], self.in_channels, *[self.resolution] * 3], \
226
+ f"Input shape mismatch, got {x.shape}, expected {[x.shape[0], self.in_channels, *[self.resolution] * 3]}"
227
+
228
+ h = x.view(*x.shape[:2], -1).permute(0, 2, 1).contiguous()
229
+
230
+ h = self.input_layer(h)
231
+ if self.pe_mode == "ape":
232
+ h = h + self.pos_emb[None]
233
+ t_emb = self.t_embedder(t)
234
+ if self.share_mod:
235
+ t_emb = self.adaLN_modulation(t_emb)
236
+ t_emb = manual_cast(t_emb, self.dtype)
237
+ h = manual_cast(h, self.dtype)
238
+ cond = manual_cast(cond, self.dtype)
239
+ for block in self.blocks:
240
+ h = block(h, t_emb, cond, self.rope_phases)
241
+ h = manual_cast(h, x.dtype)
242
+ h = F.layer_norm(h, h.shape[-1:])
243
+ h = self.out_layer(h)
244
+
245
+ h = h.permute(0, 2, 1).view(h.shape[0], h.shape[2], *[self.resolution] * 3).contiguous()
246
+
247
+ return h
trellis2/models/sparse_structure_vae.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from ..modules.norm import GroupNorm32, ChannelLayerNorm32
6
+ from ..modules.spatial import pixel_shuffle_3d
7
+ from ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
8
+
9
+
10
+ def norm_layer(norm_type: str, *args, **kwargs) -> nn.Module:
11
+ """
12
+ Return a normalization layer.
13
+ """
14
+ if norm_type == "group":
15
+ return GroupNorm32(32, *args, **kwargs)
16
+ elif norm_type == "layer":
17
+ return ChannelLayerNorm32(*args, **kwargs)
18
+ else:
19
+ raise ValueError(f"Invalid norm type {norm_type}")
20
+
21
+
22
+ class ResBlock3d(nn.Module):
23
+ def __init__(
24
+ self,
25
+ channels: int,
26
+ out_channels: Optional[int] = None,
27
+ norm_type: Literal["group", "layer"] = "layer",
28
+ ):
29
+ super().__init__()
30
+ self.channels = channels
31
+ self.out_channels = out_channels or channels
32
+
33
+ self.norm1 = norm_layer(norm_type, channels)
34
+ self.norm2 = norm_layer(norm_type, self.out_channels)
35
+ self.conv1 = nn.Conv3d(channels, self.out_channels, 3, padding=1)
36
+ self.conv2 = zero_module(nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1))
37
+ self.skip_connection = nn.Conv3d(channels, self.out_channels, 1) if channels != self.out_channels else nn.Identity()
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ h = self.norm1(x)
41
+ h = F.silu(h)
42
+ h = self.conv1(h)
43
+ h = self.norm2(h)
44
+ h = F.silu(h)
45
+ h = self.conv2(h)
46
+ h = h + self.skip_connection(x)
47
+ return h
48
+
49
+
50
+ class DownsampleBlock3d(nn.Module):
51
+ def __init__(
52
+ self,
53
+ in_channels: int,
54
+ out_channels: int,
55
+ mode: Literal["conv", "avgpool"] = "conv",
56
+ ):
57
+ assert mode in ["conv", "avgpool"], f"Invalid mode {mode}"
58
+
59
+ super().__init__()
60
+ self.in_channels = in_channels
61
+ self.out_channels = out_channels
62
+
63
+ if mode == "conv":
64
+ self.conv = nn.Conv3d(in_channels, out_channels, 2, stride=2)
65
+ elif mode == "avgpool":
66
+ assert in_channels == out_channels, "Pooling mode requires in_channels to be equal to out_channels"
67
+
68
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
69
+ if hasattr(self, "conv"):
70
+ return self.conv(x)
71
+ else:
72
+ return F.avg_pool3d(x, 2)
73
+
74
+
75
+ class UpsampleBlock3d(nn.Module):
76
+ def __init__(
77
+ self,
78
+ in_channels: int,
79
+ out_channels: int,
80
+ mode: Literal["conv", "nearest"] = "conv",
81
+ ):
82
+ assert mode in ["conv", "nearest"], f"Invalid mode {mode}"
83
+
84
+ super().__init__()
85
+ self.in_channels = in_channels
86
+ self.out_channels = out_channels
87
+
88
+ if mode == "conv":
89
+ self.conv = nn.Conv3d(in_channels, out_channels*8, 3, padding=1)
90
+ elif mode == "nearest":
91
+ assert in_channels == out_channels, "Nearest mode requires in_channels to be equal to out_channels"
92
+
93
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
94
+ if hasattr(self, "conv"):
95
+ x = self.conv(x)
96
+ return pixel_shuffle_3d(x, 2)
97
+ else:
98
+ return F.interpolate(x, scale_factor=2, mode="nearest")
99
+
100
+
101
+ class SparseStructureEncoder(nn.Module):
102
+ """
103
+ Encoder for Sparse Structure (\mathcal{E}_S in the paper Sec. 3.3).
104
+
105
+ Args:
106
+ in_channels (int): Channels of the input.
107
+ latent_channels (int): Channels of the latent representation.
108
+ num_res_blocks (int): Number of residual blocks at each resolution.
109
+ channels (List[int]): Channels of the encoder blocks.
110
+ num_res_blocks_middle (int): Number of residual blocks in the middle.
111
+ norm_type (Literal["group", "layer"]): Type of normalization layer.
112
+ use_fp16 (bool): Whether to use FP16.
113
+ """
114
+ def __init__(
115
+ self,
116
+ in_channels: int,
117
+ latent_channels: int,
118
+ num_res_blocks: int,
119
+ channels: List[int],
120
+ num_res_blocks_middle: int = 2,
121
+ norm_type: Literal["group", "layer"] = "layer",
122
+ use_fp16: bool = False,
123
+ ):
124
+ super().__init__()
125
+ self.in_channels = in_channels
126
+ self.latent_channels = latent_channels
127
+ self.num_res_blocks = num_res_blocks
128
+ self.channels = channels
129
+ self.num_res_blocks_middle = num_res_blocks_middle
130
+ self.norm_type = norm_type
131
+ self.use_fp16 = use_fp16
132
+ self.dtype = torch.float16 if use_fp16 else torch.float32
133
+
134
+ self.input_layer = nn.Conv3d(in_channels, channels[0], 3, padding=1)
135
+
136
+ self.blocks = nn.ModuleList([])
137
+ for i, ch in enumerate(channels):
138
+ self.blocks.extend([
139
+ ResBlock3d(ch, ch)
140
+ for _ in range(num_res_blocks)
141
+ ])
142
+ if i < len(channels) - 1:
143
+ self.blocks.append(
144
+ DownsampleBlock3d(ch, channels[i+1])
145
+ )
146
+
147
+ self.middle_block = nn.Sequential(*[
148
+ ResBlock3d(channels[-1], channels[-1])
149
+ for _ in range(num_res_blocks_middle)
150
+ ])
151
+
152
+ self.out_layer = nn.Sequential(
153
+ norm_layer(norm_type, channels[-1]),
154
+ nn.SiLU(),
155
+ nn.Conv3d(channels[-1], latent_channels*2, 3, padding=1)
156
+ )
157
+
158
+ if use_fp16:
159
+ self.convert_to_fp16()
160
+
161
+ @property
162
+ def device(self) -> torch.device:
163
+ """
164
+ Return the device of the model.
165
+ """
166
+ return next(self.parameters()).device
167
+
168
+ def convert_to_fp16(self) -> None:
169
+ """
170
+ Convert the torso of the model to float16.
171
+ """
172
+ self.use_fp16 = True
173
+ self.dtype = torch.float16
174
+ self.blocks.apply(convert_module_to_f16)
175
+ self.middle_block.apply(convert_module_to_f16)
176
+
177
+ def convert_to_fp32(self) -> None:
178
+ """
179
+ Convert the torso of the model to float32.
180
+ """
181
+ self.use_fp16 = False
182
+ self.dtype = torch.float32
183
+ self.blocks.apply(convert_module_to_f32)
184
+ self.middle_block.apply(convert_module_to_f32)
185
+
186
+ def forward(self, x: torch.Tensor, sample_posterior: bool = False, return_raw: bool = False) -> torch.Tensor:
187
+ h = self.input_layer(x)
188
+ h = h.type(self.dtype)
189
+
190
+ for block in self.blocks:
191
+ h = block(h)
192
+ h = self.middle_block(h)
193
+
194
+ h = h.type(x.dtype)
195
+ h = self.out_layer(h)
196
+
197
+ mean, logvar = h.chunk(2, dim=1)
198
+
199
+ if sample_posterior:
200
+ std = torch.exp(0.5 * logvar)
201
+ z = mean + std * torch.randn_like(std)
202
+ else:
203
+ z = mean
204
+
205
+ if return_raw:
206
+ return z, mean, logvar
207
+ return z
208
+
209
+
210
+ class SparseStructureDecoder(nn.Module):
211
+ """
212
+ Decoder for Sparse Structure (\mathcal{D}_S in the paper Sec. 3.3).
213
+
214
+ Args:
215
+ out_channels (int): Channels of the output.
216
+ latent_channels (int): Channels of the latent representation.
217
+ num_res_blocks (int): Number of residual blocks at each resolution.
218
+ channels (List[int]): Channels of the decoder blocks.
219
+ num_res_blocks_middle (int): Number of residual blocks in the middle.
220
+ norm_type (Literal["group", "layer"]): Type of normalization layer.
221
+ use_fp16 (bool): Whether to use FP16.
222
+ """
223
+ def __init__(
224
+ self,
225
+ out_channels: int,
226
+ latent_channels: int,
227
+ num_res_blocks: int,
228
+ channels: List[int],
229
+ num_res_blocks_middle: int = 2,
230
+ norm_type: Literal["group", "layer"] = "layer",
231
+ use_fp16: bool = False,
232
+ ):
233
+ super().__init__()
234
+ self.out_channels = out_channels
235
+ self.latent_channels = latent_channels
236
+ self.num_res_blocks = num_res_blocks
237
+ self.channels = channels
238
+ self.num_res_blocks_middle = num_res_blocks_middle
239
+ self.norm_type = norm_type
240
+ self.use_fp16 = use_fp16
241
+ self.dtype = torch.float16 if use_fp16 else torch.float32
242
+
243
+ self.input_layer = nn.Conv3d(latent_channels, channels[0], 3, padding=1)
244
+
245
+ self.middle_block = nn.Sequential(*[
246
+ ResBlock3d(channels[0], channels[0])
247
+ for _ in range(num_res_blocks_middle)
248
+ ])
249
+
250
+ self.blocks = nn.ModuleList([])
251
+ for i, ch in enumerate(channels):
252
+ self.blocks.extend([
253
+ ResBlock3d(ch, ch)
254
+ for _ in range(num_res_blocks)
255
+ ])
256
+ if i < len(channels) - 1:
257
+ self.blocks.append(
258
+ UpsampleBlock3d(ch, channels[i+1])
259
+ )
260
+
261
+ self.out_layer = nn.Sequential(
262
+ norm_layer(norm_type, channels[-1]),
263
+ nn.SiLU(),
264
+ nn.Conv3d(channels[-1], out_channels, 3, padding=1)
265
+ )
266
+
267
+ if use_fp16:
268
+ self.convert_to_fp16()
269
+
270
+ @property
271
+ def device(self) -> torch.device:
272
+ """
273
+ Return the device of the model.
274
+ """
275
+ return next(self.parameters()).device
276
+
277
+ def convert_to_fp16(self) -> None:
278
+ """
279
+ Convert the torso of the model to float16.
280
+ """
281
+ self.use_fp16 = True
282
+ self.dtype = torch.float16
283
+ self.blocks.apply(convert_module_to_f16)
284
+ self.middle_block.apply(convert_module_to_f16)
285
+
286
+ def convert_to_fp32(self) -> None:
287
+ """
288
+ Convert the torso of the model to float32.
289
+ """
290
+ self.use_fp16 = False
291
+ self.dtype = torch.float32
292
+ self.blocks.apply(convert_module_to_f32)
293
+ self.middle_block.apply(convert_module_to_f32)
294
+
295
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
296
+ h = self.input_layer(x)
297
+
298
+ h = h.type(self.dtype)
299
+
300
+ h = self.middle_block(h)
301
+ for block in self.blocks:
302
+ h = block(h)
303
+
304
+ h = h.type(x.dtype)
305
+ h = self.out_layer(h)
306
+ return h
trellis2/models/structured_latent_flow.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ from functools import partial
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import numpy as np
7
+ from ..modules.utils import convert_module_to, manual_cast, str_to_dtype
8
+ from ..modules.transformer import AbsolutePositionEmbedder
9
+ from ..modules import sparse as sp
10
+ from ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlock
11
+ from .sparse_structure_flow import TimestepEmbedder
12
+ from .sparse_elastic_mixin import SparseTransformerElasticMixin
13
+
14
+
15
+ class SLatFlowModel(nn.Module):
16
+ def __init__(
17
+ self,
18
+ resolution: int,
19
+ in_channels: int,
20
+ model_channels: int,
21
+ cond_channels: int,
22
+ out_channels: int,
23
+ num_blocks: int,
24
+ num_heads: Optional[int] = None,
25
+ num_head_channels: Optional[int] = 64,
26
+ mlp_ratio: float = 4,
27
+ pe_mode: Literal["ape", "rope"] = "ape",
28
+ rope_freq: Tuple[float, float] = (1.0, 10000.0),
29
+ dtype: str = 'float32',
30
+ use_checkpoint: bool = False,
31
+ share_mod: bool = False,
32
+ initialization: str = 'vanilla',
33
+ qk_rms_norm: bool = False,
34
+ qk_rms_norm_cross: bool = False,
35
+ ):
36
+ super().__init__()
37
+ self.resolution = resolution
38
+ self.in_channels = in_channels
39
+ self.model_channels = model_channels
40
+ self.cond_channels = cond_channels
41
+ self.out_channels = out_channels
42
+ self.num_blocks = num_blocks
43
+ self.num_heads = num_heads or model_channels // num_head_channels
44
+ self.mlp_ratio = mlp_ratio
45
+ self.pe_mode = pe_mode
46
+ self.use_checkpoint = use_checkpoint
47
+ self.share_mod = share_mod
48
+ self.initialization = initialization
49
+ self.qk_rms_norm = qk_rms_norm
50
+ self.qk_rms_norm_cross = qk_rms_norm_cross
51
+ self.dtype = str_to_dtype(dtype)
52
+
53
+ self.t_embedder = TimestepEmbedder(model_channels)
54
+ if share_mod:
55
+ self.adaLN_modulation = nn.Sequential(
56
+ nn.SiLU(),
57
+ nn.Linear(model_channels, 6 * model_channels, bias=True)
58
+ )
59
+
60
+ if pe_mode == "ape":
61
+ self.pos_embedder = AbsolutePositionEmbedder(model_channels)
62
+
63
+ self.input_layer = sp.SparseLinear(in_channels, model_channels)
64
+
65
+ self.blocks = nn.ModuleList([
66
+ ModulatedSparseTransformerCrossBlock(
67
+ model_channels,
68
+ cond_channels,
69
+ num_heads=self.num_heads,
70
+ mlp_ratio=self.mlp_ratio,
71
+ attn_mode='full',
72
+ use_checkpoint=self.use_checkpoint,
73
+ use_rope=(pe_mode == "rope"),
74
+ rope_freq=rope_freq,
75
+ share_mod=self.share_mod,
76
+ qk_rms_norm=self.qk_rms_norm,
77
+ qk_rms_norm_cross=self.qk_rms_norm_cross,
78
+ )
79
+ for _ in range(num_blocks)
80
+ ])
81
+
82
+ self.out_layer = sp.SparseLinear(model_channels, out_channels)
83
+
84
+ self.initialize_weights()
85
+ self.convert_to(self.dtype)
86
+
87
+ @property
88
+ def device(self) -> torch.device:
89
+ """
90
+ Return the device of the model.
91
+ """
92
+ return next(self.parameters()).device
93
+
94
+ def convert_to(self, dtype: torch.dtype) -> None:
95
+ """
96
+ Convert the torso of the model to the specified dtype.
97
+ """
98
+ self.dtype = dtype
99
+ self.blocks.apply(partial(convert_module_to, dtype=dtype))
100
+
101
+ def initialize_weights(self) -> None:
102
+ if self.initialization == 'vanilla':
103
+ # Initialize transformer layers:
104
+ def _basic_init(module):
105
+ if isinstance(module, nn.Linear):
106
+ torch.nn.init.xavier_uniform_(module.weight)
107
+ if module.bias is not None:
108
+ nn.init.constant_(module.bias, 0)
109
+ self.apply(_basic_init)
110
+
111
+ # Initialize timestep embedding MLP:
112
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
113
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
114
+
115
+ # Zero-out adaLN modulation layers in DiT blocks:
116
+ if self.share_mod:
117
+ nn.init.constant_(self.adaLN_modulation[-1].weight, 0)
118
+ nn.init.constant_(self.adaLN_modulation[-1].bias, 0)
119
+ else:
120
+ for block in self.blocks:
121
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
122
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
123
+
124
+ # Zero-out output layers:
125
+ nn.init.constant_(self.out_layer.weight, 0)
126
+ nn.init.constant_(self.out_layer.bias, 0)
127
+
128
+ elif self.initialization == 'scaled':
129
+ # Initialize transformer layers:
130
+ def _basic_init(module):
131
+ if isinstance(module, nn.Linear):
132
+ torch.nn.init.normal_(module.weight, std=np.sqrt(2.0 / (5.0 * self.model_channels)))
133
+ if module.bias is not None:
134
+ nn.init.constant_(module.bias, 0)
135
+ self.apply(_basic_init)
136
+
137
+ # Scaled init for to_out and ffn2
138
+ def _scaled_init(module):
139
+ if isinstance(module, nn.Linear):
140
+ torch.nn.init.normal_(module.weight, std=1.0 / np.sqrt(5 * self.num_blocks * self.model_channels))
141
+ if module.bias is not None:
142
+ nn.init.constant_(module.bias, 0)
143
+ for block in self.blocks:
144
+ block.self_attn.to_out.apply(_scaled_init)
145
+ block.cross_attn.to_out.apply(_scaled_init)
146
+ block.mlp.mlp[2].apply(_scaled_init)
147
+
148
+ # Initialize input layer to make the initial representation have variance 1
149
+ nn.init.normal_(self.input_layer.weight, std=1.0 / np.sqrt(self.in_channels))
150
+ nn.init.zeros_(self.input_layer.bias)
151
+
152
+ # Initialize timestep embedding MLP:
153
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
154
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
155
+
156
+ # Zero-out adaLN modulation layers in DiT blocks:
157
+ if self.share_mod:
158
+ nn.init.constant_(self.adaLN_modulation[-1].weight, 0)
159
+ nn.init.constant_(self.adaLN_modulation[-1].bias, 0)
160
+ else:
161
+ for block in self.blocks:
162
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
163
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
164
+
165
+ # Zero-out output layers:
166
+ nn.init.constant_(self.out_layer.weight, 0)
167
+ nn.init.constant_(self.out_layer.bias, 0)
168
+
169
+ def forward(
170
+ self,
171
+ x: sp.SparseTensor,
172
+ t: torch.Tensor,
173
+ cond: Union[torch.Tensor, List[torch.Tensor]],
174
+ concat_cond: Optional[sp.SparseTensor] = None,
175
+ **kwargs
176
+ ) -> sp.SparseTensor:
177
+ if concat_cond is not None:
178
+ x = sp.sparse_cat([x, concat_cond], dim=-1)
179
+ if isinstance(cond, list):
180
+ cond = sp.VarLenTensor.from_tensor_list(cond)
181
+
182
+ h = self.input_layer(x)
183
+ h = manual_cast(h, self.dtype)
184
+ t_emb = self.t_embedder(t)
185
+ if self.share_mod:
186
+ t_emb = self.adaLN_modulation(t_emb)
187
+ t_emb = manual_cast(t_emb, self.dtype)
188
+ cond = manual_cast(cond, self.dtype)
189
+
190
+ if self.pe_mode == "ape":
191
+ pe = self.pos_embedder(h.coords[:, 1:])
192
+ h = h + manual_cast(pe, self.dtype)
193
+ for block in self.blocks:
194
+ h = block(h, t_emb, cond)
195
+
196
+ h = manual_cast(h, x.dtype)
197
+ h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
198
+ h = self.out_layer(h)
199
+ return h
200
+
201
+
202
+ class ElasticSLatFlowModel(SparseTransformerElasticMixin, SLatFlowModel):
203
+ """
204
+ SLat Flow Model with elastic memory management.
205
+ Used for training with low VRAM.
206
+ """
207
+ pass
trellis2/modules/__pycache__/image_feature_extractor.cpython-311.pyc ADDED
Binary file (10.4 kB). View file
 
trellis2/modules/__pycache__/norm.cpython-311.pyc ADDED
Binary file (2.83 kB). View file
 
trellis2/modules/__pycache__/spatial.cpython-311.pyc ADDED
Binary file (4.65 kB). View file
 
trellis2/modules/__pycache__/utils.cpython-311.pyc ADDED
Binary file (3.92 kB). View file
 
trellis2/modules/attention/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .full_attn import *
2
+ from .modules import *
3
+ from .rope import *
trellis2/modules/attention/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (306 Bytes). View file
 
trellis2/modules/attention/__pycache__/config.cpython-311.pyc ADDED
Binary file (1.38 kB). View file
 
trellis2/modules/attention/__pycache__/full_attn.cpython-311.pyc ADDED
Binary file (8.5 kB). View file
 
trellis2/modules/attention/__pycache__/modules.cpython-311.pyc ADDED
Binary file (6.77 kB). View file
 
trellis2/modules/attention/__pycache__/rope.cpython-311.pyc ADDED
Binary file (4.35 kB). View file
 
trellis2/modules/attention/config.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import sys
3
+
4
+ # Default to 'sdpa' (PyTorch's built-in) on Windows since flash_attn isn't available
5
+ BACKEND = 'sdpa' if sys.platform == 'win32' else 'flash_attn'
6
+ DEBUG = False
7
+
8
+ def __from_env():
9
+ import os
10
+
11
+ global BACKEND
12
+ global DEBUG
13
+
14
+ env_attn_backend = os.environ.get('ATTN_BACKEND')
15
+ env_attn_debug = os.environ.get('ATTN_DEBUG')
16
+
17
+ if env_attn_backend is not None and env_attn_backend in ['xformers', 'flash_attn', 'flash_attn_3', 'sdpa', 'naive']:
18
+ BACKEND = env_attn_backend
19
+ if env_attn_debug is not None:
20
+ DEBUG = env_attn_debug == '1'
21
+
22
+ print(f"[ATTENTION] Using backend: {BACKEND}")
23
+
24
+
25
+ __from_env()
26
+
27
+
28
+ def set_backend(backend: Literal['xformers', 'flash_attn']):
29
+ global BACKEND
30
+ BACKEND = backend
31
+
32
+ def set_debug(debug: bool):
33
+ global DEBUG
34
+ DEBUG = debug
trellis2/modules/attention/full_attn.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import math
4
+ from . import config
5
+
6
+
7
+ __all__ = [
8
+ 'scaled_dot_product_attention',
9
+ ]
10
+
11
+
12
+ def _naive_sdpa(q, k, v):
13
+ """
14
+ Naive implementation of scaled dot product attention.
15
+ """
16
+ q = q.permute(0, 2, 1, 3) # [N, H, L, C]
17
+ k = k.permute(0, 2, 1, 3) # [N, H, L, C]
18
+ v = v.permute(0, 2, 1, 3) # [N, H, L, C]
19
+ scale_factor = 1 / math.sqrt(q.size(-1))
20
+ attn_weight = q @ k.transpose(-2, -1) * scale_factor
21
+ attn_weight = torch.softmax(attn_weight, dim=-1)
22
+ out = attn_weight @ v
23
+ out = out.permute(0, 2, 1, 3) # [N, L, H, C]
24
+ return out
25
+
26
+
27
+ @overload
28
+ def scaled_dot_product_attention(qkv: torch.Tensor) -> torch.Tensor:
29
+ """
30
+ Apply scaled dot product attention.
31
+
32
+ Args:
33
+ qkv (torch.Tensor): A [N, L, 3, H, C] tensor containing Qs, Ks, and Vs.
34
+ """
35
+ ...
36
+
37
+ @overload
38
+ def scaled_dot_product_attention(q: torch.Tensor, kv: torch.Tensor) -> torch.Tensor:
39
+ """
40
+ Apply scaled dot product attention.
41
+
42
+ Args:
43
+ q (torch.Tensor): A [N, L, H, C] tensor containing Qs.
44
+ kv (torch.Tensor): A [N, L, 2, H, C] tensor containing Ks and Vs.
45
+ """
46
+ ...
47
+
48
+ @overload
49
+ def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
50
+ """
51
+ Apply scaled dot product attention.
52
+
53
+ Args:
54
+ q (torch.Tensor): A [N, L, H, Ci] tensor containing Qs.
55
+ k (torch.Tensor): A [N, L, H, Ci] tensor containing Ks.
56
+ v (torch.Tensor): A [N, L, H, Co] tensor containing Vs.
57
+
58
+ Note:
59
+ k and v are assumed to have the same coordinate map.
60
+ """
61
+ ...
62
+
63
+ def scaled_dot_product_attention(*args, **kwargs):
64
+ arg_names_dict = {
65
+ 1: ['qkv'],
66
+ 2: ['q', 'kv'],
67
+ 3: ['q', 'k', 'v']
68
+ }
69
+ num_all_args = len(args) + len(kwargs)
70
+ assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3"
71
+ for key in arg_names_dict[num_all_args][len(args):]:
72
+ assert key in kwargs, f"Missing argument {key}"
73
+
74
+ if num_all_args == 1:
75
+ qkv = args[0] if len(args) > 0 else kwargs['qkv']
76
+ assert len(qkv.shape) == 5 and qkv.shape[2] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, L, 3, H, C]"
77
+ device = qkv.device
78
+
79
+ elif num_all_args == 2:
80
+ q = args[0] if len(args) > 0 else kwargs['q']
81
+ kv = args[1] if len(args) > 1 else kwargs['kv']
82
+ assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}"
83
+ assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]"
84
+ assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]"
85
+ device = q.device
86
+
87
+ elif num_all_args == 3:
88
+ q = args[0] if len(args) > 0 else kwargs['q']
89
+ k = args[1] if len(args) > 1 else kwargs['k']
90
+ v = args[2] if len(args) > 2 else kwargs['v']
91
+ assert q.shape[0] == k.shape[0] == v.shape[0], f"Batch size mismatch, got {q.shape[0]}, {k.shape[0]}, and {v.shape[0]}"
92
+ assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]"
93
+ assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]"
94
+ assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]"
95
+ device = q.device
96
+
97
+ if config.BACKEND == 'xformers':
98
+ if 'xops' not in globals():
99
+ import xformers.ops as xops
100
+ if num_all_args == 1:
101
+ q, k, v = qkv.unbind(dim=2)
102
+ elif num_all_args == 2:
103
+ k, v = kv.unbind(dim=2)
104
+ out = xops.memory_efficient_attention(q, k, v)
105
+ elif config.BACKEND == 'flash_attn':
106
+ if 'flash_attn' not in globals():
107
+ import flash_attn
108
+ if num_all_args == 1:
109
+ out = flash_attn.flash_attn_qkvpacked_func(qkv)
110
+ elif num_all_args == 2:
111
+ out = flash_attn.flash_attn_kvpacked_func(q, kv)
112
+ elif num_all_args == 3:
113
+ out = flash_attn.flash_attn_func(q, k, v)
114
+ elif config.BACKEND == 'flash_attn_3':
115
+ if 'flash_attn_3' not in globals():
116
+ import flash_attn_interface as flash_attn_3
117
+ if num_all_args == 1:
118
+ out = flash_attn_3.flash_attn_qkvpacked_func(qkv)
119
+ elif num_all_args == 2:
120
+ k, v = kv.unbind(dim=2)
121
+ out = flash_attn_3.flash_attn_func(q, k, v)
122
+ elif num_all_args == 3:
123
+ out = flash_attn_3.flash_attn_func(q, k, v)
124
+ elif config.BACKEND == 'sdpa':
125
+ if 'sdpa' not in globals():
126
+ from torch.nn.functional import scaled_dot_product_attention as sdpa
127
+ if num_all_args == 1:
128
+ q, k, v = qkv.unbind(dim=2)
129
+ elif num_all_args == 2:
130
+ k, v = kv.unbind(dim=2)
131
+ q = q.permute(0, 2, 1, 3) # [N, H, L, C]
132
+ k = k.permute(0, 2, 1, 3) # [N, H, L, C]
133
+ v = v.permute(0, 2, 1, 3) # [N, H, L, C]
134
+ out = sdpa(q, k, v) # [N, H, L, C]
135
+ out = out.permute(0, 2, 1, 3) # [N, L, H, C]
136
+ elif config.BACKEND == 'naive':
137
+ if num_all_args == 1:
138
+ q, k, v = qkv.unbind(dim=2)
139
+ elif num_all_args == 2:
140
+ k, v = kv.unbind(dim=2)
141
+ out = _naive_sdpa(q, k, v)
142
+ else:
143
+ raise ValueError(f"Unknown attention module: {config.BACKEND}")
144
+
145
+ return out
trellis2/modules/attention/modules.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from .full_attn import scaled_dot_product_attention
6
+ from .rope import RotaryPositionEmbedder
7
+
8
+
9
+ class MultiHeadRMSNorm(nn.Module):
10
+ def __init__(self, dim: int, heads: int):
11
+ super().__init__()
12
+ self.scale = dim ** 0.5
13
+ self.gamma = nn.Parameter(torch.ones(heads, dim))
14
+
15
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
16
+ return (F.normalize(x.float(), dim = -1) * self.gamma * self.scale).to(x.dtype)
17
+
18
+
19
+ class MultiHeadAttention(nn.Module):
20
+ def __init__(
21
+ self,
22
+ channels: int,
23
+ num_heads: int,
24
+ ctx_channels: Optional[int]=None,
25
+ type: Literal["self", "cross"] = "self",
26
+ attn_mode: Literal["full", "windowed"] = "full",
27
+ window_size: Optional[int] = None,
28
+ shift_window: Optional[Tuple[int, int, int]] = None,
29
+ qkv_bias: bool = True,
30
+ use_rope: bool = False,
31
+ rope_freq: Tuple[float, float] = (1.0, 10000.0),
32
+ qk_rms_norm: bool = False,
33
+ ):
34
+ super().__init__()
35
+ assert channels % num_heads == 0
36
+ assert type in ["self", "cross"], f"Invalid attention type: {type}"
37
+ assert attn_mode in ["full", "windowed"], f"Invalid attention mode: {attn_mode}"
38
+ assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention"
39
+
40
+ if attn_mode == "windowed":
41
+ raise NotImplementedError("Windowed attention is not yet implemented")
42
+
43
+ self.channels = channels
44
+ self.head_dim = channels // num_heads
45
+ self.ctx_channels = ctx_channels if ctx_channels is not None else channels
46
+ self.num_heads = num_heads
47
+ self._type = type
48
+ self.attn_mode = attn_mode
49
+ self.window_size = window_size
50
+ self.shift_window = shift_window
51
+ self.use_rope = use_rope
52
+ self.qk_rms_norm = qk_rms_norm
53
+
54
+ if self._type == "self":
55
+ self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias)
56
+ else:
57
+ self.to_q = nn.Linear(channels, channels, bias=qkv_bias)
58
+ self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias)
59
+
60
+ if self.qk_rms_norm:
61
+ self.q_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads)
62
+ self.k_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads)
63
+
64
+ self.to_out = nn.Linear(channels, channels)
65
+
66
+ def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None, phases: Optional[torch.Tensor] = None) -> torch.Tensor:
67
+ B, L, C = x.shape
68
+ if self._type == "self":
69
+ qkv = self.to_qkv(x)
70
+ qkv = qkv.reshape(B, L, 3, self.num_heads, -1)
71
+
72
+ if self.attn_mode == "full":
73
+ if self.qk_rms_norm or self.use_rope:
74
+ q, k, v = qkv.unbind(dim=2)
75
+ if self.qk_rms_norm:
76
+ q = self.q_rms_norm(q)
77
+ k = self.k_rms_norm(k)
78
+ if self.use_rope:
79
+ assert phases is not None, "Phases must be provided for RoPE"
80
+ q = RotaryPositionEmbedder.apply_rotary_embedding(q, phases)
81
+ k = RotaryPositionEmbedder.apply_rotary_embedding(k, phases)
82
+ h = scaled_dot_product_attention(q, k, v)
83
+ else:
84
+ h = scaled_dot_product_attention(qkv)
85
+ elif self.attn_mode == "windowed":
86
+ raise NotImplementedError("Windowed attention is not yet implemented")
87
+ else:
88
+ Lkv = context.shape[1]
89
+ q = self.to_q(x)
90
+ kv = self.to_kv(context)
91
+ q = q.reshape(B, L, self.num_heads, -1)
92
+ kv = kv.reshape(B, Lkv, 2, self.num_heads, -1)
93
+ if self.qk_rms_norm:
94
+ q = self.q_rms_norm(q)
95
+ k, v = kv.unbind(dim=2)
96
+ k = self.k_rms_norm(k)
97
+ h = scaled_dot_product_attention(q, k, v)
98
+ else:
99
+ h = scaled_dot_product_attention(q, kv)
100
+ h = h.reshape(B, L, -1)
101
+ h = self.to_out(h)
102
+ return h
trellis2/modules/attention/rope.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ class RotaryPositionEmbedder(nn.Module):
7
+ def __init__(
8
+ self,
9
+ head_dim: int,
10
+ dim: int = 3,
11
+ rope_freq: Tuple[float, float] = (1.0, 10000.0)
12
+ ):
13
+ super().__init__()
14
+ assert head_dim % 2 == 0, "Head dim must be divisible by 2"
15
+ self.head_dim = head_dim
16
+ self.dim = dim
17
+ self.rope_freq = rope_freq
18
+ self.freq_dim = head_dim // 2 // dim
19
+ self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim
20
+ self.freqs = rope_freq[0] / (rope_freq[1] ** (self.freqs))
21
+
22
+ def _get_phases(self, indices: torch.Tensor) -> torch.Tensor:
23
+ self.freqs = self.freqs.to(indices.device)
24
+ phases = torch.outer(indices, self.freqs)
25
+ phases = torch.polar(torch.ones_like(phases), phases)
26
+ return phases
27
+
28
+ @staticmethod
29
+ def apply_rotary_embedding(x: torch.Tensor, phases: torch.Tensor) -> torch.Tensor:
30
+ x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
31
+ x_rotated = x_complex * phases.unsqueeze(-2)
32
+ x_embed = torch.view_as_real(x_rotated).reshape(*x_rotated.shape[:-1], -1).to(x.dtype)
33
+ return x_embed
34
+
35
+ def forward(self, indices: torch.Tensor) -> torch.Tensor:
36
+ """
37
+ Args:
38
+ indices (torch.Tensor): [..., N, C] tensor of spatial positions
39
+ """
40
+ assert indices.shape[-1] == self.dim, f"Last dim of indices must be {self.dim}"
41
+ phases = self._get_phases(indices.reshape(-1)).reshape(*indices.shape[:-1], -1)
42
+ if phases.shape[-1] < self.head_dim // 2:
43
+ padn = self.head_dim // 2 - phases.shape[-1]
44
+ phases = torch.cat([phases, torch.polar(
45
+ torch.ones(*phases.shape[:-1], padn, device=phases.device),
46
+ torch.zeros(*phases.shape[:-1], padn, device=phases.device)
47
+ )], dim=-1)
48
+ return phases
trellis2/modules/image_feature_extractor.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from torchvision import transforms
5
+ from transformers import DINOv3ViTModel
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+
10
+ class DinoV2FeatureExtractor:
11
+ """
12
+ Feature extractor for DINOv2 models.
13
+ """
14
+ def __init__(self, model_name: str):
15
+ self.model_name = model_name
16
+ self.model = torch.hub.load('facebookresearch/dinov2', model_name, pretrained=True)
17
+ self.model.eval()
18
+ self.transform = transforms.Compose([
19
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
20
+ ])
21
+
22
+ def to(self, device):
23
+ self.model.to(device)
24
+
25
+ def cuda(self):
26
+ self.model.cuda()
27
+
28
+ def cpu(self):
29
+ self.model.cpu()
30
+
31
+ @torch.no_grad()
32
+ def __call__(self, image: Union[torch.Tensor, List[Image.Image]]) -> torch.Tensor:
33
+ """
34
+ Extract features from the image.
35
+
36
+ Args:
37
+ image: A batch of images as a tensor of shape (B, C, H, W) or a list of PIL images.
38
+
39
+ Returns:
40
+ A tensor of shape (B, N, D) where N is the number of patches and D is the feature dimension.
41
+ """
42
+ if isinstance(image, torch.Tensor):
43
+ assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)"
44
+ elif isinstance(image, list):
45
+ assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images"
46
+ image = [i.resize((518, 518), Image.LANCZOS) for i in image]
47
+ image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image]
48
+ image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image]
49
+ image = torch.stack(image).cuda()
50
+ else:
51
+ raise ValueError(f"Unsupported type of image: {type(image)}")
52
+
53
+ image = self.transform(image).cuda()
54
+ features = self.model(image, is_training=True)['x_prenorm']
55
+ patchtokens = F.layer_norm(features, features.shape[-1:])
56
+ return patchtokens
57
+
58
+
59
+ class DinoV3FeatureExtractor:
60
+ """
61
+ Feature extractor for DINOv3 models.
62
+ """
63
+ def __init__(self, model_name: str, image_size=512):
64
+ self.model_name = model_name
65
+ # Try loading with local_files_only first (for cached gated models)
66
+ try:
67
+ self.model = DINOv3ViTModel.from_pretrained(model_name, local_files_only=True)
68
+ except Exception:
69
+ # Fall back to remote loading
70
+ self.model = DINOv3ViTModel.from_pretrained(model_name)
71
+ self.model.eval()
72
+ self.image_size = image_size
73
+ self.transform = transforms.Compose([
74
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
75
+ ])
76
+
77
+ def to(self, device):
78
+ self.model.to(device)
79
+
80
+ def cuda(self):
81
+ self.model.cuda()
82
+
83
+ def cpu(self):
84
+ self.model.cpu()
85
+
86
+ def extract_features(self, image: torch.Tensor) -> torch.Tensor:
87
+ image = image.to(self.model.embeddings.patch_embeddings.weight.dtype)
88
+ hidden_states = self.model.embeddings(image, bool_masked_pos=None)
89
+ position_embeddings = self.model.rope_embeddings(image)
90
+
91
+ for i, layer_module in enumerate(self.model.layer):
92
+ hidden_states = layer_module(
93
+ hidden_states,
94
+ position_embeddings=position_embeddings,
95
+ )
96
+
97
+ return F.layer_norm(hidden_states, hidden_states.shape[-1:])
98
+
99
+ @torch.no_grad()
100
+ def __call__(self, image: Union[torch.Tensor, List[Image.Image]]) -> torch.Tensor:
101
+ """
102
+ Extract features from the image.
103
+
104
+ Args:
105
+ image: A batch of images as a tensor of shape (B, C, H, W) or a list of PIL images.
106
+
107
+ Returns:
108
+ A tensor of shape (B, N, D) where N is the number of patches and D is the feature dimension.
109
+ """
110
+ if isinstance(image, torch.Tensor):
111
+ assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)"
112
+ elif isinstance(image, list):
113
+ assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images"
114
+ image = [i.resize((self.image_size, self.image_size), Image.LANCZOS) for i in image]
115
+ image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image]
116
+ image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image]
117
+ image = torch.stack(image).cuda()
118
+ else:
119
+ raise ValueError(f"Unsupported type of image: {type(image)}")
120
+
121
+ image = self.transform(image).cuda()
122
+ features = self.extract_features(image)
123
+ return features
trellis2/modules/norm.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from .utils import manual_cast
4
+
5
+
6
+ class LayerNorm32(nn.LayerNorm):
7
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
8
+ x_dtype = x.dtype
9
+ x = manual_cast(x, torch.float32)
10
+ o = super().forward(x)
11
+ return manual_cast(o, x_dtype)
12
+
13
+
14
+ class GroupNorm32(nn.GroupNorm):
15
+ """
16
+ A GroupNorm layer that converts to float32 before the forward pass.
17
+ """
18
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
19
+ x_dtype = x.dtype
20
+ x = manual_cast(x, torch.float32)
21
+ o = super().forward(x)
22
+ return manual_cast(o, x_dtype)
23
+
24
+
25
+ class ChannelLayerNorm32(LayerNorm32):
26
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
27
+ DIM = x.dim()
28
+ x = x.permute(0, *range(2, DIM), 1).contiguous()
29
+ x = super().forward(x)
30
+ x = x.permute(0, DIM-1, *range(1, DIM-1)).contiguous()
31
+ return x
32
+
trellis2/modules/sparse/__init__.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import config
2
+ import importlib
3
+
4
+ __attributes = {
5
+ 'VarLenTensor': 'basic',
6
+ 'varlen_cat': 'basic',
7
+ 'varlen_unbind': 'basic',
8
+ 'SparseTensor': 'basic',
9
+ 'sparse_cat': 'basic',
10
+ 'sparse_unbind': 'basic',
11
+ 'SparseGroupNorm': 'norm',
12
+ 'SparseLayerNorm': 'norm',
13
+ 'SparseGroupNorm32': 'norm',
14
+ 'SparseLayerNorm32': 'norm',
15
+ 'SparseReLU': 'nonlinearity',
16
+ 'SparseSiLU': 'nonlinearity',
17
+ 'SparseGELU': 'nonlinearity',
18
+ 'SparseActivation': 'nonlinearity',
19
+ 'SparseLinear': 'linear',
20
+ 'sparse_scaled_dot_product_attention': 'attention',
21
+ 'SerializeMode': 'attention',
22
+ 'sparse_serialized_scaled_dot_product_self_attention': 'attention',
23
+ 'sparse_windowed_scaled_dot_product_self_attention': 'attention',
24
+ 'sparse_windowed_scaled_dot_product_cross_attention': 'attention',
25
+ 'SparseRotaryPositionEmbedder': 'attention',
26
+ 'SparseMultiHeadAttention': 'attention',
27
+ 'SparseConv3d': 'conv',
28
+ 'SparseInverseConv3d': 'conv',
29
+ 'SparseDownsample': 'spatial',
30
+ 'SparseUpsample': 'spatial',
31
+ 'SparseSubdivide': 'spatial',
32
+ 'SparseSpatial2Channel': 'spatial',
33
+ 'SparseChannel2Spatial': 'spatial',
34
+ 'sparse_nearest_interpolate': 'spatial',
35
+ 'sparse_trilinear_interpolate': 'spatial',
36
+ 'encode_seq': 'serialize',
37
+ 'decode_seq': 'serialize',
38
+ }
39
+
40
+ __submodules = ['transformer', 'conv']
41
+
42
+ __all__ = list(__attributes.keys()) + __submodules
43
+
44
+ def __getattr__(name):
45
+ if name not in globals():
46
+ if name in __attributes:
47
+ module_name = __attributes[name]
48
+ module = importlib.import_module(f".{module_name}", __name__)
49
+ globals()[name] = getattr(module, name)
50
+ elif name in __submodules:
51
+ module = importlib.import_module(f".{name}", __name__)
52
+ globals()[name] = module
53
+ else:
54
+ raise AttributeError(f"module {__name__} has no attribute {name}")
55
+ return globals()[name]
56
+
57
+
58
+ # For Pylance
59
+ if __name__ == '__main__':
60
+ from .basic import *
61
+ from .norm import *
62
+ from .nonlinearity import *
63
+ from .linear import *
64
+ from .attention import *
65
+ from .conv import *
66
+ from .spatial import *
67
+ from .serialize import *
68
+ import transformer
69
+ import conv
trellis2/modules/sparse/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.99 kB). View file
 
trellis2/modules/sparse/__pycache__/basic.cpython-311.pyc ADDED
Binary file (54.7 kB). View file
 
trellis2/modules/sparse/__pycache__/config.cpython-311.pyc ADDED
Binary file (1.93 kB). View file
 
trellis2/modules/sparse/__pycache__/linear.cpython-311.pyc ADDED
Binary file (1.39 kB). View file
 
trellis2/modules/sparse/__pycache__/nonlinearity.cpython-311.pyc ADDED
Binary file (2.87 kB). View file
 
trellis2/modules/sparse/attention/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .full_attn import *
2
+ from .windowed_attn import *
3
+ from .modules import *
trellis2/modules/sparse/attention/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (322 Bytes). View file
 
trellis2/modules/sparse/attention/__pycache__/full_attn.cpython-311.pyc ADDED
Binary file (17.9 kB). View file
 
trellis2/modules/sparse/attention/__pycache__/modules.cpython-311.pyc ADDED
Binary file (10.4 kB). View file