1
This commit is contained in:
131
trellis/models/structured_latent_vae/decoder_gs.py
Normal file
131
trellis/models/structured_latent_vae/decoder_gs.py
Normal file
@@ -0,0 +1,131 @@
|
||||
from typing import *
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from ...modules import sparse as sp
|
||||
from ...utils.random_utils import hammersley_sequence
|
||||
from .base import SparseTransformerBase
|
||||
from ...representations import Gaussian
|
||||
from ..sparse_elastic_mixin import SparseTransformerElasticMixin
|
||||
|
||||
|
||||
class SLatGaussianDecoder(SparseTransformerBase):
|
||||
def __init__(
|
||||
self,
|
||||
resolution: int,
|
||||
model_channels: int,
|
||||
latent_channels: int,
|
||||
num_blocks: int,
|
||||
num_heads: Optional[int] = None,
|
||||
num_head_channels: Optional[int] = 64,
|
||||
mlp_ratio: float = 4,
|
||||
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
||||
window_size: int = 8,
|
||||
pe_mode: Literal["ape", "rope"] = "ape",
|
||||
use_fp16: bool = False,
|
||||
use_checkpoint: bool = False,
|
||||
qk_rms_norm: bool = False,
|
||||
representation_config: dict = None,
|
||||
):
|
||||
super().__init__(
|
||||
in_channels=latent_channels,
|
||||
model_channels=model_channels,
|
||||
num_blocks=num_blocks,
|
||||
num_heads=num_heads,
|
||||
num_head_channels=num_head_channels,
|
||||
mlp_ratio=mlp_ratio,
|
||||
attn_mode=attn_mode,
|
||||
window_size=window_size,
|
||||
pe_mode=pe_mode,
|
||||
use_fp16=use_fp16,
|
||||
use_checkpoint=use_checkpoint,
|
||||
qk_rms_norm=qk_rms_norm,
|
||||
)
|
||||
self.resolution = resolution
|
||||
self.rep_config = representation_config
|
||||
self._calc_layout()
|
||||
self.out_layer = sp.SparseLinear(model_channels, self.out_channels)
|
||||
self._build_perturbation()
|
||||
|
||||
self.initialize_weights()
|
||||
if use_fp16:
|
||||
self.convert_to_fp16()
|
||||
|
||||
def initialize_weights(self) -> None:
|
||||
super().initialize_weights()
|
||||
# Zero-out output layers:
|
||||
nn.init.constant_(self.out_layer.weight, 0)
|
||||
nn.init.constant_(self.out_layer.bias, 0)
|
||||
|
||||
def _build_perturbation(self) -> None:
|
||||
perturbation = [hammersley_sequence(3, i, self.rep_config['num_gaussians']) for i in range(self.rep_config['num_gaussians'])]
|
||||
perturbation = torch.tensor(perturbation).float() * 2 - 1
|
||||
perturbation = perturbation / self.rep_config['voxel_size']
|
||||
perturbation = torch.atanh(perturbation).to(self.device)
|
||||
self.register_buffer('offset_perturbation', perturbation)
|
||||
|
||||
def _calc_layout(self) -> None:
|
||||
self.layout = {
|
||||
'_xyz' : {'shape': (self.rep_config['num_gaussians'], 3), 'size': self.rep_config['num_gaussians'] * 3},
|
||||
'_features_dc' : {'shape': (self.rep_config['num_gaussians'], 1, 3), 'size': self.rep_config['num_gaussians'] * 3},
|
||||
'_scaling' : {'shape': (self.rep_config['num_gaussians'], 3), 'size': self.rep_config['num_gaussians'] * 3},
|
||||
'_rotation' : {'shape': (self.rep_config['num_gaussians'], 4), 'size': self.rep_config['num_gaussians'] * 4},
|
||||
'_opacity' : {'shape': (self.rep_config['num_gaussians'], 1), 'size': self.rep_config['num_gaussians']},
|
||||
}
|
||||
start = 0
|
||||
for k, v in self.layout.items():
|
||||
v['range'] = (start, start + v['size'])
|
||||
start += v['size']
|
||||
self.out_channels = start
|
||||
|
||||
def to_representation(self, x: sp.SparseTensor) -> List[Gaussian]:
|
||||
"""
|
||||
Convert a batch of network outputs to 3D representations.
|
||||
|
||||
Args:
|
||||
x: The [N x * x C] sparse tensor output by the network.
|
||||
|
||||
Returns:
|
||||
list of representations
|
||||
"""
|
||||
ret = []
|
||||
for i in range(x.shape[0]):
|
||||
representation = Gaussian(
|
||||
sh_degree=0,
|
||||
aabb=[-0.5, -0.5, -0.5, 1.0, 1.0, 1.0],
|
||||
mininum_kernel_size = self.rep_config['3d_filter_kernel_size'],
|
||||
scaling_bias = self.rep_config['scaling_bias'],
|
||||
opacity_bias = self.rep_config['opacity_bias'],
|
||||
scaling_activation = self.rep_config['scaling_activation']
|
||||
)
|
||||
xyz = (x.coords[x.layout[i]][:, 1:].float() + 0.5) / self.resolution
|
||||
for k, v in self.layout.items():
|
||||
if k == '_xyz':
|
||||
offset = x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape'])
|
||||
offset = offset * self.rep_config['lr'][k]
|
||||
if self.rep_config['perturb_offset']:
|
||||
offset = offset + self.offset_perturbation
|
||||
offset = torch.tanh(offset) / self.resolution * 0.5 * self.rep_config['voxel_size']
|
||||
_xyz = xyz.unsqueeze(1) + offset
|
||||
setattr(representation, k, _xyz.flatten(0, 1))
|
||||
else:
|
||||
feats = x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape']).flatten(0, 1)
|
||||
feats = feats * self.rep_config['lr'][k]
|
||||
setattr(representation, k, feats)
|
||||
ret.append(representation)
|
||||
return ret
|
||||
|
||||
def forward(self, x: sp.SparseTensor) -> List[Gaussian]:
|
||||
h = super().forward(x)
|
||||
h = h.type(x.dtype)
|
||||
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
||||
h = self.out_layer(h)
|
||||
return self.to_representation(h)
|
||||
|
||||
|
||||
class ElasticSLatGaussianDecoder(SparseTransformerElasticMixin, SLatGaussianDecoder):
|
||||
"""
|
||||
Slat VAE Gaussian decoder with elastic memory management.
|
||||
Used for training with low VRAM.
|
||||
"""
|
||||
pass
|
||||
176
trellis/models/structured_latent_vae/decoder_mesh.py
Normal file
176
trellis/models/structured_latent_vae/decoder_mesh.py
Normal file
@@ -0,0 +1,176 @@
|
||||
from typing import *
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
from ...modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
|
||||
from ...modules import sparse as sp
|
||||
from .base import SparseTransformerBase
|
||||
from ...representations import MeshExtractResult
|
||||
from ...representations.mesh import SparseFeatures2Mesh
|
||||
from ..sparse_elastic_mixin import SparseTransformerElasticMixin
|
||||
|
||||
|
||||
class SparseSubdivideBlock3d(nn.Module):
|
||||
"""
|
||||
A 3D subdivide block that can subdivide the sparse tensor.
|
||||
|
||||
Args:
|
||||
channels: channels in the inputs and outputs.
|
||||
out_channels: if specified, the number of output channels.
|
||||
num_groups: the number of groups for the group norm.
|
||||
"""
|
||||
def __init__(
|
||||
self,
|
||||
channels: int,
|
||||
resolution: int,
|
||||
out_channels: Optional[int] = None,
|
||||
num_groups: int = 32
|
||||
):
|
||||
super().__init__()
|
||||
self.channels = channels
|
||||
self.resolution = resolution
|
||||
self.out_resolution = resolution * 2
|
||||
self.out_channels = out_channels or channels
|
||||
|
||||
self.act_layers = nn.Sequential(
|
||||
sp.SparseGroupNorm32(num_groups, channels),
|
||||
sp.SparseSiLU()
|
||||
)
|
||||
|
||||
self.sub = sp.SparseSubdivide()
|
||||
|
||||
self.out_layers = nn.Sequential(
|
||||
sp.SparseConv3d(channels, self.out_channels, 3, indice_key=f"res_{self.out_resolution}"),
|
||||
sp.SparseGroupNorm32(num_groups, self.out_channels),
|
||||
sp.SparseSiLU(),
|
||||
zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3, indice_key=f"res_{self.out_resolution}")),
|
||||
)
|
||||
|
||||
if self.out_channels == channels:
|
||||
self.skip_connection = nn.Identity()
|
||||
else:
|
||||
self.skip_connection = sp.SparseConv3d(channels, self.out_channels, 1, indice_key=f"res_{self.out_resolution}")
|
||||
|
||||
def forward(self, x: sp.SparseTensor) -> sp.SparseTensor:
|
||||
"""
|
||||
Apply the block to a Tensor, conditioned on a timestep embedding.
|
||||
|
||||
Args:
|
||||
x: an [N x C x ...] Tensor of features.
|
||||
Returns:
|
||||
an [N x C x ...] Tensor of outputs.
|
||||
"""
|
||||
h = self.act_layers(x)
|
||||
h = self.sub(h)
|
||||
x = self.sub(x)
|
||||
h = self.out_layers(h)
|
||||
h = h + self.skip_connection(x)
|
||||
return h
|
||||
|
||||
|
||||
class SLatMeshDecoder(SparseTransformerBase):
|
||||
def __init__(
|
||||
self,
|
||||
resolution: int,
|
||||
model_channels: int,
|
||||
latent_channels: int,
|
||||
num_blocks: int,
|
||||
num_heads: Optional[int] = None,
|
||||
num_head_channels: Optional[int] = 64,
|
||||
mlp_ratio: float = 4,
|
||||
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
||||
window_size: int = 8,
|
||||
pe_mode: Literal["ape", "rope"] = "ape",
|
||||
use_fp16: bool = False,
|
||||
use_checkpoint: bool = False,
|
||||
qk_rms_norm: bool = False,
|
||||
representation_config: dict = None,
|
||||
):
|
||||
super().__init__(
|
||||
in_channels=latent_channels,
|
||||
model_channels=model_channels,
|
||||
num_blocks=num_blocks,
|
||||
num_heads=num_heads,
|
||||
num_head_channels=num_head_channels,
|
||||
mlp_ratio=mlp_ratio,
|
||||
attn_mode=attn_mode,
|
||||
window_size=window_size,
|
||||
pe_mode=pe_mode,
|
||||
use_fp16=use_fp16,
|
||||
use_checkpoint=use_checkpoint,
|
||||
qk_rms_norm=qk_rms_norm,
|
||||
)
|
||||
self.resolution = resolution
|
||||
self.rep_config = representation_config
|
||||
self.mesh_extractor = SparseFeatures2Mesh(res=self.resolution*4, use_color=self.rep_config.get('use_color', False))
|
||||
self.out_channels = self.mesh_extractor.feats_channels
|
||||
self.upsample = nn.ModuleList([
|
||||
SparseSubdivideBlock3d(
|
||||
channels=model_channels,
|
||||
resolution=resolution,
|
||||
out_channels=model_channels // 4
|
||||
),
|
||||
SparseSubdivideBlock3d(
|
||||
channels=model_channels // 4,
|
||||
resolution=resolution * 2,
|
||||
out_channels=model_channels // 8
|
||||
)
|
||||
])
|
||||
self.out_layer = sp.SparseLinear(model_channels // 8, self.out_channels)
|
||||
|
||||
self.initialize_weights()
|
||||
if use_fp16:
|
||||
self.convert_to_fp16()
|
||||
|
||||
def initialize_weights(self) -> None:
|
||||
super().initialize_weights()
|
||||
# Zero-out output layers:
|
||||
nn.init.constant_(self.out_layer.weight, 0)
|
||||
nn.init.constant_(self.out_layer.bias, 0)
|
||||
|
||||
def convert_to_fp16(self) -> None:
|
||||
"""
|
||||
Convert the torso of the model to float16.
|
||||
"""
|
||||
super().convert_to_fp16()
|
||||
self.upsample.apply(convert_module_to_f16)
|
||||
|
||||
def convert_to_fp32(self) -> None:
|
||||
"""
|
||||
Convert the torso of the model to float32.
|
||||
"""
|
||||
super().convert_to_fp32()
|
||||
self.upsample.apply(convert_module_to_f32)
|
||||
|
||||
def to_representation(self, x: sp.SparseTensor) -> List[MeshExtractResult]:
|
||||
"""
|
||||
Convert a batch of network outputs to 3D representations.
|
||||
|
||||
Args:
|
||||
x: The [N x * x C] sparse tensor output by the network.
|
||||
|
||||
Returns:
|
||||
list of representations
|
||||
"""
|
||||
ret = []
|
||||
for i in range(x.shape[0]):
|
||||
mesh = self.mesh_extractor(x[i], training=self.training)
|
||||
ret.append(mesh)
|
||||
return ret
|
||||
|
||||
def forward(self, x: sp.SparseTensor) -> List[MeshExtractResult]:
|
||||
h = super().forward(x)
|
||||
for block in self.upsample:
|
||||
h = block(h)
|
||||
h = h.type(x.dtype)
|
||||
h = self.out_layer(h)
|
||||
return self.to_representation(h)
|
||||
|
||||
|
||||
class ElasticSLatMeshDecoder(SparseTransformerElasticMixin, SLatMeshDecoder):
|
||||
"""
|
||||
Slat VAE Mesh decoder with elastic memory management.
|
||||
Used for training with low VRAM.
|
||||
"""
|
||||
pass
|
||||
113
trellis/models/structured_latent_vae/decoder_rf.py
Normal file
113
trellis/models/structured_latent_vae/decoder_rf.py
Normal file
@@ -0,0 +1,113 @@
|
||||
from typing import *
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
from ...modules import sparse as sp
|
||||
from .base import SparseTransformerBase
|
||||
from ...representations import Strivec
|
||||
from ..sparse_elastic_mixin import SparseTransformerElasticMixin
|
||||
|
||||
|
||||
class SLatRadianceFieldDecoder(SparseTransformerBase):
|
||||
def __init__(
|
||||
self,
|
||||
resolution: int,
|
||||
model_channels: int,
|
||||
latent_channels: int,
|
||||
num_blocks: int,
|
||||
num_heads: Optional[int] = None,
|
||||
num_head_channels: Optional[int] = 64,
|
||||
mlp_ratio: float = 4,
|
||||
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
||||
window_size: int = 8,
|
||||
pe_mode: Literal["ape", "rope"] = "ape",
|
||||
use_fp16: bool = False,
|
||||
use_checkpoint: bool = False,
|
||||
qk_rms_norm: bool = False,
|
||||
representation_config: dict = None,
|
||||
):
|
||||
super().__init__(
|
||||
in_channels=latent_channels,
|
||||
model_channels=model_channels,
|
||||
num_blocks=num_blocks,
|
||||
num_heads=num_heads,
|
||||
num_head_channels=num_head_channels,
|
||||
mlp_ratio=mlp_ratio,
|
||||
attn_mode=attn_mode,
|
||||
window_size=window_size,
|
||||
pe_mode=pe_mode,
|
||||
use_fp16=use_fp16,
|
||||
use_checkpoint=use_checkpoint,
|
||||
qk_rms_norm=qk_rms_norm,
|
||||
)
|
||||
self.resolution = resolution
|
||||
self.rep_config = representation_config
|
||||
self._calc_layout()
|
||||
self.out_layer = sp.SparseLinear(model_channels, self.out_channels)
|
||||
|
||||
self.initialize_weights()
|
||||
if use_fp16:
|
||||
self.convert_to_fp16()
|
||||
|
||||
def initialize_weights(self) -> None:
|
||||
super().initialize_weights()
|
||||
# Zero-out output layers:
|
||||
nn.init.constant_(self.out_layer.weight, 0)
|
||||
nn.init.constant_(self.out_layer.bias, 0)
|
||||
|
||||
def _calc_layout(self) -> None:
|
||||
self.layout = {
|
||||
'trivec': {'shape': (self.rep_config['rank'], 3, self.rep_config['dim']), 'size': self.rep_config['rank'] * 3 * self.rep_config['dim']},
|
||||
'density': {'shape': (self.rep_config['rank'],), 'size': self.rep_config['rank']},
|
||||
'features_dc': {'shape': (self.rep_config['rank'], 1, 3), 'size': self.rep_config['rank'] * 3},
|
||||
}
|
||||
start = 0
|
||||
for k, v in self.layout.items():
|
||||
v['range'] = (start, start + v['size'])
|
||||
start += v['size']
|
||||
self.out_channels = start
|
||||
|
||||
def to_representation(self, x: sp.SparseTensor) -> List[Strivec]:
|
||||
"""
|
||||
Convert a batch of network outputs to 3D representations.
|
||||
|
||||
Args:
|
||||
x: The [N x * x C] sparse tensor output by the network.
|
||||
|
||||
Returns:
|
||||
list of representations
|
||||
"""
|
||||
ret = []
|
||||
for i in range(x.shape[0]):
|
||||
representation = Strivec(
|
||||
sh_degree=0,
|
||||
resolution=self.resolution,
|
||||
aabb=[-0.5, -0.5, -0.5, 1, 1, 1],
|
||||
rank=self.rep_config['rank'],
|
||||
dim=self.rep_config['dim'],
|
||||
device='cuda',
|
||||
)
|
||||
representation.density_shift = 0.0
|
||||
representation.position = (x.coords[x.layout[i]][:, 1:].float() + 0.5) / self.resolution
|
||||
representation.depth = torch.full((representation.position.shape[0], 1), int(np.log2(self.resolution)), dtype=torch.uint8, device='cuda')
|
||||
for k, v in self.layout.items():
|
||||
setattr(representation, k, x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape']))
|
||||
representation.trivec = representation.trivec + 1
|
||||
ret.append(representation)
|
||||
return ret
|
||||
|
||||
def forward(self, x: sp.SparseTensor) -> List[Strivec]:
|
||||
h = super().forward(x)
|
||||
h = h.type(x.dtype)
|
||||
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
||||
h = self.out_layer(h)
|
||||
return self.to_representation(h)
|
||||
|
||||
|
||||
class ElasticSLatRadianceFieldDecoder(SparseTransformerElasticMixin, SLatRadianceFieldDecoder):
|
||||
"""
|
||||
Slat VAE Radiance Field Decoder with elastic memory management.
|
||||
Used for training with low VRAM.
|
||||
"""
|
||||
pass
|
||||
80
trellis/models/structured_latent_vae/encoder.py
Normal file
80
trellis/models/structured_latent_vae/encoder.py
Normal file
@@ -0,0 +1,80 @@
|
||||
from typing import *
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from ...modules import sparse as sp
|
||||
from .base import SparseTransformerBase
|
||||
from ..sparse_elastic_mixin import SparseTransformerElasticMixin
|
||||
|
||||
|
||||
class SLatEncoder(SparseTransformerBase):
|
||||
def __init__(
|
||||
self,
|
||||
resolution: int,
|
||||
in_channels: int,
|
||||
model_channels: int,
|
||||
latent_channels: int,
|
||||
num_blocks: int,
|
||||
num_heads: Optional[int] = None,
|
||||
num_head_channels: Optional[int] = 64,
|
||||
mlp_ratio: float = 4,
|
||||
attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin",
|
||||
window_size: int = 8,
|
||||
pe_mode: Literal["ape", "rope"] = "ape",
|
||||
use_fp16: bool = False,
|
||||
use_checkpoint: bool = False,
|
||||
qk_rms_norm: bool = False,
|
||||
):
|
||||
super().__init__(
|
||||
in_channels=in_channels,
|
||||
model_channels=model_channels,
|
||||
num_blocks=num_blocks,
|
||||
num_heads=num_heads,
|
||||
num_head_channels=num_head_channels,
|
||||
mlp_ratio=mlp_ratio,
|
||||
attn_mode=attn_mode,
|
||||
window_size=window_size,
|
||||
pe_mode=pe_mode,
|
||||
use_fp16=use_fp16,
|
||||
use_checkpoint=use_checkpoint,
|
||||
qk_rms_norm=qk_rms_norm,
|
||||
)
|
||||
self.resolution = resolution
|
||||
self.out_layer = sp.SparseLinear(model_channels, 2 * latent_channels)
|
||||
|
||||
self.initialize_weights()
|
||||
if use_fp16:
|
||||
self.convert_to_fp16()
|
||||
|
||||
def initialize_weights(self) -> None:
|
||||
super().initialize_weights()
|
||||
# Zero-out output layers:
|
||||
nn.init.constant_(self.out_layer.weight, 0)
|
||||
nn.init.constant_(self.out_layer.bias, 0)
|
||||
|
||||
def forward(self, x: sp.SparseTensor, sample_posterior=True, return_raw=False):
|
||||
h = super().forward(x)
|
||||
h = h.type(x.dtype)
|
||||
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:]))
|
||||
h = self.out_layer(h)
|
||||
|
||||
# Sample from the posterior distribution
|
||||
mean, logvar = h.feats.chunk(2, dim=-1)
|
||||
if sample_posterior:
|
||||
std = torch.exp(0.5 * logvar)
|
||||
z = mean + std * torch.randn_like(std)
|
||||
else:
|
||||
z = mean
|
||||
z = h.replace(z)
|
||||
|
||||
if return_raw:
|
||||
return z, mean, logvar
|
||||
else:
|
||||
return z
|
||||
|
||||
|
||||
class ElasticSLatEncoder(SparseTransformerElasticMixin, SLatEncoder):
|
||||
"""
|
||||
SLat VAE encoder with elastic memory management.
|
||||
Used for training with low VRAM.
|
||||
"""
|
||||
Reference in New Issue
Block a user