Spaces:
Running on Zero
Running on Zero
Commit ·
388d03f
1
Parent(s): 917a889
update
Browse filesFiles changed (5)
18 unmodified lines1920212223242518 unmodified linesparts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg18 unmodified lines19202122232418 unmodified linesparts/sdist/var/share/python-wheels/*.egg-info/.installed.cfg
12345678---title: TRELLIS.2emoji: 🏢colorFrom: indigocolorTo: bluesdk: gradiosdk_version: 6.1.0app_file: app.py12345678---title: TRELLIS.2emoji: 🏢colorFrom: purplecolorTo: redsdk: gradiosdk_version: 6.1.0app_file: app.py
12 unmodified lines131415161718192012 unmodified linestransformers==4.46.3git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.3/flash_attn-2.7.3+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whlhttps://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/cumesh-0.0.1-cp310-cp310-linux_x86_64.whl?download=truehttps://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/flex_gemm-0.0.1-cp310-cp310-linux_x86_64.whl?download=truehttps://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/o_voxel-0.0.1-cp310-cp310-linux_x86_64.whl?download=truehttps://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/nvdiffrast-0.3.5-cp310-cp310-linux_x86_64?download=truehttps://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/nvdiffrec_render-0.0.0-cp310-cp310-linux_x86_64.whl?download=true12 unmodified lines1314151617181920212223242512 unmodified linestransformers==4.46.3git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.3/flash_attn-2.7.3+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whlhttps://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/cumesh-0.0.1-cp310-cp310-linux_x86_64.whlhttps://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/flex_gemm-0.0.1-cp310-cp310-linux_x86_64.whlhttps://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/o_voxel-0.0.1-cp310-cp310-linux_x86_64.whlhttps://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/nvdiffrast-0.3.5-cp310-cp310-linux_x86_64.whlhttps://github.com/JeffreyXiang/Storages/releases/download/Space_Wheels_251210/nvdiffrec_render-0.0.0-cp310-cp310-linux_x86_64.whl# https://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/cumesh-0.0.1-cp310-cp310-linux_x86_64.whl?download=true# https://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/flex_gemm-0.0.1-cp310-cp310-linux_x86_64.whl?download=true# https://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/o_voxel-0.0.1-cp310-cp310-linux_x86_64.whl?download=true# https://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/nvdiffrast-0.3.5-cp310-cp310-linux_x86_64?download=true# https://huggingface.co/spaces/JeffreyXiang/TRELLIS.2/resolve/main/wheels/nvdiffrec_render-0.0.0-cp310-cp310-linux_x86_64.whl?download=true
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118from typing import *import torchimport torch.nn.functional as Ffrom torchvision import transformsfrom transformers import DINOv3ViTModelimport numpy as npfrom PIL import Image
class DinoV2FeatureExtractor: """ Feature extractor for DINOv2 models. """ def __init__(self, model_name: str): self.model_name = model_name self.model = torch.hub.load('facebookresearch/dinov2', model_name, pretrained=True) self.model.eval() self.transform = transforms.Compose([ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ])
def to(self, device): self.model.to(device)
def cuda(self): self.model.cuda()
def cpu(self): self.model.cpu() @torch.no_grad() def __call__(self, image: Union[torch.Tensor, List[Image.Image]]) -> torch.Tensor: """ Extract features from the image. Args: image: A batch of images as a tensor of shape (B, C, H, W) or a list of PIL images. Returns: A tensor of shape (B, N, D) where N is the number of patches and D is the feature dimension. """ if isinstance(image, torch.Tensor): assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)" elif isinstance(image, list): assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images" image = [i.resize((518, 518), Image.LANCZOS) for i in image] image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image] image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image] image = torch.stack(image).cuda() else: raise ValueError(f"Unsupported type of image: {type(image)}") image = self.transform(image).cuda() features = self.model(image, is_training=True)['x_prenorm'] patchtokens = F.layer_norm(features, features.shape[-1:]) return patchtokens
class DinoV3FeatureExtractor: """ Feature extractor for DINOv3 models. """ def __init__(self, model_name: str, image_size=512): self.model_name = model_name self.model = DINOv3ViTModel.from_pretrained(model_name) self.model.eval() self.image_size = image_size self.transform = transforms.Compose([ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ])
def to(self, device): self.model.to(device)
def cuda(self): self.model.cuda()
def cpu(self): self.model.cpu()
def extract_features(self, image: torch.Tensor) -> torch.Tensor: image = image.to(self.model.embeddings.patch_embeddings.weight.dtype) hidden_states = self.model.embeddings(image, bool_masked_pos=None) position_embeddings = self.model.rope_embeddings(image)
for i, layer_module in enumerate(self.model.layer): hidden_states = layer_module( hidden_states, position_embeddings=position_embeddings, )
return F.layer_norm(hidden_states, hidden_states.shape[-1:]) @torch.no_grad() def __call__(self, image: Union[torch.Tensor, List[Image.Image]]) -> torch.Tensor: """ Extract features from the image. Args: image: A batch of images as a tensor of shape (B, C, H, W) or a list of PIL images. Returns: A tensor of shape (B, N, D) where N is the number of patches and D is the feature dimension. """ if isinstance(image, torch.Tensor): assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)" elif isinstance(image, list): assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images" image = [i.resize((self.image_size, self.image_size), Image.LANCZOS) for i in image] image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image] image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image] image = torch.stack(image).cuda() else: raise ValueError(f"Unsupported type of image: {type(image)}") image = self.transform(image).cuda() features = self.extract_features(image) return features4 unmodified lines5678910111211 unmodified lines2425262728293061 unmodified lines92939495969798131 unmodified lines2302312322332342352363 unmodified lines24024124224324424524628 unmodified lines2752762772782792802813 unmodified lines28528628728828929029137 unmodified lines32933033133233333433519 unmodified lines3553563573583593603613623633643653663673683693703713723739 unmodified lines38338438538638738838939039139239339439539639726 unmodified lines4244254264274284294304314324334344354364374384394404415 unmodified lines4474484494504514524534544554564574584594604614624 unmodified linesfrom PIL import Imagefrom .base import Pipelinefrom . import samplers, rembgfrom .. import trainersfrom ..modules import sparse as spfrom ..representations import Mesh, MeshWithVoxel11 unmodified linestex_slat_sampler_params (dict): The parameters for the texture latent sampler.shape_slat_normalization (dict): The normalization parameters for the structured latent.tex_slat_normalization (dict): The normalization parameters for the texture latent.image_cond_model (trainers.Trainer): The image conditioning model.rembg_model (Callable): The model for removing background.low_vram (bool): Whether to use low-VRAM mode."""61 unmodified linesnew_pipeline.shape_slat_normalization = args['shape_slat_normalization']new_pipeline.tex_slat_normalization = args['tex_slat_normalization']new_pipeline.image_cond_model = getattr(trainers, args['image_cond_model']['name'])(**args['image_cond_model']['args'])new_pipeline.rembg_model = getattr(rembg, args['rembg_model']['name'])(**args['rembg_model']['args'])new_pipeline.low_vram = args.get('low_vram', True)131 unmodified linesflow_model,coords: torch.Tensor,sampler_params: dict = {},) -> sp.SparseTensor:"""Sample structured latent with the given conditioning.3 unmodified linessampler_params (dict): Additional parameters for the sampler."""# Sample structured latentnoise = sp.SparseTensor(feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device),coords=coords,)28 unmodified linescoords: torch.Tensor,sampler_params: dict = {},max_num_tokens: int = 49152,) -> sp.SparseTensor:"""Sample structured latent with the given conditioning.3 unmodified linessampler_params (dict): Additional parameters for the sampler."""# LRnoise = sp.SparseTensor(feats=torch.randn(coords.shape[0], flow_model_lr.in_channels).to(self.device),coords=coords,)37 unmodified lineshr_resolution -= 128# Sample structured latentnoise = sp.SparseTensor(feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device),coords=coords,)19 unmodified linesdef decode_shape_slat(self,slat: sp.SparseTensor,resolution: int,) -> Tuple[List[Mesh], List[sp.SparseTensor]]:"""Decode the structured latent.Args:slat (sp.SparseTensor): The structured latent.formats (List[str]): The formats to decode the structured latent to.Returns:List[Mesh]: The decoded meshes.List[sp.SparseTensor]: The decoded substructures."""self.models['shape_slat_decoder'].set_resolution(resolution)if self.low_vram:9 unmodified linesself,cond: dict,flow_model,shape_slat: sp.SparseTensor,sampler_params: dict = {},) -> sp.SparseTensor:"""Sample structured latent with the given conditioning.Args:cond (dict): The conditioning information.shape_slat (sp.SparseTensor): The structured latent for shapesampler_params (dict): Additional parameters for the sampler."""# Sample structured latent26 unmodified linesdef decode_tex_slat(self,slat: sp.SparseTensor,subs: List[sp.SparseTensor],) -> sp.SparseTensor:"""Decode the structured latent.Args:slat (sp.SparseTensor): The structured latent.formats (List[str]): The formats to decode the structured latent to.Returns:List[sp.SparseTensor]: The decoded texture voxels"""if self.low_vram:self.models['tex_slat_decoder'].to(self.device)5 unmodified lines@torch.no_grad()def decode_latent(self,shape_slat: sp.SparseTensor,tex_slat: sp.SparseTensor,resolution: int,) -> List[MeshWithVoxel]:"""Decode the latent codes.Args:shape_slat (sp.SparseTensor): The structured latent for shape.tex_slat (sp.SparseTensor): The structured latent for texture.resolution (int): The resolution of the output."""meshes, subs = self.decode_shape_slat(shape_slat, resolution)4 unmodified lines5678910111211 unmodified lines2425262728293061 unmodified lines92939495969798131 unmodified lines2302312322332342352363 unmodified lines24024124224324424524628 unmodified lines2752762772782792802813 unmodified lines28528628728828929029137 unmodified lines32933033133233333433519 unmodified lines3553563573583593603613623633643653663673683693703713723739 unmodified lines38338438538638738838939039139239339439539639726 unmodified lines4244254264274284294304314324334344354364374384394404415 unmodified lines4474484494504514524534544554564574584594604614624 unmodified linesfrom PIL import Imagefrom .base import Pipelinefrom . import samplers, rembgfrom ..modules.sparse import SparseTensorfrom ..modules import image_feature_extractorfrom ..representations import Mesh, MeshWithVoxel11 unmodified linestex_slat_sampler_params (dict): The parameters for the texture latent sampler.shape_slat_normalization (dict): The normalization parameters for the structured latent.tex_slat_normalization (dict): The normalization parameters for the texture latent.image_cond_model (Callable): The image conditioning model.rembg_model (Callable): The model for removing background.low_vram (bool): Whether to use low-VRAM mode."""61 unmodified linesnew_pipeline.shape_slat_normalization = args['shape_slat_normalization']new_pipeline.tex_slat_normalization = args['tex_slat_normalization']new_pipeline.image_cond_model = getattr(image_feature_extractor, args['image_cond_model']['name'])(**args['image_cond_model']['args'])new_pipeline.rembg_model = getattr(rembg, args['rembg_model']['name'])(**args['rembg_model']['args'])new_pipeline.low_vram = args.get('low_vram', True)131 unmodified linesflow_model,coords: torch.Tensor,sampler_params: dict = {},) -> SparseTensor:"""Sample structured latent with the given conditioning.3 unmodified linessampler_params (dict): Additional parameters for the sampler."""# Sample structured latentnoise = SparseTensor(feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device),coords=coords,)28 unmodified linescoords: torch.Tensor,sampler_params: dict = {},max_num_tokens: int = 49152,) -> SparseTensor:"""Sample structured latent with the given conditioning.3 unmodified linessampler_params (dict): Additional parameters for the sampler."""# LRnoise = SparseTensor(feats=torch.randn(coords.shape[0], flow_model_lr.in_channels).to(self.device),coords=coords,)37 unmodified lineshr_resolution -= 128# Sample structured latentnoise = SparseTensor(feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device),coords=coords,)19 unmodified linesdef decode_shape_slat(self,slat: SparseTensor,resolution: int,) -> Tuple[List[Mesh], List[SparseTensor]]:"""Decode the structured latent.Args:slat (SparseTensor): The structured latent.formats (List[str]): The formats to decode the structured latent to.Returns:List[Mesh]: The decoded meshes.List[SparseTensor]: The decoded substructures."""self.models['shape_slat_decoder'].set_resolution(resolution)if self.low_vram:9 unmodified linesself,cond: dict,flow_model,shape_slat: SparseTensor,sampler_params: dict = {},) -> SparseTensor:"""Sample structured latent with the given conditioning.Args:cond (dict): The conditioning information.shape_slat (SparseTensor): The structured latent for shapesampler_params (dict): Additional parameters for the sampler."""# Sample structured latent26 unmodified linesdef decode_tex_slat(self,slat: SparseTensor,subs: List[SparseTensor],) -> SparseTensor:"""Decode the structured latent.Args:slat (SparseTensor): The structured latent.formats (List[str]): The formats to decode the structured latent to.Returns:List[SparseTensor]: The decoded texture voxels"""if self.low_vram:self.models['tex_slat_decoder'].to(self.device)5 unmodified lines@torch.no_grad()def decode_latent(self,shape_slat: SparseTensor,tex_slat: SparseTensor,resolution: int,) -> List[MeshWithVoxel]:"""Decode the latent codes.Args:shape_slat (SparseTensor): The structured latent for shape.tex_slat (SparseTensor): The structured latent for texture.resolution (int): The resolution of the output."""meshes, subs = self.decode_shape_slat(shape_slat, resolution)
.gitignore-1
README.md+2-2
requirements.txt+10-5
trellis2/modules/image_feature_extractor.pyAdded+118
trellis2/pipelines/trellis2_image_to_3d.py+25-25