Spaces:
Build error
Build error
Commit ·
db6a3b7
1
Parent(s): ceccc26
Upload
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- app.pyAdded+152
- assets/example_image/T.pngAdded
- assets/example_image/typical_building_building.pngAdded
- assets/example_image/typical_building_castle.pngAdded
- assets/example_image/typical_building_colorful_cottage.pngAdded
- assets/example_image/typical_building_maya_pyramid.pngAdded
- assets/example_image/typical_building_mushroom.pngAdded
- assets/example_image/typical_building_space_station.pngAdded
- assets/example_image/typical_creature_dragon.pngAdded
- assets/example_image/typical_creature_elephant.pngAdded
- assets/example_image/typical_creature_furry.pngAdded
- assets/example_image/typical_creature_quadruped.pngAdded
- assets/example_image/typical_creature_robot_crab.pngAdded
- assets/example_image/typical_creature_robot_dinosour.pngAdded
- assets/example_image/typical_creature_rock_monster.pngAdded
- assets/example_image/typical_humanoid_block_robot.pngAdded
- assets/example_image/typical_humanoid_dragonborn.pngAdded
- assets/example_image/typical_humanoid_dwarf.pngAdded
- assets/example_image/typical_humanoid_goblin.pngAdded
- assets/example_image/typical_humanoid_mech.pngAdded
- assets/example_image/typical_misc_crate.pngAdded
- assets/example_image/typical_misc_fireplace.pngAdded
- assets/example_image/typical_misc_gate.pngAdded
- assets/example_image/typical_misc_lantern.pngAdded
- assets/example_image/typical_misc_magicbook.pngAdded
- assets/example_image/typical_misc_mailbox.pngAdded
- assets/example_image/typical_misc_monster_chest.pngAdded
- assets/example_image/typical_misc_paper_machine.pngAdded
- assets/example_image/typical_misc_phonograph.pngAdded
- assets/example_image/typical_misc_portal2.pngAdded
- assets/example_image/typical_misc_storage_chest.pngAdded
- assets/example_image/typical_misc_telephone.pngAdded
- assets/example_image/typical_misc_television.pngAdded
- assets/example_image/typical_misc_workbench.pngAdded
- assets/example_image/typical_vehicle_biplane.pngAdded
- assets/example_image/typical_vehicle_bulldozer.pngAdded
- assets/example_image/typical_vehicle_cart.pngAdded
- assets/example_image/typical_vehicle_excavator.pngAdded
- assets/example_image/typical_vehicle_helicopter.pngAdded
- assets/example_image/typical_vehicle_locomotive.pngAdded
- assets/example_image/typical_vehicle_pirate_ship.pngAdded
- assets/example_image/weatherworn_misc_paper_machine3.pngAdded
- requirements.txtAdded+28
- trellis/__init__.pyAdded+6
- trellis/models/__init__.pyAdded+70
- trellis/models/sparse_structure_flow.pyAdded+200
- trellis/models/sparse_structure_vae.pyAdded+306
- trellis/models/structured_latent_flow.pyAdded+262
- trellis/models/structured_latent_vae/__init__.pyAdded+4
- trellis/models/structured_latent_vae/base.pyAdded+117
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import gradio as gr# from gradio_litmodel3d import LitModel3D
import osfrom typing import *import imageioimport uuidfrom PIL import Imagefrom trellis.pipelines import TrellisImageTo3DPipelinefrom trellis.utils import render_utils, postprocessing_utils
def preprocess_image(image: Image.Image) -> Image.Image: """ Preprocess the input image.
Args: image (Image.Image): The input image.
Returns: Image.Image: The preprocessed image. """ return pipeline.preprocess_image(image)
def image_to_3d(image: Image.Image) -> Tuple[dict, str]: """ Convert an image to a 3D model.
Args: image (Image.Image): The input image.
Returns: dict: The information of the generated 3D model. str: The path to the video of the 3D model. """ outputs = pipeline(image, formats=["gaussian", "mesh"], preprocess_image=False) video = render_utils.render_video(outputs['gaussian'][0])['color'] model_id = uuid.uuid4() video_path = f"/tmp/Trellis-demo/{model_id}.mp4" os.makedirs(os.path.dirname(video_path), exist_ok=True) imageio.mimsave(video_path, video, fps=30) model = {'gaussian': outputs['gaussian'][0], 'mesh': outputs['mesh'][0], 'model_id': model_id} return model, video_path
def extract_glb(model: dict, mesh_simplify: float, texture_size: int) -> Tuple[str, str]: """ Extract a GLB file from the 3D model.
Args: model (dict): The generated 3D model. mesh_simplify (float): The mesh simplification factor. texture_size (int): The texture resolution.
Returns: str: The path to the extracted GLB file. """ glb = postprocessing_utils.to_glb(model['gaussian'], model['mesh'], simplify=mesh_simplify, texture_size=texture_size) glb_path = f"/tmp/Trellis-demo/{model['model_id']}.glb" glb.export(glb_path) return glb_path, glb_path
def activate_button() -> gr.Button: return gr.Button(interactive=True)
def deactivate_button() -> gr.Button: return gr.Button(interactive=False)
with gr.Blocks() as demo: with gr.Row(): with gr.Column(): image_prompt = gr.Image(label="Image Prompt", image_mode="RGBA", type="pil", height=300) generate_btn = gr.Button("Generate", interactive=False)
mesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01) texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512) extract_glb_btn = gr.Button("Extract GLB", interactive=False)
with gr.Column(): video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300) model_output = gr.Model3D(label="Extracted GLB", height=300) download_glb = gr.DownloadButton(label="Download GLB", interactive=False)
# Example images at the bottom of the page with gr.Row(): examples = gr.Examples( examples=[ f'assets/example_image/{image}' for image in os.listdir("assets/example_image") ], inputs=[image_prompt], fn=lambda image: (preprocess_image(image), gr.Button(interactive=True)), outputs=[image_prompt, generate_btn], run_on_click=True, examples_per_page=64, )
model = gr.State()
# Handlers image_prompt.upload( preprocess_image, inputs=[image_prompt], outputs=[image_prompt], ).then( activate_button, outputs=[generate_btn], )
image_prompt.clear( deactivate_button, outputs=[generate_btn], )
generate_btn.click( image_to_3d, inputs=[image_prompt], outputs=[model, video_output], ).then( activate_button, outputs=[extract_glb_btn], )
video_output.clear( deactivate_button, outputs=[extract_glb_btn], )
extract_glb_btn.click( extract_glb, inputs=[model, mesh_simplify, texture_size], outputs=[model_output, download_glb], ).then( activate_button, outputs=[download_glb], )
model_output.clear( deactivate_button, outputs=[download_glb], )
# Launch the Gradio appif __name__ == "__main__": pipeline = TrellisImageTo3DPipeline.from_pretrained("JeffreyXiang/TRELLIS-image-large") pipeline.cuda() demo.launch()12345678910111213141516171819202122232425262728--extra-index-url https://download.pytorch.org/whl/cu118--find-links https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.4.0_cu121.html
torch==2.4.0torchvision==0.19.0pillow==10.4.0imageio==2.36.1imageio-ffmpeg==0.5.1tqdm==4.67.1easydict==1.13opencv-python-headless==4.10.0.84scipy==1.14.1rembg==2.0.60onnxruntime==1.20.1trimesh==4.5.3xatlas==0.0.9pyvista==0.44.2pymeshfix==0.17.0igraph==0.11.8git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8xformers==0.0.27.post2+cu118flash-attn==2.7.0.post2kaolin==0.17.0spconv-cu118==2.3.6transformers==4.46.3wheels/nvdiffrast-0.3.3-py3-none-any.whlwheels/diff_gaussian_rasterization-0.0.0-cp310-cp310-linux_x86_64.whl123456from . import modelsfrom . import modulesfrom . import pipelinesfrom . import renderersfrom . import representationsfrom . import utils12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import importlib
__attributes = { 'SparseStructureEncoder': 'sparse_structure_vae', 'SparseStructureDecoder': 'sparse_structure_vae', 'SparseStructureFlowModel': 'sparse_structure_flow', 'SLatEncoder': 'structured_latent_vae', 'SLatGaussianDecoder': 'structured_latent_vae', 'SLatRadianceFieldDecoder': 'structured_latent_vae', 'SLatMeshDecoder': 'structured_latent_vae', 'SLatFlowModel': 'structured_latent_flow',}
__submodules = []
__all__ = list(__attributes.keys()) + __submodules
def __getattr__(name): if name not in globals(): if name in __attributes: module_name = __attributes[name] module = importlib.import_module(f".{module_name}", __name__) globals()[name] = getattr(module, name) elif name in __submodules: module = importlib.import_module(f".{name}", __name__) globals()[name] = module else: raise AttributeError(f"module {__name__} has no attribute {name}") return globals()[name]
def from_pretrained(path: str, **kwargs): """ Load a model from a pretrained checkpoint.
Args: path: The path to the checkpoint. Can be either local path or a Hugging Face model name. NOTE: config file and model file should take the name f'{path}.json' and f'{path}.safetensors' respectively. **kwargs: Additional arguments for the model constructor. """ import os import json from safetensors.torch import load_file is_local = os.path.exists(f"{path}.json") and os.path.exists(f"{path}.safetensors")
if is_local: config_file = f"{path}.json" model_file = f"{path}.safetensors" else: from huggingface_hub import hf_hub_download path_parts = path.split('/') repo_id = f'{path_parts[0]}/{path_parts[1]}' model_name = '/'.join(path_parts[2:]) config_file = hf_hub_download(repo_id, f"{model_name}.json") model_file = hf_hub_download(repo_id, f"{model_name}.safetensors")
with open(config_file, 'r') as f: config = json.load(f) model = __getattr__(config['name'])(**config['args'], **kwargs) model.load_state_dict(load_file(model_file))
return model
# For Pylanceif __name__ == '__main__': from .sparse_structure_vae import SparseStructureEncoder, SparseStructureDecoder from .sparse_structure_flow import SparseStructureFlowModel from .structured_latent_vae import SLatEncoder, SLatGaussianDecoder, SLatRadianceFieldDecoder, SLatMeshDecoder from .structured_latent_flow import SLatFlowModel123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Fimport numpy as npfrom ..modules.utils import convert_module_to_f16, convert_module_to_f32from ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlockfrom ..modules.spatial import patchify, unpatchify
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """ def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000): """ Create sinusoidal timestep embeddings.
Args: t: a 1-D Tensor of N indices, one per batch element. These may be fractional. dim: the dimension of the output. max_period: controls the minimum frequency of the embeddings.
Returns: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 freqs = torch.exp( -np.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t): t_freq = self.timestep_embedding(t, self.frequency_embedding_size) t_emb = self.mlp(t_freq) return t_emb
class SparseStructureFlowModel(nn.Module): def __init__( self, resolution: int, in_channels: int, model_channels: int, cond_channels: int, out_channels: int, num_blocks: int, num_heads: Optional[int] = None, num_head_channels: Optional[int] = 64, mlp_ratio: float = 4, patch_size: int = 2, pe_mode: Literal["ape", "rope"] = "ape", use_fp16: bool = False, use_checkpoint: bool = False, share_mod: bool = False, qk_rms_norm: bool = False, qk_rms_norm_cross: bool = False, ): super().__init__() self.resolution = resolution self.in_channels = in_channels self.model_channels = model_channels self.cond_channels = cond_channels self.out_channels = out_channels self.num_blocks = num_blocks self.num_heads = num_heads or model_channels // num_head_channels self.mlp_ratio = mlp_ratio self.patch_size = patch_size self.pe_mode = pe_mode self.use_fp16 = use_fp16 self.use_checkpoint = use_checkpoint self.share_mod = share_mod self.qk_rms_norm = qk_rms_norm self.qk_rms_norm_cross = qk_rms_norm_cross self.dtype = torch.float16 if use_fp16 else torch.float32
self.t_embedder = TimestepEmbedder(model_channels) if share_mod: self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(model_channels, 6 * model_channels, bias=True) )
if pe_mode == "ape": pos_embedder = AbsolutePositionEmbedder(model_channels, 3) coords = torch.meshgrid(*[torch.arange(res, device=self.device) for res in [resolution // patch_size] * 3], indexing='ij') coords = torch.stack(coords, dim=-1).reshape(-1, 3) pos_emb = pos_embedder(coords) self.register_buffer("pos_emb", pos_emb)
self.input_layer = nn.Linear(in_channels * patch_size**3, model_channels) self.blocks = nn.ModuleList([ ModulatedTransformerCrossBlock( model_channels, cond_channels, num_heads=self.num_heads, mlp_ratio=self.mlp_ratio, attn_mode='full', use_checkpoint=self.use_checkpoint, use_rope=(pe_mode == "rope"), share_mod=share_mod, qk_rms_norm=self.qk_rms_norm, qk_rms_norm_cross=self.qk_rms_norm_cross, ) for _ in range(num_blocks) ])
self.out_layer = nn.Linear(model_channels, out_channels * patch_size**3)
self.initialize_weights() if use_fp16: self.convert_to_fp16()
@property def device(self) -> torch.device: """ Return the device of the model. """ return next(self.parameters()).device
def convert_to_fp16(self) -> None: """ Convert the torso of the model to float16. """ self.blocks.apply(convert_module_to_f16)
def convert_to_fp32(self) -> None: """ Convert the torso of the model to float32. """ self.blocks.apply(convert_module_to_f32)
def initialize_weights(self) -> None: # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in DiT blocks: if self.share_mod: nn.init.constant_(self.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.adaLN_modulation[-1].bias, 0) else: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers: nn.init.constant_(self.out_layer.weight, 0) nn.init.constant_(self.out_layer.bias, 0)
def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: assert [*x.shape] == [x.shape[0], self.in_channels, *[self.resolution] * 3], \ f"Input shape mismatch, got {x.shape}, expected {[x.shape[0], self.in_channels, *[self.resolution] * 3]}"
h = patchify(x, self.patch_size) h = h.view(*h.shape[:2], -1).permute(0, 2, 1).contiguous()
h = self.input_layer(h) h = h + self.pos_emb[None] t_emb = self.t_embedder(t) if self.share_mod: t_emb = self.adaLN_modulation(t_emb) t_emb = t_emb.type(self.dtype) h = h.type(self.dtype) cond = cond.type(self.dtype) for block in self.blocks: h = block(h, t_emb, cond) h = h.type(x.dtype) h = F.layer_norm(h, h.shape[-1:]) h = self.out_layer(h)
h = h.permute(0, 2, 1).view(h.shape[0], h.shape[2], *[self.resolution // self.patch_size] * 3) h = unpatchify(h, self.patch_size).contiguous()
return h123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Ffrom ..modules.norm import GroupNorm32, ChannelLayerNorm32from ..modules.spatial import pixel_shuffle_3dfrom ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
def norm_layer(norm_type: str, *args, **kwargs) -> nn.Module: """ Return a normalization layer. """ if norm_type == "group": return GroupNorm32(32, *args, **kwargs) elif norm_type == "layer": return ChannelLayerNorm32(*args, **kwargs) else: raise ValueError(f"Invalid norm type {norm_type}")
class ResBlock3d(nn.Module): def __init__( self, channels: int, out_channels: Optional[int] = None, norm_type: Literal["group", "layer"] = "layer", ): super().__init__() self.channels = channels self.out_channels = out_channels or channels
self.norm1 = norm_layer(norm_type, channels) self.norm2 = norm_layer(norm_type, self.out_channels) self.conv1 = nn.Conv3d(channels, self.out_channels, 3, padding=1) self.conv2 = zero_module(nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1)) self.skip_connection = nn.Conv3d(channels, self.out_channels, 1) if channels != self.out_channels else nn.Identity() def forward(self, x: torch.Tensor) -> torch.Tensor: h = self.norm1(x) h = F.silu(h) h = self.conv1(h) h = self.norm2(h) h = F.silu(h) h = self.conv2(h) h = h + self.skip_connection(x) return h
class DownsampleBlock3d(nn.Module): def __init__( self, in_channels: int, out_channels: int, mode: Literal["conv", "avgpool"] = "conv", ): assert mode in ["conv", "avgpool"], f"Invalid mode {mode}"
super().__init__() self.in_channels = in_channels self.out_channels = out_channels
if mode == "conv": self.conv = nn.Conv3d(in_channels, out_channels, 2, stride=2) elif mode == "avgpool": assert in_channels == out_channels, "Pooling mode requires in_channels to be equal to out_channels"
def forward(self, x: torch.Tensor) -> torch.Tensor: if hasattr(self, "conv"): return self.conv(x) else: return F.avg_pool3d(x, 2)
class UpsampleBlock3d(nn.Module): def __init__( self, in_channels: int, out_channels: int, mode: Literal["conv", "nearest"] = "conv", ): assert mode in ["conv", "nearest"], f"Invalid mode {mode}"
super().__init__() self.in_channels = in_channels self.out_channels = out_channels
if mode == "conv": self.conv = nn.Conv3d(in_channels, out_channels*8, 3, padding=1) elif mode == "nearest": assert in_channels == out_channels, "Nearest mode requires in_channels to be equal to out_channels"
def forward(self, x: torch.Tensor) -> torch.Tensor: if hasattr(self, "conv"): x = self.conv(x) return pixel_shuffle_3d(x, 2) else: return F.interpolate(x, scale_factor=2, mode="nearest")
class SparseStructureEncoder(nn.Module): """ Encoder for Sparse Structure (\mathcal{E}_S in the paper Sec. 3.3). Args: in_channels (int): Channels of the input. latent_channels (int): Channels of the latent representation. num_res_blocks (int): Number of residual blocks at each resolution. channels (List[int]): Channels of the encoder blocks. num_res_blocks_middle (int): Number of residual blocks in the middle. norm_type (Literal["group", "layer"]): Type of normalization layer. use_fp16 (bool): Whether to use FP16. """ def __init__( self, in_channels: int, latent_channels: int, num_res_blocks: int, channels: List[int], num_res_blocks_middle: int = 2, norm_type: Literal["group", "layer"] = "layer", use_fp16: bool = False, ): super().__init__() self.in_channels = in_channels self.latent_channels = latent_channels self.num_res_blocks = num_res_blocks self.channels = channels self.num_res_blocks_middle = num_res_blocks_middle self.norm_type = norm_type self.use_fp16 = use_fp16 self.dtype = torch.float16 if use_fp16 else torch.float32
self.input_layer = nn.Conv3d(in_channels, channels[0], 3, padding=1)
self.blocks = nn.ModuleList([]) for i, ch in enumerate(channels): self.blocks.extend([ ResBlock3d(ch, ch) for _ in range(num_res_blocks) ]) if i < len(channels) - 1: self.blocks.append( DownsampleBlock3d(ch, channels[i+1]) ) self.middle_block = nn.Sequential(*[ ResBlock3d(channels[-1], channels[-1]) for _ in range(num_res_blocks_middle) ])
self.out_layer = nn.Sequential( norm_layer(norm_type, channels[-1]), nn.SiLU(), nn.Conv3d(channels[-1], latent_channels*2, 3, padding=1) )
if use_fp16: self.convert_to_fp16()
@property def device(self) -> torch.device: """ Return the device of the model. """ return next(self.parameters()).device
def convert_to_fp16(self) -> None: """ Convert the torso of the model to float16. """ self.use_fp16 = True self.dtype = torch.float16 self.blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16)
def convert_to_fp32(self) -> None: """ Convert the torso of the model to float32. """ self.use_fp16 = False self.dtype = torch.float32 self.blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32)
def forward(self, x: torch.Tensor, sample_posterior: bool = False, return_raw: bool = False) -> torch.Tensor: h = self.input_layer(x) h = h.type(self.dtype)
for block in self.blocks: h = block(h) h = self.middle_block(h)
h = h.type(x.dtype) h = self.out_layer(h)
mean, logvar = h.chunk(2, dim=1)
if sample_posterior: std = torch.exp(0.5 * logvar) z = mean + std * torch.randn_like(std) else: z = mean if return_raw: return z, mean, logvar return z
class SparseStructureDecoder(nn.Module): """ Decoder for Sparse Structure (\mathcal{D}_S in the paper Sec. 3.3). Args: out_channels (int): Channels of the output. latent_channels (int): Channels of the latent representation. num_res_blocks (int): Number of residual blocks at each resolution. channels (List[int]): Channels of the decoder blocks. num_res_blocks_middle (int): Number of residual blocks in the middle. norm_type (Literal["group", "layer"]): Type of normalization layer. use_fp16 (bool): Whether to use FP16. """ def __init__( self, out_channels: int, latent_channels: int, num_res_blocks: int, channels: List[int], num_res_blocks_middle: int = 2, norm_type: Literal["group", "layer"] = "layer", use_fp16: bool = False, ): super().__init__() self.out_channels = out_channels self.latent_channels = latent_channels self.num_res_blocks = num_res_blocks self.channels = channels self.num_res_blocks_middle = num_res_blocks_middle self.norm_type = norm_type self.use_fp16 = use_fp16 self.dtype = torch.float16 if use_fp16 else torch.float32
self.input_layer = nn.Conv3d(latent_channels, channels[0], 3, padding=1)
self.middle_block = nn.Sequential(*[ ResBlock3d(channels[0], channels[0]) for _ in range(num_res_blocks_middle) ])
self.blocks = nn.ModuleList([]) for i, ch in enumerate(channels): self.blocks.extend([ ResBlock3d(ch, ch) for _ in range(num_res_blocks) ]) if i < len(channels) - 1: self.blocks.append( UpsampleBlock3d(ch, channels[i+1]) )
self.out_layer = nn.Sequential( norm_layer(norm_type, channels[-1]), nn.SiLU(), nn.Conv3d(channels[-1], out_channels, 3, padding=1) )
if use_fp16: self.convert_to_fp16()
@property def device(self) -> torch.device: """ Return the device of the model. """ return next(self.parameters()).device def convert_to_fp16(self) -> None: """ Convert the torso of the model to float16. """ self.use_fp16 = True self.dtype = torch.float16 self.blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16)
def convert_to_fp32(self) -> None: """ Convert the torso of the model to float32. """ self.use_fp16 = False self.dtype = torch.float32 self.blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32) def forward(self, x: torch.Tensor) -> torch.Tensor: h = self.input_layer(x) h = h.type(self.dtype) h = self.middle_block(h) for block in self.blocks: h = block(h)
h = h.type(x.dtype) h = self.out_layer(h) return h123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Fimport numpy as npfrom ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32from ..modules.transformer import AbsolutePositionEmbedderfrom ..modules.norm import LayerNorm32from ..modules import sparse as spfrom ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlockfrom .sparse_structure_flow import TimestepEmbedder
class SparseResBlock3d(nn.Module): def __init__( self, channels: int, emb_channels: int, out_channels: Optional[int] = None, downsample: bool = False, upsample: bool = False, ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.out_channels = out_channels or channels self.downsample = downsample self.upsample = upsample assert not (downsample and upsample), "Cannot downsample and upsample at the same time"
self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6) self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3) self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3)) self.emb_layers = nn.Sequential( nn.SiLU(), nn.Linear(emb_channels, 2 * self.out_channels, bias=True), ) self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity() self.updown = None if self.downsample: self.updown = sp.SparseDownsample(2) elif self.upsample: self.updown = sp.SparseUpsample(2)
def _updown(self, x: sp.SparseTensor) -> sp.SparseTensor: if self.updown is not None: x = self.updown(x) return x
def forward(self, x: sp.SparseTensor, emb: torch.Tensor) -> sp.SparseTensor: emb_out = self.emb_layers(emb).type(x.dtype) scale, shift = torch.chunk(emb_out, 2, dim=1)
x = self._updown(x) h = x.replace(self.norm1(x.feats)) h = h.replace(F.silu(h.feats)) h = self.conv1(h) h = h.replace(self.norm2(h.feats)) * (1 + scale) + shift h = h.replace(F.silu(h.feats)) h = self.conv2(h) h = h + self.skip_connection(x)
return h
class SLatFlowModel(nn.Module): def __init__( self, resolution: int, in_channels: int, model_channels: int, cond_channels: int, out_channels: int, num_blocks: int, num_heads: Optional[int] = None, num_head_channels: Optional[int] = 64, mlp_ratio: float = 4, patch_size: int = 2, num_io_res_blocks: int = 2, io_block_channels: List[int] = None, pe_mode: Literal["ape", "rope"] = "ape", use_fp16: bool = False, use_checkpoint: bool = False, use_skip_connection: bool = True, share_mod: bool = False, qk_rms_norm: bool = False, qk_rms_norm_cross: bool = False, ): super().__init__() self.resolution = resolution self.in_channels = in_channels self.model_channels = model_channels self.cond_channels = cond_channels self.out_channels = out_channels self.num_blocks = num_blocks self.num_heads = num_heads or model_channels // num_head_channels self.mlp_ratio = mlp_ratio self.patch_size = patch_size self.num_io_res_blocks = num_io_res_blocks self.io_block_channels = io_block_channels self.pe_mode = pe_mode self.use_fp16 = use_fp16 self.use_checkpoint = use_checkpoint self.use_skip_connection = use_skip_connection self.share_mod = share_mod self.qk_rms_norm = qk_rms_norm self.qk_rms_norm_cross = qk_rms_norm_cross self.dtype = torch.float16 if use_fp16 else torch.float32
assert int(np.log2(patch_size)) == np.log2(patch_size), "Patch size must be a power of 2" assert np.log2(patch_size) == len(io_block_channels), "Number of IO ResBlocks must match the number of stages"
self.t_embedder = TimestepEmbedder(model_channels) if share_mod: self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(model_channels, 6 * model_channels, bias=True) )
if pe_mode == "ape": self.pos_embedder = AbsolutePositionEmbedder(model_channels)
self.input_layer = sp.SparseLinear(in_channels, io_block_channels[0]) self.input_blocks = nn.ModuleList([]) for chs, next_chs in zip(io_block_channels, io_block_channels[1:] + [model_channels]): self.input_blocks.extend([ SparseResBlock3d( chs, model_channels, out_channels=chs, ) for _ in range(num_io_res_blocks-1) ]) self.input_blocks.append( SparseResBlock3d( chs, model_channels, out_channels=next_chs, downsample=True, ) ) self.blocks = nn.ModuleList([ ModulatedSparseTransformerCrossBlock( model_channels, cond_channels, num_heads=self.num_heads, mlp_ratio=self.mlp_ratio, attn_mode='full', use_checkpoint=self.use_checkpoint, use_rope=(pe_mode == "rope"), share_mod=self.share_mod, qk_rms_norm=self.qk_rms_norm, qk_rms_norm_cross=self.qk_rms_norm_cross, ) for _ in range(num_blocks) ])
self.out_blocks = nn.ModuleList([]) for chs, prev_chs in zip(reversed(io_block_channels), [model_channels] + list(reversed(io_block_channels[1:]))): self.out_blocks.append( SparseResBlock3d( prev_chs * 2 if self.use_skip_connection else prev_chs, model_channels, out_channels=chs, upsample=True, ) ) self.out_blocks.extend([ SparseResBlock3d( chs * 2 if self.use_skip_connection else chs, model_channels, out_channels=chs, ) for _ in range(num_io_res_blocks-1) ]) self.out_layer = sp.SparseLinear(io_block_channels[0], out_channels)
self.initialize_weights() if use_fp16: self.convert_to_fp16()
@property def device(self) -> torch.device: """ Return the device of the model. """ return next(self.parameters()).device
def convert_to_fp16(self) -> None: """ Convert the torso of the model to float16. """ self.input_blocks.apply(convert_module_to_f16) self.blocks.apply(convert_module_to_f16) self.out_blocks.apply(convert_module_to_f16)
def convert_to_fp32(self) -> None: """ Convert the torso of the model to float32. """ self.input_blocks.apply(convert_module_to_f32) self.blocks.apply(convert_module_to_f32) self.out_blocks.apply(convert_module_to_f32)
def initialize_weights(self) -> None: # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in DiT blocks: if self.share_mod: nn.init.constant_(self.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.adaLN_modulation[-1].bias, 0) else: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# 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, t: torch.Tensor, cond: torch.Tensor) -> sp.SparseTensor: h = self.input_layer(x).type(self.dtype) t_emb = self.t_embedder(t) if self.share_mod: t_emb = self.adaLN_modulation(t_emb) t_emb = t_emb.type(self.dtype) cond = cond.type(self.dtype)
skips = [] # pack with input blocks for block in self.input_blocks: h = block(h, t_emb) skips.append(h.feats) if self.pe_mode == "ape": h = h + self.pos_embedder(h.coords[:, 1:]).type(self.dtype) for block in self.blocks: h = block(h, t_emb, cond)
# unpack with output blocks for block, skip in zip(self.out_blocks, reversed(skips)): if self.use_skip_connection: h = block(h.replace(torch.cat([h.feats, skip], dim=1)), t_emb) else: h = block(h, t_emb)
h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) h = self.out_layer(h.type(x.dtype)) return h1234from .encoder import SLatEncoderfrom .decoder_gs import SLatGaussianDecoderfrom .decoder_rf import SLatRadianceFieldDecoderfrom .decoder_mesh import SLatMeshDecoder123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117from typing import *import torchimport torch.nn as nnfrom ...modules.utils import convert_module_to_f16, convert_module_to_f32from ...modules import sparse as spfrom ...modules.transformer import AbsolutePositionEmbedderfrom ...modules.sparse.transformer import SparseTransformerBlock
def block_attn_config(self): """ Return the attention configuration of the model. """ for i in range(self.num_blocks): if self.attn_mode == "shift_window": yield "serialized", self.window_size, 0, (16 * (i % 2),) * 3, sp.SerializeMode.Z_ORDER elif self.attn_mode == "shift_sequence": yield "serialized", self.window_size, self.window_size // 2 * (i % 2), (0, 0, 0), sp.SerializeMode.Z_ORDER elif self.attn_mode == "shift_order": yield "serialized", self.window_size, 0, (0, 0, 0), sp.SerializeModes[i % 4] elif self.attn_mode == "full": yield "full", None, None, None, None elif self.attn_mode == "swin": yield "windowed", self.window_size, None, self.window_size // 2 * (i % 2), None
class SparseTransformerBase(nn.Module): """ Sparse Transformer without output layers. Serve as the base class for encoder and decoder. """ def __init__( self, in_channels: int, model_channels: int, num_blocks: int, num_heads: Optional[int] = None, num_head_channels: Optional[int] = 64, mlp_ratio: float = 4.0, attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full", window_size: Optional[int] = None, pe_mode: Literal["ape", "rope"] = "ape", use_fp16: bool = False, use_checkpoint: bool = False, qk_rms_norm: bool = False, ): super().__init__() self.in_channels = in_channels self.model_channels = model_channels self.num_blocks = num_blocks self.window_size = window_size self.num_heads = num_heads or model_channels // num_head_channels self.mlp_ratio = mlp_ratio self.attn_mode = attn_mode self.pe_mode = pe_mode self.use_fp16 = use_fp16 self.use_checkpoint = use_checkpoint self.qk_rms_norm = qk_rms_norm self.dtype = torch.float16 if use_fp16 else torch.float32
if pe_mode == "ape": self.pos_embedder = AbsolutePositionEmbedder(model_channels)
self.input_layer = sp.SparseLinear(in_channels, model_channels) self.blocks = nn.ModuleList([ SparseTransformerBlock( model_channels, num_heads=self.num_heads, mlp_ratio=self.mlp_ratio, attn_mode=attn_mode, window_size=window_size, shift_sequence=shift_sequence, shift_window=shift_window, serialize_mode=serialize_mode, use_checkpoint=self.use_checkpoint, use_rope=(pe_mode == "rope"), qk_rms_norm=self.qk_rms_norm, ) for attn_mode, window_size, shift_sequence, shift_window, serialize_mode in block_attn_config(self) ])
@property def device(self) -> torch.device: """ Return the device of the model. """ return next(self.parameters()).device
def convert_to_fp16(self) -> None: """ Convert the torso of the model to float16. """ self.blocks.apply(convert_module_to_f16)
def convert_to_fp32(self) -> None: """ Convert the torso of the model to float32. """ self.blocks.apply(convert_module_to_f32)
def initialize_weights(self) -> None: # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: h = self.input_layer(x) if self.pe_mode == "ape": h = h + self.pos_embedder(x.coords[:, 1:]) h = h.type(self.dtype) for block in self.blocks: h = block(h) return happ.pyAdded+152
assets/example_image/T.pngAdded

assets/example_image/typical_building_building.pngAdded

assets/example_image/typical_building_castle.pngAdded

assets/example_image/typical_building_colorful_cottage.pngAdded

assets/example_image/typical_building_maya_pyramid.pngAdded

assets/example_image/typical_building_mushroom.pngAdded

assets/example_image/typical_building_space_station.pngAdded

assets/example_image/typical_creature_dragon.pngAdded

assets/example_image/typical_creature_elephant.pngAdded

assets/example_image/typical_creature_furry.pngAdded

assets/example_image/typical_creature_quadruped.pngAdded

assets/example_image/typical_creature_robot_crab.pngAdded

assets/example_image/typical_creature_robot_dinosour.pngAdded

assets/example_image/typical_creature_rock_monster.pngAdded

assets/example_image/typical_humanoid_block_robot.pngAdded

assets/example_image/typical_humanoid_dragonborn.pngAdded

assets/example_image/typical_humanoid_dwarf.pngAdded

assets/example_image/typical_humanoid_goblin.pngAdded

assets/example_image/typical_humanoid_mech.pngAdded

assets/example_image/typical_misc_crate.pngAdded

assets/example_image/typical_misc_fireplace.pngAdded

assets/example_image/typical_misc_gate.pngAdded

assets/example_image/typical_misc_lantern.pngAdded

assets/example_image/typical_misc_magicbook.pngAdded

assets/example_image/typical_misc_mailbox.pngAdded

assets/example_image/typical_misc_monster_chest.pngAdded

assets/example_image/typical_misc_paper_machine.pngAdded

assets/example_image/typical_misc_phonograph.pngAdded

assets/example_image/typical_misc_portal2.pngAdded

assets/example_image/typical_misc_storage_chest.pngAdded

assets/example_image/typical_misc_telephone.pngAdded

assets/example_image/typical_misc_television.pngAdded

assets/example_image/typical_misc_workbench.pngAdded

assets/example_image/typical_vehicle_biplane.pngAdded

assets/example_image/typical_vehicle_bulldozer.pngAdded

assets/example_image/typical_vehicle_cart.pngAdded

assets/example_image/typical_vehicle_excavator.pngAdded

assets/example_image/typical_vehicle_helicopter.pngAdded

assets/example_image/typical_vehicle_locomotive.pngAdded

assets/example_image/typical_vehicle_pirate_ship.pngAdded

assets/example_image/weatherworn_misc_paper_machine3.pngAdded

requirements.txtAdded+28
trellis/__init__.pyAdded+6
trellis/models/__init__.pyAdded+70
trellis/models/sparse_structure_flow.pyAdded+200
trellis/models/sparse_structure_vae.pyAdded+306
trellis/models/structured_latent_flow.pyAdded+262
trellis/models/structured_latent_vae/__init__.pyAdded+4
trellis/models/structured_latent_vae/base.pyAdded+117