diff --git a/.gitattributes b/.gitattributes index a4864ac6c8558162f9a7fd5a44b02e127dad0d08..1452b4c4965493f0b4d65c4fb64091fa74dfef54 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3985,3 +3985,11 @@ PSIVG/PSIVG/data_root/OUT_Simulation/0000/2026-10-31_run/point_cloud/00194.ply f PSIVG/PSIVG/data_root/OUT_Simulation/0000/2026-10-31_run/point_cloud/00195.ply filter=lfs diff=lfs merge=lfs -text PSIVG/PSIVG/psivg/perception/vipe/vipe_ext.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text OVOW/engine/oneposeviagen/SAM2-in-video/sam2/_C.so filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/city.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/courtyard.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/forest.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/interior.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/_C.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/PKG-INFO b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..5dcd457cd7fffa38b5ff72b71c90cc222c958131 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/PKG-INFO @@ -0,0 +1,5 @@ +Metadata-Version: 2.4 +Name: models +Version: 0.1 +License-File: LICENSE.txt +Dynamic: license-file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/SOURCES.txt b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..c045bf0468575c2f877ceaa920f016b4c9664138 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/SOURCES.txt @@ -0,0 +1,7 @@ +LICENSE.txt +README.md +setup.py +models.egg-info/PKG-INFO +models.egg-info/SOURCES.txt +models.egg-info/dependency_links.txt +models.egg-info/top_level.txt \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/dependency_links.txt b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/top_level.txt b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/top_level.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/depth_pro.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/depth_pro.py new file mode 100644 index 0000000000000000000000000000000000000000..f31b4e16178c5e29a3ffcd1a2366fe585bc9c370 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/depth_pro.py @@ -0,0 +1,298 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. +# Depth Pro: Sharp Monocular Metric Depth in Less Than a Second + + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Mapping, Optional, Tuple, Union + +import torch +from torch import nn +from torchvision.transforms import ( + Compose, + ConvertImageDtype, + Lambda, + Normalize, + ToTensor, +) + +from .network.decoder import MultiresConvDecoder +from .network.encoder import DepthProEncoder +from .network.fov import FOVNetwork +from .network.vit_factory import VIT_CONFIG_DICT, ViTPreset, create_vit + + +@dataclass +class DepthProConfig: + """Configuration for DepthPro.""" + + patch_encoder_preset: ViTPreset + image_encoder_preset: ViTPreset + decoder_features: int + + checkpoint_uri: Optional[str] = None + fov_encoder_preset: Optional[ViTPreset] = None + use_fov_head: bool = True + + +DEFAULT_MONODEPTH_CONFIG_DICT = DepthProConfig( + patch_encoder_preset="dinov2l16_384", + image_encoder_preset="dinov2l16_384", + checkpoint_uri="./checkpoints/depth_pro.pt", + decoder_features=256, + use_fov_head=True, + fov_encoder_preset="dinov2l16_384", +) + + +def create_backbone_model( + preset: ViTPreset +) -> Tuple[nn.Module, ViTPreset]: + """Create and load a backbone model given a config. + + Args: + ---- + preset: A backbone preset to load pre-defind configs. + + Returns: + ------- + A Torch module and the associated config. + + """ + if preset in VIT_CONFIG_DICT: + config = VIT_CONFIG_DICT[preset] + model = create_vit(preset=preset, use_pretrained=False) + else: + raise KeyError(f"Preset {preset} not found.") + + return model, config + + +def create_model_and_transforms( + config: DepthProConfig = DEFAULT_MONODEPTH_CONFIG_DICT, + device: torch.device = torch.device("cpu"), + precision: torch.dtype = torch.float32, +) -> Tuple[DepthPro, Compose]: + """Create a DepthPro model and load weights from `config.checkpoint_uri`. + + Args: + ---- + config: The configuration for the DPT model architecture. + device: The optional Torch device to load the model onto, default runs on "cpu". + precision: The optional precision used for the model, default is FP32. + + Returns: + ------- + The Torch DepthPro model and associated Transform. + + """ + patch_encoder, patch_encoder_config = create_backbone_model( + preset=config.patch_encoder_preset + ) + image_encoder, _ = create_backbone_model( + preset=config.image_encoder_preset + ) + + fov_encoder = None + if config.use_fov_head and config.fov_encoder_preset is not None: + fov_encoder, _ = create_backbone_model(preset=config.fov_encoder_preset) + + dims_encoder = patch_encoder_config.encoder_feature_dims + hook_block_ids = patch_encoder_config.encoder_feature_layer_ids + encoder = DepthProEncoder( + dims_encoder=dims_encoder, + patch_encoder=patch_encoder, + image_encoder=image_encoder, + hook_block_ids=hook_block_ids, + decoder_features=config.decoder_features, + ) + decoder = MultiresConvDecoder( + dims_encoder=[config.decoder_features] + list(encoder.dims_encoder), + dim_decoder=config.decoder_features, + ) + model = DepthPro( + encoder=encoder, + decoder=decoder, + last_dims=(32, 1), + use_fov_head=config.use_fov_head, + fov_encoder=fov_encoder, + ).to(device) + + if precision == torch.half: + model.half() + + transform = Compose( + [ + ToTensor(), + Lambda(lambda x: x.to(device)), + Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), + ConvertImageDtype(precision), + ] + ) + + if config.checkpoint_uri is not None: + state_dict = torch.load(config.checkpoint_uri, map_location="cpu") + missing_keys, unexpected_keys = model.load_state_dict( + state_dict=state_dict, strict=True + ) + + if len(unexpected_keys) != 0: + raise KeyError( + f"Found unexpected keys when loading monodepth: {unexpected_keys}" + ) + + # fc_norm is only for the classification head, + # which we would not use. We only use the encoding. + missing_keys = [key for key in missing_keys if "fc_norm" not in key] + if len(missing_keys) != 0: + raise KeyError(f"Keys are missing when loading monodepth: {missing_keys}") + + return model, transform + + +class DepthPro(nn.Module): + """DepthPro network.""" + + def __init__( + self, + encoder: DepthProEncoder, + decoder: MultiresConvDecoder, + last_dims: tuple[int, int], + use_fov_head: bool = True, + fov_encoder: Optional[nn.Module] = None, + ): + """Initialize DepthPro. + + Args: + ---- + encoder: The DepthProEncoder backbone. + decoder: The MultiresConvDecoder decoder. + last_dims: The dimension for the last convolution layers. + use_fov_head: Whether to use the field-of-view head. + fov_encoder: A separate encoder for the field of view. + + """ + super().__init__() + + self.encoder = encoder + self.decoder = decoder + + dim_decoder = decoder.dim_decoder + self.head = nn.Sequential( + nn.Conv2d( + dim_decoder, dim_decoder // 2, kernel_size=3, stride=1, padding=1 + ), + nn.ConvTranspose2d( + in_channels=dim_decoder // 2, + out_channels=dim_decoder // 2, + kernel_size=2, + stride=2, + padding=0, + bias=True, + ), + nn.Conv2d( + dim_decoder // 2, + last_dims[0], + kernel_size=3, + stride=1, + padding=1, + ), + nn.ReLU(True), + nn.Conv2d(last_dims[0], last_dims[1], kernel_size=1, stride=1, padding=0), + nn.ReLU(), + ) + + # Set the final convolution layer's bias to be 0. + self.head[4].bias.data.fill_(0) + + # Set the FOV estimation head. + if use_fov_head: + self.fov = FOVNetwork(num_features=dim_decoder, fov_encoder=fov_encoder) + + @property + def img_size(self) -> int: + """Return the internal image size of the network.""" + return self.encoder.img_size + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """Decode by projection and fusion of multi-resolution encodings. + + Args: + ---- + x (torch.Tensor): Input image. + + Returns: + ------- + The canonical inverse depth map [m] and the optional estimated field of view [deg]. + + """ + _, _, H, W = x.shape + assert H == self.img_size and W == self.img_size + + encodings = self.encoder(x) + features, features_0 = self.decoder(encodings) + canonical_inverse_depth = self.head(features) + + fov_deg = None + if hasattr(self, "fov"): + fov_deg = self.fov.forward(x, features_0.detach()) + + return canonical_inverse_depth, fov_deg + + @torch.no_grad() + def infer( + self, + x: torch.Tensor, + f_px: Optional[Union[float, torch.Tensor]] = None, + interpolation_mode="bilinear", + ) -> Mapping[str, torch.Tensor]: + """Infer depth and fov for a given image. + + If the image is not at network resolution, it is resized to 1536x1536 and + the estimated depth is resized to the original image resolution. + Note: if the focal length is given, the estimated value is ignored and the provided + focal length is use to generate the metric depth values. + + Args: + ---- + x (torch.Tensor): Input image + f_px (torch.Tensor): Optional focal length in pixels corresponding to `x`. + interpolation_mode (str): Interpolation function for downsampling/upsampling. + + Returns: + ------- + Tensor dictionary (torch.Tensor): depth [m], focallength [pixels]. + + """ + if len(x.shape) == 3: + x = x.unsqueeze(0) + _, _, H, W = x.shape + resize = H != self.img_size or W != self.img_size + + if resize: + x = nn.functional.interpolate( + x, + size=(self.img_size, self.img_size), + mode=interpolation_mode, + align_corners=False, + ) + + canonical_inverse_depth, fov_deg = self.forward(x) + if f_px is None: + f_px = 0.5 * W / torch.tan(0.5 * torch.deg2rad(fov_deg.to(torch.float))) + + inverse_depth = canonical_inverse_depth * (W / f_px) + f_px = f_px.squeeze() + + if resize: + inverse_depth = nn.functional.interpolate( + inverse_depth, size=(H, W), mode=interpolation_mode, align_corners=False + ) + + depth = 1.0 / torch.clamp(inverse_depth, min=1e-4, max=1e4) + + return { + "depth": depth.squeeze(), + "focallength_px": f_px, + } diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/boundary_metrics.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/boundary_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..d7650dbb60b990ed66b4444a1bbb7f7eaaed1390 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/boundary_metrics.py @@ -0,0 +1,332 @@ +from typing import List, Tuple + +import numpy as np + + +def connected_component(r: np.ndarray, c: np.ndarray) -> List[List[int]]: + """Find connected components in the given row and column indices. + + Args: + ---- + r (np.ndarray): Row indices. + c (np.ndarray): Column indices. + + Yields: + ------ + List[int]: Indices of connected components. + + """ + indices = [0] + for i in range(1, r.size): + if r[i] == r[indices[-1]] and c[i] == c[indices[-1]] + 1: + indices.append(i) + else: + yield indices + indices = [i] + yield indices + + +def nms_horizontal(ratio: np.ndarray, threshold: float) -> np.ndarray: + """Apply Non-Maximum Suppression (NMS) horizontally on the given ratio matrix. + + Args: + ---- + ratio (np.ndarray): Input ratio matrix. + threshold (float): Threshold for NMS. + + Returns: + ------- + np.ndarray: Binary mask after applying NMS. + + """ + mask = np.zeros_like(ratio, dtype=bool) + r, c = np.nonzero(ratio > threshold) + if len(r) == 0: + return mask + for ids in connected_component(r, c): + values = [ratio[r[i], c[i]] for i in ids] + mi = np.argmax(values) + mask[r[ids[mi]], c[ids[mi]]] = True + return mask + + +def nms_vertical(ratio: np.ndarray, threshold: float) -> np.ndarray: + """Apply Non-Maximum Suppression (NMS) vertically on the given ratio matrix. + + Args: + ---- + ratio (np.ndarray): Input ratio matrix. + threshold (float): Threshold for NMS. + + Returns: + ------- + np.ndarray: Binary mask after applying NMS. + + """ + return np.transpose(nms_horizontal(np.transpose(ratio), threshold)) + + +def fgbg_depth( + d: np.ndarray, t: float +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Find foreground-background relations between neighboring pixels. + + Args: + ---- + d (np.ndarray): Depth matrix. + t (float): Threshold for comparison. + + Returns: + ------- + Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating + left, top, right, and bottom foreground-background relations. + + """ + right_is_big_enough = (d[..., :, 1:] / d[..., :, :-1]) > t + left_is_big_enough = (d[..., :, :-1] / d[..., :, 1:]) > t + bottom_is_big_enough = (d[..., 1:, :] / d[..., :-1, :]) > t + top_is_big_enough = (d[..., :-1, :] / d[..., 1:, :]) > t + return ( + left_is_big_enough, + top_is_big_enough, + right_is_big_enough, + bottom_is_big_enough, + ) + + +def fgbg_depth_thinned( + d: np.ndarray, t: float +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Find foreground-background relations between neighboring pixels with Non-Maximum Suppression. + + Args: + ---- + d (np.ndarray): Depth matrix. + t (float): Threshold for NMS. + + Returns: + ------- + Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating + left, top, right, and bottom foreground-background relations with NMS applied. + + """ + right_is_big_enough = nms_horizontal(d[..., :, 1:] / d[..., :, :-1], t) + left_is_big_enough = nms_horizontal(d[..., :, :-1] / d[..., :, 1:], t) + bottom_is_big_enough = nms_vertical(d[..., 1:, :] / d[..., :-1, :], t) + top_is_big_enough = nms_vertical(d[..., :-1, :] / d[..., 1:, :], t) + return ( + left_is_big_enough, + top_is_big_enough, + right_is_big_enough, + bottom_is_big_enough, + ) + + +def fgbg_binary_mask( + d: np.ndarray, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Find foreground-background relations between neighboring pixels in binary masks. + + Args: + ---- + d (np.ndarray): Binary depth matrix. + + Returns: + ------- + Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating + left, top, right, and bottom foreground-background relations in binary masks. + + """ + assert d.dtype == bool + right_is_big_enough = d[..., :, 1:] & ~d[..., :, :-1] + left_is_big_enough = d[..., :, :-1] & ~d[..., :, 1:] + bottom_is_big_enough = d[..., 1:, :] & ~d[..., :-1, :] + top_is_big_enough = d[..., :-1, :] & ~d[..., 1:, :] + return ( + left_is_big_enough, + top_is_big_enough, + right_is_big_enough, + bottom_is_big_enough, + ) + + +def edge_recall_matting(pr: np.ndarray, gt: np.ndarray, t: float) -> float: + """Calculate edge recall for image matting. + + Args: + ---- + pr (np.ndarray): Predicted depth matrix. + gt (np.ndarray): Ground truth binary mask. + t (float): Threshold for NMS. + + Returns: + ------- + float: Edge recall value. + + """ + assert gt.dtype == bool + ap, bp, cp, dp = fgbg_depth_thinned(pr, t) + ag, bg, cg, dg = fgbg_binary_mask(gt) + return 0.25 * ( + np.count_nonzero(ap & ag) / max(np.count_nonzero(ag), 1) + + np.count_nonzero(bp & bg) / max(np.count_nonzero(bg), 1) + + np.count_nonzero(cp & cg) / max(np.count_nonzero(cg), 1) + + np.count_nonzero(dp & dg) / max(np.count_nonzero(dg), 1) + ) + + +def boundary_f1( + pr: np.ndarray, + gt: np.ndarray, + t: float, + return_p: bool = False, + return_r: bool = False, +) -> float: + """Calculate Boundary F1 score. + + Args: + ---- + pr (np.ndarray): Predicted depth matrix. + gt (np.ndarray): Ground truth depth matrix. + t (float): Threshold for comparison. + return_p (bool, optional): If True, return precision. Defaults to False. + return_r (bool, optional): If True, return recall. Defaults to False. + + Returns: + ------- + float: Boundary F1 score, or precision, or recall depending on the flags. + + """ + ap, bp, cp, dp = fgbg_depth(pr, t) + ag, bg, cg, dg = fgbg_depth(gt, t) + + r = 0.25 * ( + np.count_nonzero(ap & ag) / max(np.count_nonzero(ag), 1) + + np.count_nonzero(bp & bg) / max(np.count_nonzero(bg), 1) + + np.count_nonzero(cp & cg) / max(np.count_nonzero(cg), 1) + + np.count_nonzero(dp & dg) / max(np.count_nonzero(dg), 1) + ) + p = 0.25 * ( + np.count_nonzero(ap & ag) / max(np.count_nonzero(ap), 1) + + np.count_nonzero(bp & bg) / max(np.count_nonzero(bp), 1) + + np.count_nonzero(cp & cg) / max(np.count_nonzero(cp), 1) + + np.count_nonzero(dp & dg) / max(np.count_nonzero(dp), 1) + ) + if r + p == 0: + return 0.0 + if return_p: + return p + if return_r: + return r + return 2 * (r * p) / (r + p) + + +def get_thresholds_and_weights( + t_min: float, t_max: float, N: int +) -> Tuple[np.ndarray, np.ndarray]: + """Generate thresholds and weights for the given range. + + Args: + ---- + t_min (float): Minimum threshold. + t_max (float): Maximum threshold. + N (int): Number of thresholds. + + Returns: + ------- + Tuple[np.ndarray, np.ndarray]: Array of thresholds and corresponding weights. + + """ + thresholds = np.linspace(t_min, t_max, N) + weights = thresholds / thresholds.sum() + return thresholds, weights + + +def invert_depth(depth: np.ndarray, eps: float = 1e-6) -> np.ndarray: + """Inverts a depth map with numerical stability. + + Args: + ---- + depth (np.ndarray): Depth map to be inverted. + eps (float): Minimum value to avoid division by zero (default is 1e-6). + + Returns: + ------- + np.ndarray: Inverted depth map. + + """ + inverse_depth = 1.0 / depth.clip(min=eps) + return inverse_depth + + +def SI_boundary_F1( + predicted_depth: np.ndarray, + target_depth: np.ndarray, + t_min: float = 1.05, + t_max: float = 1.25, + N: int = 10, +) -> float: + """Calculate Scale-Invariant Boundary F1 Score for depth-based ground-truth. + + Args: + ---- + predicted_depth (np.ndarray): Predicted depth matrix. + target_depth (np.ndarray): Ground truth depth matrix. + t_min (float, optional): Minimum threshold. Defaults to 1.05. + t_max (float, optional): Maximum threshold. Defaults to 1.25. + N (int, optional): Number of thresholds. Defaults to 10. + + Returns: + ------- + float: Scale-Invariant Boundary F1 Score. + + """ + assert predicted_depth.ndim == target_depth.ndim == 2 + thresholds, weights = get_thresholds_and_weights(t_min, t_max, N) + f1_scores = np.array( + [ + boundary_f1(invert_depth(predicted_depth), invert_depth(target_depth), t) + for t in thresholds + ] + ) + return np.sum(f1_scores * weights) + + +def SI_boundary_Recall( + predicted_depth: np.ndarray, + target_mask: np.ndarray, + t_min: float = 1.05, + t_max: float = 1.25, + N: int = 10, + alpha_threshold: float = 0.1, +) -> float: + """Calculate Scale-Invariant Boundary Recall Score for mask-based ground-truth. + + Args: + ---- + predicted_depth (np.ndarray): Predicted depth matrix. + target_mask (np.ndarray): Ground truth binary mask. + t_min (float, optional): Minimum threshold. Defaults to 1.05. + t_max (float, optional): Maximum threshold. Defaults to 1.25. + N (int, optional): Number of thresholds. Defaults to 10. + alpha_threshold (float, optional): Threshold for alpha masking. Defaults to 0.1. + + Returns: + ------- + float: Scale-Invariant Boundary Recall Score. + + """ + assert predicted_depth.ndim == target_mask.ndim == 2 + thresholds, weights = get_thresholds_and_weights(t_min, t_max, N) + thresholded_target = target_mask > alpha_threshold + + recall_scores = np.array( + [ + edge_recall_matting( + invert_depth(predicted_depth), thresholded_target, t=float(t) + ) + for t in thresholds + ] + ) + weighted_recall = np.sum(recall_scores * weights) + return weighted_recall diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/dis5k_sample_list.txt b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/dis5k_sample_list.txt new file mode 100644 index 0000000000000000000000000000000000000000..81da1dcdb786da7bbec861604f50d4f039f695ef --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/dis5k_sample_list.txt @@ -0,0 +1,200 @@ +DIS5K/DIS-TE1/im/12#Graphics#4#TrafficSign#8245751856_821be14f86_o.jpg +DIS5K/DIS-TE1/im/13#Insect#4#Butterfly#16023994688_7ff8cdccb1_o.jpg +DIS5K/DIS-TE1/im/14#Kitchenware#4#Kitchenware#IMG_20210520_205538.jpg +DIS5K/DIS-TE1/im/14#Kitchenware#8#SweetStand#4848284981_fc90f54b50_o.jpg +DIS5K/DIS-TE1/im/17#Non-motor Vehicle#4#Cart#15012855035_d10b57014f_o.jpg +DIS5K/DIS-TE1/im/2#Aircraft#5#Kite#13104545564_5afceec9bd_o.jpg +DIS5K/DIS-TE1/im/20#Sports#10#Skateboarding#8472763540_bb2390e928_o.jpg +DIS5K/DIS-TE1/im/21#Tool#14#Sword#32473146960_dcc6b77848_o.jpg +DIS5K/DIS-TE1/im/21#Tool#15#Tapeline#9680492386_2d2020f282_o.jpg +DIS5K/DIS-TE1/im/21#Tool#4#Flag#507752845_ef852100f0_o.jpg +DIS5K/DIS-TE1/im/21#Tool#6#Key#11966089533_3becd78b44_o.jpg +DIS5K/DIS-TE1/im/21#Tool#8#Scale#31946428472_d28def471b_o.jpg +DIS5K/DIS-TE1/im/22#Weapon#4#Rifle#8472656430_3eb908b211_o.jpg +DIS5K/DIS-TE1/im/8#Electronics#3#Earphone#1177468301_641df8c267_o.jpg +DIS5K/DIS-TE1/im/8#Electronics#9#MusicPlayer#2235782872_7d47847bb4_o.jpg +DIS5K/DIS-TE2/im/11#Furniture#13#Ladder#3878434417_2ed740586e_o.jpg +DIS5K/DIS-TE2/im/13#Insect#1#Ant#27047700955_3b3a1271f8_o.jpg +DIS5K/DIS-TE2/im/13#Insect#11#Spider#5567179191_38d1f65589_o.jpg +DIS5K/DIS-TE2/im/13#Insect#8#Locust#5237933769_e6687c05e4_o.jpg +DIS5K/DIS-TE2/im/14#Kitchenware#2#DishRack#70838854_40cf689da7_o.jpg +DIS5K/DIS-TE2/im/14#Kitchenware#8#SweetStand#8467929412_fef7f4275d_o.jpg +DIS5K/DIS-TE2/im/16#Music Instrument#2#Harp#28058219806_28e05ff24a_o.jpg +DIS5K/DIS-TE2/im/17#Non-motor Vehicle#1#BabyCarriage#29794777180_2e1695a0cf_o.jpg +DIS5K/DIS-TE2/im/19#Ship#3#Sailboat#22442908623_5977e3becf_o.jpg +DIS5K/DIS-TE2/im/2#Aircraft#5#Kite#44654358051_1400e71cc4_o.jpg +DIS5K/DIS-TE2/im/21#Tool#11#Stand#IMG_20210520_205442.jpg +DIS5K/DIS-TE2/im/21#Tool#17#Tripod#9318977876_34615ec9a0_o.jpg +DIS5K/DIS-TE2/im/5#Artifact#3#Handcraft#50860882577_8482143b1b_o.jpg +DIS5K/DIS-TE2/im/8#Electronics#10#Robot#3093360210_fee54dc5c5_o.jpg +DIS5K/DIS-TE2/im/8#Electronics#6#Microphone#47411477652_6da66cbc10_o.jpg +DIS5K/DIS-TE3/im/14#Kitchenware#4#Kitchenware#2451122898_ef883175dd_o.jpg +DIS5K/DIS-TE3/im/15#Machine#4#SewingMachine#9311164128_97ba1d3947_o.jpg +DIS5K/DIS-TE3/im/16#Music Instrument#2#Harp#7670920550_59e992fd7b_o.jpg +DIS5K/DIS-TE3/im/17#Non-motor Vehicle#1#BabyCarriage#8389984877_1fddf8715c_o.jpg +DIS5K/DIS-TE3/im/17#Non-motor Vehicle#3#Carriage#5947122724_98e0fc3d1f_o.jpg +DIS5K/DIS-TE3/im/2#Aircraft#2#Balloon#2487168092_641505883f_o.jpg +DIS5K/DIS-TE3/im/2#Aircraft#4#Helicopter#8401177591_06c71c8df2_o.jpg +DIS5K/DIS-TE3/im/20#Sports#1#Archery#12520003103_faa43ea3e0_o.jpg +DIS5K/DIS-TE3/im/21#Tool#11#Stand#IMG_20210709_221507.jpg +DIS5K/DIS-TE3/im/21#Tool#2#Clip#5656649687_63d0c6696d_o.jpg +DIS5K/DIS-TE3/im/21#Tool#6#Key#12878459244_6387a140ea_o.jpg +DIS5K/DIS-TE3/im/3#Aquatic#1#Lobster#109214461_f52b4b6093_o.jpg +DIS5K/DIS-TE3/im/4#Architecture#19#Windmill#20195851863_2627117e0e_o.jpg +DIS5K/DIS-TE3/im/5#Artifact#2#Cage#5821476369_ea23927487_o.jpg +DIS5K/DIS-TE3/im/8#Electronics#7#MobileHolder#49732997896_7f53c290b5_o.jpg +DIS5K/DIS-TE4/im/13#Insect#6#Centipede#15302179708_a267850881_o.jpg +DIS5K/DIS-TE4/im/17#Non-motor Vehicle#11#Tricycle#5771069105_a3aef6f665_o.jpg +DIS5K/DIS-TE4/im/17#Non-motor Vehicle#2#Bicycle#4245936196_fdf812dcb7_o.jpg +DIS5K/DIS-TE4/im/17#Non-motor Vehicle#9#ShoppingCart#4674052920_a5b7a2b236_o.jpg +DIS5K/DIS-TE4/im/18#Plant#1#Bonsai#3539420884_ca8973e2c0_o.jpg +DIS5K/DIS-TE4/im/2#Aircraft#6#Parachute#33590416634_9d6f2325e7_o.jpg +DIS5K/DIS-TE4/im/20#Sports#1#Archery#46924476515_0be1caa684_o.jpg +DIS5K/DIS-TE4/im/20#Sports#8#Racket#19337607166_dd1985fb59_o.jpg +DIS5K/DIS-TE4/im/21#Tool#6#Key#3193329588_839b0c74ce_o.jpg +DIS5K/DIS-TE4/im/5#Artifact#2#Cage#5821886526_0573ba2d0d_o.jpg +DIS5K/DIS-TE4/im/5#Artifact#3#Handcraft#50105138282_3c1d02c968_o.jpg +DIS5K/DIS-TE4/im/8#Electronics#1#Antenna#4305034305_874f21a701_o.jpg +DIS5K/DIS-TR/im/1#Accessories#1#Bag#15554964549_3105e51b6f_o.jpg +DIS5K/DIS-TR/im/1#Accessories#1#Bag#41104261980_098a6c4a56_o.jpg +DIS5K/DIS-TR/im/1#Accessories#2#Clothes#2284764037_871b2e8ca4_o.jpg +DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#1824643784_70d0134156_o.jpg +DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#3590020230_37b09a29b3_o.jpg +DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#4809652879_4da8a69f3b_o.jpg +DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#792204934_f9b28f99b4_o.jpg +DIS5K/DIS-TR/im/1#Accessories#5#Jewelry#13909132974_c4750c5fb7_o.jpg +DIS5K/DIS-TR/im/1#Accessories#7#Shoe#2483391615_9199ece8d6_o.jpg +DIS5K/DIS-TR/im/1#Accessories#8#Watch#4343266960_f6633b029b_o.jpg +DIS5K/DIS-TR/im/10#Frame#2#BicycleFrame#17897573_42964dd104_o.jpg +DIS5K/DIS-TR/im/10#Frame#5#Rack#15898634812_64807069ff_o.jpg +DIS5K/DIS-TR/im/10#Frame#5#Rack#23928546819_c184cb0b60_o.jpg +DIS5K/DIS-TR/im/11#Furniture#19#Shower#6189119596_77bcfe80ee_o.jpg +DIS5K/DIS-TR/im/11#Furniture#2#Bench#3263647075_9306e280b5_o.jpg +DIS5K/DIS-TR/im/11#Furniture#5#CoatHanger#12774091054_cd5ff520ef_o.jpg +DIS5K/DIS-TR/im/11#Furniture#6#DentalChair#13878156865_d0439dcb32_o.jpg +DIS5K/DIS-TR/im/11#Furniture#9#Easel#5861024714_2070cd480c_o.jpg +DIS5K/DIS-TR/im/12#Graphics#4#TrafficSign#40621867334_f3c32ec189_o.jpg +DIS5K/DIS-TR/im/13#Insect#1#Ant#3295038190_db5dd0d4f4_o.jpg +DIS5K/DIS-TR/im/13#Insect#10#Mosquito#24341339_a88a1dad4c_o.jpg +DIS5K/DIS-TR/im/13#Insect#11#Spider#27171518270_63b78069ff_o.jpg +DIS5K/DIS-TR/im/13#Insect#11#Spider#49925050281_fa727c154e_o.jpg +DIS5K/DIS-TR/im/13#Insect#2#Beatle#279616486_2f1e64f591_o.jpg +DIS5K/DIS-TR/im/13#Insect#3#Bee#43892067695_82cf3e536b_o.jpg +DIS5K/DIS-TR/im/13#Insect#6#Centipede#20874281788_3e15c90a1c_o.jpg +DIS5K/DIS-TR/im/13#Insect#7#Dragonfly#14106671120_1b824d77e4_o.jpg +DIS5K/DIS-TR/im/13#Insect#8#Locust#21637491048_676ef7c9f7_o.jpg +DIS5K/DIS-TR/im/13#Insect#9#Mantis#1381120202_9dff6987b2_o.jpg +DIS5K/DIS-TR/im/14#Kitchenware#1#Cup#12812517473_327d6474b8_o.jpg +DIS5K/DIS-TR/im/14#Kitchenware#10#WineGlass#6402491641_389275d4d1_o.jpg +DIS5K/DIS-TR/im/14#Kitchenware#3#Hydrovalve#3129932040_8c05825004_o.jpg +DIS5K/DIS-TR/im/14#Kitchenware#4#Kitchenware#2881934780_87d5218ebb_o.jpg +DIS5K/DIS-TR/im/14#Kitchenware#4#Kitchenware#IMG_20210520_205527.jpg +DIS5K/DIS-TR/im/14#Kitchenware#6#Spoon#32989113501_b69eccf0df_o.jpg +DIS5K/DIS-TR/im/14#Kitchenware#8#SweetStand#2867322189_c56d1e0b87_o.jpg +DIS5K/DIS-TR/im/15#Machine#1#Gear#19217846720_f5f2807475_o.jpg +DIS5K/DIS-TR/im/15#Machine#2#Machine#1620160659_9571b7a7ab_o.jpg +DIS5K/DIS-TR/im/16#Music Instrument#2#Harp#6012801603_1a6e2c16a6_o.jpg +DIS5K/DIS-TR/im/16#Music Instrument#5#Trombone#8683292118_d223c17ccb_o.jpg +DIS5K/DIS-TR/im/16#Music Instrument#6#Trumpet#8393262740_b8c216142c_o.jpg +DIS5K/DIS-TR/im/16#Music Instrument#8#Violin#1511267391_40e4949d68_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#1#BabyCarriage#6989512997_38b3dbc88b_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#12#Wheel#14627183228_b2d68cf501_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#12#Wheel#2932226475_1b2403e549_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#12#Wheel#5420155648_86459905b8_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#2#Bicycle#IMG_20210513_134904.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#3#Carriage#3311962551_6f211b7bd6_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#4#Cart#2609732026_baf7fff3a1_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#5#Handcart#5821282211_201cefeaf2_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#7#Mower#5779003232_3bb3ae531a_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#9#ShoppingCart#10051622843_ace07e32b8_o.jpg +DIS5K/DIS-TR/im/17#Non-motor Vehicle#9#ShoppingCart#8075259294_f23e243849_o.jpg +DIS5K/DIS-TR/im/18#Plant#2#Tree#44800999741_e377e16dbb_o.jpg +DIS5K/DIS-TR/im/2#Aircraft#1#Airplane#2631761913_3ac67d0223_o.jpg +DIS5K/DIS-TR/im/2#Aircraft#1#Airplane#37707911566_e908a261b6_o.jpg +DIS5K/DIS-TR/im/2#Aircraft#3#HangGlider#2557220131_b8506920c5_o.jpg +DIS5K/DIS-TR/im/2#Aircraft#4#Helicopter#6215659280_5dbd9b4546_o.jpg +DIS5K/DIS-TR/im/2#Aircraft#6#Parachute#20185790493_e56fcaf8c6_o.jpg +DIS5K/DIS-TR/im/20#Sports#1#Archery#3871269982_ae4c59a7eb_o.jpg +DIS5K/DIS-TR/im/20#Sports#9#RockClimbing#9662433268_51299bc50e_o.jpg +DIS5K/DIS-TR/im/21#Tool#14#Sword#26258479365_2950d7fa37_o.jpg +DIS5K/DIS-TR/im/21#Tool#15#Tapeline#15505703447_e0fdeaa5a6_o.jpg +DIS5K/DIS-TR/im/21#Tool#4#Flag#26678602024_9b665742de_o.jpg +DIS5K/DIS-TR/im/21#Tool#4#Flag#5774823110_d603ce3cc8_o.jpg +DIS5K/DIS-TR/im/21#Tool#5#Hook#6867989814_dba18d673c_o.jpg +DIS5K/DIS-TR/im/22#Weapon#4#Rifle#4451713125_cd91719189_o.jpg +DIS5K/DIS-TR/im/3#Aquatic#2#Seadragon#4910944581_913139b238_o.jpg +DIS5K/DIS-TR/im/4#Architecture#12#Scaffold#3661448960_8aff24cc4d_o.jpg +DIS5K/DIS-TR/im/4#Architecture#13#Sculpture#6385318715_9a88d4eba7_o.jpg +DIS5K/DIS-TR/im/4#Architecture#17#Well#5011603479_75cf42808a_o.jpg +DIS5K/DIS-TR/im/5#Artifact#2#Cage#4892828841_7f1bc05682_o.jpg +DIS5K/DIS-TR/im/5#Artifact#3#Handcraft#15404211628_9e9ff2ce2e_o.jpg +DIS5K/DIS-TR/im/5#Artifact#3#Handcraft#3200169865_7c84cfcccf_o.jpg +DIS5K/DIS-TR/im/5#Artifact#3#Handcraft#5859295071_c217e7c22f_o.jpg +DIS5K/DIS-TR/im/6#Automobile#10#SteeringWheel#17200338026_f1e2122d8e_o.jpg +DIS5K/DIS-TR/im/6#Automobile#3#Car#3780893425_1a7d275e09_o.jpg +DIS5K/DIS-TR/im/6#Automobile#5#Crane#15282506502_1b1132a7c3_o.jpg +DIS5K/DIS-TR/im/7#Electrical#1#Cable#16767791875_8e6df41752_o.jpg +DIS5K/DIS-TR/im/7#Electrical#1#Cable#3291433361_38747324c4_o.jpg +DIS5K/DIS-TR/im/7#Electrical#1#Cable#4195104238_12a754c61a_o.jpg +DIS5K/DIS-TR/im/7#Electrical#1#Cable#49645415132_61e5664ecf_o.jpg +DIS5K/DIS-TR/im/7#Electrical#1#Cable#IMG_20210521_232406.jpg +DIS5K/DIS-TR/im/7#Electrical#10#UtilityPole#3298312021_92f431e3e9_o.jpg +DIS5K/DIS-TR/im/7#Electrical#10#UtilityPole#47950134773_fbfff63f4e_o.jpg +DIS5K/DIS-TR/im/7#Electrical#11#VacuumCleaner#5448403677_6a29e21881_o.jpg +DIS5K/DIS-TR/im/7#Electrical#2#CeilingLamp#611568868_680ed5d39f_o.jpg +DIS5K/DIS-TR/im/7#Electrical#3#Fan#3391683115_990525a693_o.jpg +DIS5K/DIS-TR/im/7#Electrical#6#StreetLamp#150049122_0692266618_o.jpg +DIS5K/DIS-TR/im/7#Electrical#9#TransmissionTower#31433908671_7e7e277dfe_o.jpg +DIS5K/DIS-TR/im/8#Electronics#1#Antenna#8727884873_e0622ee5c4_o.jpg +DIS5K/DIS-TR/im/8#Electronics#2#Camcorder#4172690390_7e5f280ace_o.jpg +DIS5K/DIS-TR/im/8#Electronics#3#Earphone#413984555_f290febdf5_o.jpg +DIS5K/DIS-TR/im/8#Electronics#5#Headset#30574225373_3717ed9fa4_o.jpg +DIS5K/DIS-TR/im/8#Electronics#6#Microphone#538006482_4aae4f5bd6_o.jpg +DIS5K/DIS-TR/im/8#Electronics#9#MusicPlayer#1306012480_2ea80d2afd_o.jpg +DIS5K/DIS-TR/im/9#Entertainment#1#GymEquipment#33071754135_8f3195cbd1_o.jpg +DIS5K/DIS-TR/im/9#Entertainment#2#KidsPlayground#2305807849_be53d724ea_o.jpg +DIS5K/DIS-TR/im/9#Entertainment#2#KidsPlayground#3862040422_5bbf903204_o.jpg +DIS5K/DIS-TR/im/9#Entertainment#3#OutdoorFitnessEquipment#10814507005_3dacaa28b3_o.jpg +DIS5K/DIS-TR/im/9#Entertainment#4#FerrisWheel#81640293_4b0ee62040_o.jpg +DIS5K/DIS-TR/im/9#Entertainment#5#Swing#49867339188_08073f4b76_o.jpg +DIS5K/DIS-VD/im/1#Accessories#1#Bag#6815402415_e01c1a41e6_o.jpg +DIS5K/DIS-VD/im/1#Accessories#5#Jewelry#2744070193_1486582e8d_o.jpg +DIS5K/DIS-VD/im/10#Frame#1#BasketballHoop#IMG_20210521_232650.jpg +DIS5K/DIS-VD/im/10#Frame#5#Rack#6156611713_49ebf12b1e_o.jpg +DIS5K/DIS-VD/im/11#Furniture#11#Handrail#3276641240_1b84b5af85_o.jpg +DIS5K/DIS-VD/im/11#Furniture#13#Ladder#33423266_5391cf47e9_o.jpg +DIS5K/DIS-VD/im/11#Furniture#17#Table#3725111755_4fc101e7ab_o.jpg +DIS5K/DIS-VD/im/11#Furniture#2#Bench#35556410400_7235b58070_o.jpg +DIS5K/DIS-VD/im/11#Furniture#4#Chair#3301769985_e49de6739f_o.jpg +DIS5K/DIS-VD/im/11#Furniture#6#DentalChair#23811071619_2a95c3a688_o.jpg +DIS5K/DIS-VD/im/11#Furniture#9#Easel#8322807354_df6d56542e_o.jpg +DIS5K/DIS-VD/im/13#Insect#10#Mosquito#12391674863_0cdf430d3f_o.jpg +DIS5K/DIS-VD/im/13#Insect#7#Dragonfly#14693028899_344ea118f2_o.jpg +DIS5K/DIS-VD/im/14#Kitchenware#10#WineGlass#4450148455_8f460f541a_o.jpg +DIS5K/DIS-VD/im/14#Kitchenware#3#Hydrovalve#IMG_20210520_203410.jpg +DIS5K/DIS-VD/im/15#Machine#3#PlowHarrow#34521712846_df4babb024_o.jpg +DIS5K/DIS-VD/im/16#Music Instrument#5#Trombone#6222242743_e7189405cd_o.jpg +DIS5K/DIS-VD/im/17#Non-motor Vehicle#12#Wheel#25677578797_ea47e1d9e8_o.jpg +DIS5K/DIS-VD/im/17#Non-motor Vehicle#2#Bicycle#5153474856_21560b081b_o.jpg +DIS5K/DIS-VD/im/17#Non-motor Vehicle#7#Mower#16992510572_8a6ff27398_o.jpg +DIS5K/DIS-VD/im/19#Ship#2#Canoe#40571458163_7faf8b73d9_o.jpg +DIS5K/DIS-VD/im/2#Aircraft#1#Airplane#4270588164_66a619e834_o.jpg +DIS5K/DIS-VD/im/2#Aircraft#4#Helicopter#86789665_650b94b2ee_o.jpg +DIS5K/DIS-VD/im/20#Sports#14#Wakesurfing#5589577652_5061c168d2_o.jpg +DIS5K/DIS-VD/im/21#Tool#10#Spade#37018312543_63b21b0784_o.jpg +DIS5K/DIS-VD/im/21#Tool#14#Sword#24789047250_42df9bf422_o.jpg +DIS5K/DIS-VD/im/21#Tool#18#Umbrella#IMG_20210513_140445.jpg +DIS5K/DIS-VD/im/21#Tool#6#Key#43939732715_5a6e28b518_o.jpg +DIS5K/DIS-VD/im/22#Weapon#1#Cannon#12758066705_90b54295e7_o.jpg +DIS5K/DIS-VD/im/22#Weapon#4#Rifle#8019368790_fb6dc469a7_o.jpg +DIS5K/DIS-VD/im/3#Aquatic#5#Shrimp#2582833427_7a99e7356e_o.jpg +DIS5K/DIS-VD/im/4#Architecture#12#Scaffold#1013402687_590750354e_o.jpg +DIS5K/DIS-VD/im/4#Architecture#13#Sculpture#17176841759_272a3ed6e3_o.jpg +DIS5K/DIS-VD/im/4#Architecture#14#Stair#15079108505_0d11281624_o.jpg +DIS5K/DIS-VD/im/4#Architecture#19#Windmill#2928111082_ceb3051c04_o.jpg +DIS5K/DIS-VD/im/4#Architecture#3#Crack#3551574032_17dd106d31_o.jpg +DIS5K/DIS-VD/im/4#Architecture#5#GasStation#4564307581_c3069bdc62_o.jpg +DIS5K/DIS-VD/im/4#Architecture#8#ObservationTower#2704526950_d4f0ddc807_o.jpg +DIS5K/DIS-VD/im/5#Artifact#3#Handcraft#10873642323_1bafce3aa5_o.jpg +DIS5K/DIS-VD/im/6#Automobile#11#Tractor#8594504006_0c2c557d85_o.jpg +DIS5K/DIS-VD/im/8#Electronics#3#Earphone#8106454803_1178d867cc_o.jpg \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74882c0eacac7e9bde0e13008fab31037eae671d --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. +"""Depth Pro network blocks.""" diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/decoder.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..770665fcd3e47948388d5da43487d9e75dc0f3fc --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/decoder.py @@ -0,0 +1,206 @@ +"""Copyright (C) 2024 Apple Inc. All Rights Reserved. + +Dense Prediction Transformer Decoder architecture. + +Implements a variant of Vision Transformers for Dense Prediction, https://arxiv.org/abs/2103.13413 +""" + +from __future__ import annotations + +from typing import Iterable + +import torch +from torch import nn + + +class MultiresConvDecoder(nn.Module): + """Decoder for multi-resolution encodings.""" + + def __init__( + self, + dims_encoder: Iterable[int], + dim_decoder: int, + ): + """Initialize multiresolution convolutional decoder. + + Args: + ---- + dims_encoder: Expected dims at each level from the encoder. + dim_decoder: Dim of decoder features. + + """ + super().__init__() + self.dims_encoder = list(dims_encoder) + self.dim_decoder = dim_decoder + self.dim_out = dim_decoder + + num_encoders = len(self.dims_encoder) + + # At the highest resolution, i.e. level 0, we apply projection w/ 1x1 convolution + # when the dimensions mismatch. Otherwise we do not do anything, which is + # the default behavior of monodepth. + conv0 = ( + nn.Conv2d(self.dims_encoder[0], dim_decoder, kernel_size=1, bias=False) + if self.dims_encoder[0] != dim_decoder + else nn.Identity() + ) + + convs = [conv0] + for i in range(1, num_encoders): + convs.append( + nn.Conv2d( + self.dims_encoder[i], + dim_decoder, + kernel_size=3, + stride=1, + padding=1, + bias=False, + ) + ) + + self.convs = nn.ModuleList(convs) + + fusions = [] + for i in range(num_encoders): + fusions.append( + FeatureFusionBlock2d( + num_features=dim_decoder, + deconv=(i != 0), + batch_norm=False, + ) + ) + self.fusions = nn.ModuleList(fusions) + + def forward(self, encodings: torch.Tensor) -> torch.Tensor: + """Decode the multi-resolution encodings.""" + num_levels = len(encodings) + num_encoders = len(self.dims_encoder) + + if num_levels != num_encoders: + raise ValueError( + f"Got encoder output levels={num_levels}, expected levels={num_encoders+1}." + ) + + # Project features of different encoder dims to the same decoder dim. + # Fuse features from the lowest resolution (num_levels-1) + # to the highest (0). + features = self.convs[-1](encodings[-1]) + lowres_features = features + features = self.fusions[-1](features) + for i in range(num_levels - 2, -1, -1): + features_i = self.convs[i](encodings[i]) + features = self.fusions[i](features, features_i) + return features, lowres_features + + +class ResidualBlock(nn.Module): + """Generic implementation of residual blocks. + + This implements a generic residual block from + He et al. - Identity Mappings in Deep Residual Networks (2016), + https://arxiv.org/abs/1603.05027 + which can be further customized via factory functions. + """ + + def __init__(self, residual: nn.Module, shortcut: nn.Module | None = None) -> None: + """Initialize ResidualBlock.""" + super().__init__() + self.residual = residual + self.shortcut = shortcut + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply residual block.""" + delta_x = self.residual(x) + + if self.shortcut is not None: + x = self.shortcut(x) + + return x + delta_x + + +class FeatureFusionBlock2d(nn.Module): + """Feature fusion for DPT.""" + + def __init__( + self, + num_features: int, + deconv: bool = False, + batch_norm: bool = False, + ): + """Initialize feature fusion block. + + Args: + ---- + num_features: Input and output dimensions. + deconv: Whether to use deconv before the final output conv. + batch_norm: Whether to use batch normalization in resnet blocks. + + """ + super().__init__() + + self.resnet1 = self._residual_block(num_features, batch_norm) + self.resnet2 = self._residual_block(num_features, batch_norm) + + self.use_deconv = deconv + if deconv: + self.deconv = nn.ConvTranspose2d( + in_channels=num_features, + out_channels=num_features, + kernel_size=2, + stride=2, + padding=0, + bias=False, + ) + + self.out_conv = nn.Conv2d( + num_features, + num_features, + kernel_size=1, + stride=1, + padding=0, + bias=True, + ) + + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x0: torch.Tensor, x1: torch.Tensor | None = None) -> torch.Tensor: + """Process and fuse input features.""" + x = x0 + + if x1 is not None: + res = self.resnet1(x1) + x = self.skip_add.add(x, res) + + x = self.resnet2(x) + + if self.use_deconv: + x = self.deconv(x) + x = self.out_conv(x) + + return x + + @staticmethod + def _residual_block(num_features: int, batch_norm: bool): + """Create a residual block.""" + + def _create_block(dim: int, batch_norm: bool) -> list[nn.Module]: + layers = [ + nn.ReLU(False), + nn.Conv2d( + num_features, + num_features, + kernel_size=3, + stride=1, + padding=1, + bias=not batch_norm, + ), + ] + if batch_norm: + layers.append(nn.BatchNorm2d(dim)) + return layers + + residual = nn.Sequential( + *_create_block(dim=num_features, batch_norm=batch_norm), + *_create_block(dim=num_features, batch_norm=batch_norm), + ) + return ResidualBlock(residual) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/encoder.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a3da17d47bf91662463520afaf413f08676c3b --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/encoder.py @@ -0,0 +1,332 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. +# DepthProEncoder combining patch and image encoders. + +from __future__ import annotations + +import math +from typing import Iterable, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class DepthProEncoder(nn.Module): + """DepthPro Encoder. + + An encoder aimed at creating multi-resolution encodings from Vision Transformers. + """ + + def __init__( + self, + dims_encoder: Iterable[int], + patch_encoder: nn.Module, + image_encoder: nn.Module, + hook_block_ids: Iterable[int], + decoder_features: int, + ): + """Initialize DepthProEncoder. + + The framework + 1. creates an image pyramid, + 2. generates overlapping patches with a sliding window at each pyramid level, + 3. creates batched encodings via vision transformer backbones, + 4. produces multi-resolution encodings. + + Args: + ---- + img_size: Backbone image resolution. + dims_encoder: Dimensions of the encoder at different layers. + patch_encoder: Backbone used for patches. + image_encoder: Backbone used for global image encoder. + hook_block_ids: Hooks to obtain intermediate features for the patch encoder model. + decoder_features: Number of feature output in the decoder. + + """ + super().__init__() + + self.dims_encoder = list(dims_encoder) + self.patch_encoder = patch_encoder + self.image_encoder = image_encoder + self.hook_block_ids = list(hook_block_ids) + + patch_encoder_embed_dim = patch_encoder.embed_dim + image_encoder_embed_dim = image_encoder.embed_dim + + self.out_size = int( + patch_encoder.patch_embed.img_size[0] // patch_encoder.patch_embed.patch_size[0] + ) + + def _create_project_upsample_block( + dim_in: int, + dim_out: int, + upsample_layers: int, + dim_int: Optional[int] = None, + ) -> nn.Module: + if dim_int is None: + dim_int = dim_out + # Projection. + blocks = [ + nn.Conv2d( + in_channels=dim_in, + out_channels=dim_int, + kernel_size=1, + stride=1, + padding=0, + bias=False, + ) + ] + + # Upsampling. + blocks += [ + nn.ConvTranspose2d( + in_channels=dim_int if i == 0 else dim_out, + out_channels=dim_out, + kernel_size=2, + stride=2, + padding=0, + bias=False, + ) + for i in range(upsample_layers) + ] + + return nn.Sequential(*blocks) + + self.upsample_latent0 = _create_project_upsample_block( + dim_in=patch_encoder_embed_dim, + dim_int=self.dims_encoder[0], + dim_out=decoder_features, + upsample_layers=3, + ) + self.upsample_latent1 = _create_project_upsample_block( + dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[0], upsample_layers=2 + ) + + self.upsample0 = _create_project_upsample_block( + dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[1], upsample_layers=1 + ) + self.upsample1 = _create_project_upsample_block( + dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[2], upsample_layers=1 + ) + self.upsample2 = _create_project_upsample_block( + dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[3], upsample_layers=1 + ) + + self.upsample_lowres = nn.ConvTranspose2d( + in_channels=image_encoder_embed_dim, + out_channels=self.dims_encoder[3], + kernel_size=2, + stride=2, + padding=0, + bias=True, + ) + self.fuse_lowres = nn.Conv2d( + in_channels=(self.dims_encoder[3] + self.dims_encoder[3]), + out_channels=self.dims_encoder[3], + kernel_size=1, + stride=1, + padding=0, + bias=True, + ) + + # Obtain intermediate outputs of the blocks. + self.patch_encoder.blocks[self.hook_block_ids[0]].register_forward_hook( + self._hook0 + ) + self.patch_encoder.blocks[self.hook_block_ids[1]].register_forward_hook( + self._hook1 + ) + + def _hook0(self, model, input, output): + self.backbone_highres_hook0 = output + + def _hook1(self, model, input, output): + self.backbone_highres_hook1 = output + + @property + def img_size(self) -> int: + """Return the full image size of the SPN network.""" + return self.patch_encoder.patch_embed.img_size[0] * 4 + + def _create_pyramid( + self, x: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Create a 3-level image pyramid.""" + # Original resolution: 1536 by default. + x0 = x + + # Middle resolution: 768 by default. + x1 = F.interpolate( + x, size=None, scale_factor=0.5, mode="bilinear", align_corners=False + ) + + # Low resolution: 384 by default, corresponding to the backbone resolution. + x2 = F.interpolate( + x, size=None, scale_factor=0.25, mode="bilinear", align_corners=False + ) + + return x0, x1, x2 + + def split(self, x: torch.Tensor, overlap_ratio: float = 0.25) -> torch.Tensor: + """Split the input into small patches with sliding window.""" + patch_size = 384 + patch_stride = int(patch_size * (1 - overlap_ratio)) + + image_size = x.shape[-1] + steps = int(math.ceil((image_size - patch_size) / patch_stride)) + 1 + + x_patch_list = [] + for j in range(steps): + j0 = j * patch_stride + j1 = j0 + patch_size + + for i in range(steps): + i0 = i * patch_stride + i1 = i0 + patch_size + x_patch_list.append(x[..., j0:j1, i0:i1]) + + return torch.cat(x_patch_list, dim=0) + + def merge(self, x: torch.Tensor, batch_size: int, padding: int = 3) -> torch.Tensor: + """Merge the patched input into a image with sliding window.""" + steps = int(math.sqrt(x.shape[0] // batch_size)) + + idx = 0 + + output_list = [] + for j in range(steps): + output_row_list = [] + for i in range(steps): + output = x[batch_size * idx : batch_size * (idx + 1)] + + if j != 0: + output = output[..., padding:, :] + if i != 0: + output = output[..., :, padding:] + if j != steps - 1: + output = output[..., :-padding, :] + if i != steps - 1: + output = output[..., :, :-padding] + + output_row_list.append(output) + idx += 1 + + output_row = torch.cat(output_row_list, dim=-1) + output_list.append(output_row) + output = torch.cat(output_list, dim=-2) + return output + + def reshape_feature( + self, embeddings: torch.Tensor, width, height, cls_token_offset=1 + ): + """Discard class token and reshape 1D feature map to a 2D grid.""" + b, hw, c = embeddings.shape + + # Remove class token. + if cls_token_offset > 0: + embeddings = embeddings[:, cls_token_offset:, :] + + # Shape: (batch, height, width, dim) -> (batch, dim, height, width) + embeddings = embeddings.reshape(b, height, width, c).permute(0, 3, 1, 2) + return embeddings + + def forward(self, x: torch.Tensor) -> list[torch.Tensor]: + """Encode input at multiple resolutions. + + Args: + ---- + x (torch.Tensor): Input image. + + Returns: + ------- + Multi resolution encoded features. + + """ + batch_size = x.shape[0] + + # Step 0: create a 3-level image pyramid. + x0, x1, x2 = self._create_pyramid(x) + + # Step 1: split to create batched overlapped mini-images at the backbone (BeiT/ViT/Dino) + # resolution. + # 5x5 @ 384x384 at the highest resolution (1536x1536). + x0_patches = self.split(x0, overlap_ratio=0.25) + # 3x3 @ 384x384 at the middle resolution (768x768). + x1_patches = self.split(x1, overlap_ratio=0.5) + # 1x1 # 384x384 at the lowest resolution (384x384). + x2_patches = x2 + + # Concatenate all the sliding window patches and form a batch of size (35=5x5+3x3+1x1). + x_pyramid_patches = torch.cat( + (x0_patches, x1_patches, x2_patches), + dim=0, + ) + + # Step 2: Run the backbone (BeiT) model and get the result of large batch size. + x_pyramid_encodings = self.patch_encoder(x_pyramid_patches) + x_pyramid_encodings = self.reshape_feature( + x_pyramid_encodings, self.out_size, self.out_size + ) + + # Step 3: merging. + # Merge highres latent encoding. + x_latent0_encodings = self.reshape_feature( + self.backbone_highres_hook0, + self.out_size, + self.out_size, + ) + x_latent0_features = self.merge( + x_latent0_encodings[: batch_size * 5 * 5], batch_size=batch_size, padding=3 + ) + + x_latent1_encodings = self.reshape_feature( + self.backbone_highres_hook1, + self.out_size, + self.out_size, + ) + x_latent1_features = self.merge( + x_latent1_encodings[: batch_size * 5 * 5], batch_size=batch_size, padding=3 + ) + + # Split the 35 batch size from pyramid encoding back into 5x5+3x3+1x1. + x0_encodings, x1_encodings, x2_encodings = torch.split( + x_pyramid_encodings, + [len(x0_patches), len(x1_patches), len(x2_patches)], + dim=0, + ) + + # 96x96 feature maps by merging 5x5 @ 24x24 patches with overlaps. + x0_features = self.merge(x0_encodings, batch_size=batch_size, padding=3) + + # 48x84 feature maps by merging 3x3 @ 24x24 patches with overlaps. + x1_features = self.merge(x1_encodings, batch_size=batch_size, padding=6) + + # 24x24 feature maps. + x2_features = x2_encodings + + # Apply the image encoder model. + x_global_features = self.image_encoder(x2_patches) + x_global_features = self.reshape_feature( + x_global_features, self.out_size, self.out_size + ) + + # Upsample feature maps. + x_latent0_features = self.upsample_latent0(x_latent0_features) + x_latent1_features = self.upsample_latent1(x_latent1_features) + + x0_features = self.upsample0(x0_features) + x1_features = self.upsample1(x1_features) + x2_features = self.upsample2(x2_features) + + x_global_features = self.upsample_lowres(x_global_features) + x_global_features = self.fuse_lowres( + torch.cat((x2_features, x_global_features), dim=1) + ) + + return [ + x_latent0_features, + x_latent1_features, + x0_features, + x1_features, + x_global_features, + ] diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/fov.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/fov.py new file mode 100644 index 0000000000000000000000000000000000000000..5900286509ca9535d4d29679b88055b5b6aed938 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/fov.py @@ -0,0 +1,82 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. +# Field of View network architecture. + +from typing import Optional + +import torch +from torch import nn +from torch.nn import functional as F + + +class FOVNetwork(nn.Module): + """Field of View estimation network.""" + + def __init__( + self, + num_features: int, + fov_encoder: Optional[nn.Module] = None, + ): + """Initialize the Field of View estimation block. + + Args: + ---- + num_features: Number of features used. + fov_encoder: Optional encoder to bring additional network capacity. + + """ + super().__init__() + + # Create FOV head. + fov_head0 = [ + nn.Conv2d( + num_features, num_features // 2, kernel_size=3, stride=2, padding=1 + ), # 128 x 24 x 24 + nn.ReLU(True), + ] + fov_head = [ + nn.Conv2d( + num_features // 2, num_features // 4, kernel_size=3, stride=2, padding=1 + ), # 64 x 12 x 12 + nn.ReLU(True), + nn.Conv2d( + num_features // 4, num_features // 8, kernel_size=3, stride=2, padding=1 + ), # 32 x 6 x 6 + nn.ReLU(True), + nn.Conv2d(num_features // 8, 1, kernel_size=6, stride=1, padding=0), + ] + if fov_encoder is not None: + self.encoder = nn.Sequential( + fov_encoder, nn.Linear(fov_encoder.embed_dim, num_features // 2) + ) + self.downsample = nn.Sequential(*fov_head0) + else: + fov_head = fov_head0 + fov_head + self.head = nn.Sequential(*fov_head) + + def forward(self, x: torch.Tensor, lowres_feature: torch.Tensor) -> torch.Tensor: + """Forward the fov network. + + Args: + ---- + x (torch.Tensor): Input image. + lowres_feature (torch.Tensor): Low resolution feature. + + Returns: + ------- + The field of view tensor. + + """ + if hasattr(self, "encoder"): + x = F.interpolate( + x, + size=None, + scale_factor=0.25, + mode="bilinear", + align_corners=False, + ) + x = self.encoder(x)[:, 1:].permute(0, 2, 1) + lowres_feature = self.downsample(lowres_feature) + x = x.reshape_as(lowres_feature) + lowres_feature + else: + x = lowres_feature + return self.head(x) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c3768a1dcedccd99a58f9507f4edac3cde9da0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit.py @@ -0,0 +1,123 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. + + +try: + from timm.layers import resample_abs_pos_embed +except ImportError as err: + print("ImportError: {0}".format(err)) +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint + + +def make_vit_b16_backbone( + model, + encoder_feature_dims, + encoder_feature_layer_ids, + vit_features, + start_index=1, + use_grad_checkpointing=False, +) -> nn.Module: + """Make a ViTb16 backbone for the DPT model.""" + if use_grad_checkpointing: + model.set_grad_checkpointing() + + vit_model = nn.Module() + vit_model.hooks = encoder_feature_layer_ids + vit_model.model = model + vit_model.features = encoder_feature_dims + vit_model.vit_features = vit_features + vit_model.model.start_index = start_index + vit_model.model.patch_size = vit_model.model.patch_embed.patch_size + vit_model.model.is_vit = True + vit_model.model.forward = vit_model.model.forward_features + + return vit_model + + +def forward_features_eva_fixed(self, x): + """Encode features.""" + x = self.patch_embed(x) + x, rot_pos_embed = self._pos_embed(x) + for blk in self.blocks: + if self.grad_checkpointing: + x = checkpoint(blk, x, rot_pos_embed) + else: + x = blk(x, rot_pos_embed) + x = self.norm(x) + return x + + +def resize_vit(model: nn.Module, img_size) -> nn.Module: + """Resample the ViT module to the given size.""" + patch_size = model.patch_embed.patch_size + model.patch_embed.img_size = img_size + grid_size = tuple([s // p for s, p in zip(img_size, patch_size)]) + model.patch_embed.grid_size = grid_size + + pos_embed = resample_abs_pos_embed( + model.pos_embed, + grid_size, # img_size + num_prefix_tokens=( + 0 if getattr(model, "no_embed_class", False) else model.num_prefix_tokens + ), + ) + model.pos_embed = torch.nn.Parameter(pos_embed) + + return model + + +def resize_patch_embed(model: nn.Module, new_patch_size=(16, 16)) -> nn.Module: + """Resample the ViT patch size to the given one.""" + # interpolate patch embedding + if hasattr(model, "patch_embed"): + old_patch_size = model.patch_embed.patch_size + + if ( + new_patch_size[0] != old_patch_size[0] + or new_patch_size[1] != old_patch_size[1] + ): + patch_embed_proj = model.patch_embed.proj.weight + patch_embed_proj_bias = model.patch_embed.proj.bias + use_bias = True if patch_embed_proj_bias is not None else False + _, _, h, w = patch_embed_proj.shape + + new_patch_embed_proj = torch.nn.functional.interpolate( + patch_embed_proj, + size=[new_patch_size[0], new_patch_size[1]], + mode="bicubic", + align_corners=False, + ) + new_patch_embed_proj = ( + new_patch_embed_proj * (h / new_patch_size[0]) * (w / new_patch_size[1]) + ) + + model.patch_embed.proj = nn.Conv2d( + in_channels=model.patch_embed.proj.in_channels, + out_channels=model.patch_embed.proj.out_channels, + kernel_size=new_patch_size, + stride=new_patch_size, + bias=use_bias, + ) + + if use_bias: + model.patch_embed.proj.bias = patch_embed_proj_bias + + model.patch_embed.proj.weight = torch.nn.Parameter(new_patch_embed_proj) + + model.patch_size = new_patch_size + model.patch_embed.patch_size = new_patch_size + model.patch_embed.img_size = ( + int( + model.patch_embed.img_size[0] + * new_patch_size[0] + / old_patch_size[0] + ), + int( + model.patch_embed.img_size[1] + * new_patch_size[1] + / old_patch_size[1] + ), + ) + + return model diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit_factory.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd899f650978043c2c83348670beaf597e9ca30 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit_factory.py @@ -0,0 +1,124 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. +# Factory functions to build and load ViT models. + + +from __future__ import annotations + +import logging +import types +from dataclasses import dataclass +from typing import Dict, List, Literal, Optional + +import timm +import torch +import torch.nn as nn + +from .vit import ( + forward_features_eva_fixed, + make_vit_b16_backbone, + resize_patch_embed, + resize_vit, +) + +LOGGER = logging.getLogger(__name__) + + +ViTPreset = Literal[ + "dinov2l16_384", +] + + +@dataclass +class ViTConfig: + """Configuration for ViT.""" + + in_chans: int + embed_dim: int + + img_size: int = 384 + patch_size: int = 16 + + # In case we need to rescale the backbone when loading from timm. + timm_preset: Optional[str] = None + timm_img_size: int = 384 + timm_patch_size: int = 16 + + # The following 2 parameters are only used by DPT. See dpt_factory.py. + encoder_feature_layer_ids: List[int] = None + """The layers in the Beit/ViT used to constructs encoder features for DPT.""" + encoder_feature_dims: List[int] = None + """The dimension of features of encoder layers from Beit/ViT features for DPT.""" + + +VIT_CONFIG_DICT: Dict[ViTPreset, ViTConfig] = { + "dinov2l16_384": ViTConfig( + in_chans=3, + embed_dim=1024, + encoder_feature_layer_ids=[5, 11, 17, 23], + encoder_feature_dims=[256, 512, 1024, 1024], + img_size=384, + patch_size=16, + timm_preset="vit_large_patch14_dinov2", + timm_img_size=518, + timm_patch_size=14, + ), +} + + +def create_vit( + preset: ViTPreset, + use_pretrained: bool = False, + checkpoint_uri: str | None = None, + use_grad_checkpointing: bool = False, +) -> nn.Module: + """Create and load a VIT backbone module. + + Args: + ---- + preset: The VIT preset to load the pre-defined config. + use_pretrained: Load pretrained weights if True, default is False. + checkpoint_uri: Checkpoint to load the wights from. + use_grad_checkpointing: Use grandient checkpointing. + + Returns: + ------- + A Torch ViT backbone module. + + """ + config = VIT_CONFIG_DICT[preset] + + img_size = (config.img_size, config.img_size) + patch_size = (config.patch_size, config.patch_size) + + if "eva02" in preset: + model = timm.create_model(config.timm_preset, pretrained=use_pretrained) + model.forward_features = types.MethodType(forward_features_eva_fixed, model) + else: + model = timm.create_model( + config.timm_preset, pretrained=use_pretrained, dynamic_img_size=True + ) + model = make_vit_b16_backbone( + model, + encoder_feature_dims=config.encoder_feature_dims, + encoder_feature_layer_ids=config.encoder_feature_layer_ids, + vit_features=config.embed_dim, + use_grad_checkpointing=use_grad_checkpointing, + ) + if config.patch_size != config.timm_patch_size: + model.model = resize_patch_embed(model.model, new_patch_size=patch_size) + if config.img_size != config.timm_img_size: + model.model = resize_vit(model.model, img_size=img_size) + + if checkpoint_uri is not None: + state_dict = torch.load(checkpoint_uri, map_location="cpu") + missing_keys, unexpected_keys = model.load_state_dict( + state_dict=state_dict, strict=False + ) + + if len(unexpected_keys) != 0: + raise KeyError(f"Found unexpected keys when loading vit: {unexpected_keys}") + if len(missing_keys) != 0: + raise KeyError(f"Keys are missing when loading vit: {missing_keys}") + + LOGGER.info(model) + return model.model diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/test_depth_pro.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/test_depth_pro.py new file mode 100644 index 0000000000000000000000000000000000000000..87c015226eea64ca8a94b57b8f475d5ecfb74b4a --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/test_depth_pro.py @@ -0,0 +1,27 @@ +from PIL import Image +from models.monoD import depth_pro + +# Load model and preprocessing transform +model, transform = depth_pro.create_model_and_transforms() +model.eval() + +# Load and preprocess an image. +image_path = "assets/dance/00000.jpg" +image, _, f_px = depth_pro.load_rgb(image_path) +image = transform(image) + +# Run inference. +import time +t0 = time.time() +prediction = model.infer(image, f_px=f_px) +depth = prediction["depth"] # Depth in [m]. +focallength_px = prediction["focallength_px"] # Focal length in pixels. +import cv2 +import numpy as np +depth = depth.clamp(0,30).squeeze().detach().cpu().numpy() +depth = (depth - depth.min())/(depth.max()-depth.min()) * 255.0 +depth = depth.astype(np.uint8) +depth = cv2.applyColorMap(depth, cv2.COLORMAP_INFERNO) +cv2.imwrite("depth.png", depth) +print(f"Time: {time.time() - t0:.2f}s") +import pdb; pdb.set_trace() \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/utils.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0a401def2e1d6a2dd96b204e962569e9da5e0ef1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/utils.py @@ -0,0 +1,112 @@ +# Copyright (C) 2024 Apple Inc. All Rights Reserved. + +import logging +from pathlib import Path +from typing import Any, Dict, List, Tuple, Union + +import numpy as np +import pillow_heif +from PIL import ExifTags, Image, TiffTags +from pillow_heif import register_heif_opener + +register_heif_opener() +LOGGER = logging.getLogger(__name__) + + +def extract_exif(img_pil: Image) -> Dict[str, Any]: + """Return exif information as a dictionary. + + Args: + ---- + img_pil: A Pillow image. + + Returns: + ------- + A dictionary with extracted EXIF information. + + """ + # Get full exif description from get_ifd(0x8769): + # cf https://pillow.readthedocs.io/en/stable/releasenotes/8.2.0.html#image-getexif-exif-and-gps-ifd + img_exif = img_pil.getexif().get_ifd(0x8769) + exif_dict = {ExifTags.TAGS[k]: v for k, v in img_exif.items() if k in ExifTags.TAGS} + + tiff_tags = img_pil.getexif() + tiff_dict = { + TiffTags.TAGS_V2[k].name: v + for k, v in tiff_tags.items() + if k in TiffTags.TAGS_V2 + } + return {**exif_dict, **tiff_dict} + + +def fpx_from_f35(width: float, height: float, f_mm: float = 50) -> float: + """Convert a focal length given in mm (35mm film equivalent) to pixels.""" + return f_mm * np.sqrt(width**2.0 + height**2.0) / np.sqrt(36**2 + 24**2) + + +def load_rgb( + path: Union[Path, str], auto_rotate: bool = True, remove_alpha: bool = True +) -> Tuple[np.ndarray, List[bytes], float]: + """Load an RGB image. + + Args: + ---- + path: The url to the image to load. + auto_rotate: Rotate the image based on the EXIF data, default is True. + remove_alpha: Remove the alpha channel, default is True. + + Returns: + ------- + img: The image loaded as a numpy array. + icc_profile: The color profile of the image. + f_px: The optional focal length in pixels, extracting from the exif data. + + """ + LOGGER.debug(f"Loading image {path} ...") + + path = Path(path) + if path.suffix.lower() in [".heic"]: + heif_file = pillow_heif.open_heif(path, convert_hdr_to_8bit=True) + img_pil = heif_file.to_pillow() + else: + img_pil = Image.open(path) + + img_exif = extract_exif(img_pil) + icc_profile = img_pil.info.get("icc_profile", None) + + # Rotate the image. + if auto_rotate: + exif_orientation = img_exif.get("Orientation", 1) + if exif_orientation == 3: + img_pil = img_pil.transpose(Image.ROTATE_180) + elif exif_orientation == 6: + img_pil = img_pil.transpose(Image.ROTATE_270) + elif exif_orientation == 8: + img_pil = img_pil.transpose(Image.ROTATE_90) + elif exif_orientation != 1: + LOGGER.warning(f"Ignoring image orientation {exif_orientation}.") + + img = np.array(img_pil) + # Convert to RGB if single channel. + if img.ndim < 3 or img.shape[2] == 1: + img = np.dstack((img, img, img)) + + if remove_alpha: + img = img[:, :, :3] + + LOGGER.debug(f"\tHxW: {img.shape[0]}x{img.shape[1]}") + + # Extract the focal length from exif data. + f_35mm = img_exif.get( + "FocalLengthIn35mmFilm", + img_exif.get( + "FocalLenIn35mmFilm", img_exif.get("FocalLengthIn35mmFormat", None) + ), + ) + if f_35mm is not None and f_35mm > 0: + LOGGER.debug(f"\tfocal length @ 35mm film: {f_35mm}mm") + f_px = fpx_from_f35(img.shape[1], img.shape[0], f_35mm) + else: + f_px = None + + return img, icc_profile, f_px diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e09b2cf4b1bc7d94ff59e8b3cb9fc2fc82779c4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/__init__.py @@ -0,0 +1 @@ +from .hubconf import * \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/hubconf.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/hubconf.py new file mode 100644 index 0000000000000000000000000000000000000000..9b281847befd0ed2f6102232ba98af01085901ae --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/hubconf.py @@ -0,0 +1,435 @@ +dependencies = ["torch"] + +import torch + +from .midas.dpt_depth import DPTDepthModel +from .midas.midas_net import MidasNet +from .midas.midas_net_custom import MidasNet_small + +def DPT_BEiT_L_512(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_BEiT_L_512 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="beitl16_512", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_512.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_BEiT_L_384(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_BEiT_L_384 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="beitl16_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_BEiT_B_384(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_BEiT_B_384 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="beitb16_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_base_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_SwinV2_L_384(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_SwinV2_L_384 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="swin2l24_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_large_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_SwinV2_B_384(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_SwinV2_B_384 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="swin2b24_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_base_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_SwinV2_T_256(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_SwinV2_T_256 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="swin2t16_256", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_tiny_256.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_Swin_L_384(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_Swin_L_384 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="swinl12_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin_large_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_Next_ViT_L_384(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_Next_ViT_L_384 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="next_vit_large_6m", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_next_vit_large_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_LeViT_224(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT_LeViT_224 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="levit_384", + non_negative=True, + head_features_1=64, + head_features_2=8, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_levit_224.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_Large(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT-Large model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="vitl16_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3/dpt_large_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def DPT_Hybrid(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS DPT-Hybrid model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = DPTDepthModel( + path=None, + backbone="vitb_rn50_384", + non_negative=True, + ) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v3/dpt_hybrid_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def MiDaS(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS v2.1 model for monocular depth estimation + pretrained (bool): load pretrained weights into model + """ + + model = MidasNet() + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v2_1/midas_v21_384.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + +def MiDaS_small(pretrained=True, **kwargs): + """ # This docstring shows up in hub.help() + MiDaS v2.1 small model for monocular depth estimation on resource-constrained devices + pretrained (bool): load pretrained weights into model + """ + + model = MidasNet_small(None, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True}) + + if pretrained: + checkpoint = ( + "https://github.com/isl-org/MiDaS/releases/download/v2_1/midas_v21_small_256.pt" + ) + state_dict = torch.hub.load_state_dict_from_url( + checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True + ) + model.load_state_dict(state_dict) + + return model + + +def transforms(): + import cv2 + from torchvision.transforms import Compose + from midas.transforms import Resize, NormalizeImage, PrepareForNet + from midas import transforms + + transforms.default_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 384, + 384, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method="upper_bound", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + transforms.small_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 256, + 256, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method="upper_bound", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + transforms.dpt_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 384, + 384, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method="minimal", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + transforms.beit512_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 512, + 512, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method="minimal", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + transforms.swin384_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 384, + 384, + resize_target=None, + keep_aspect_ratio=False, + ensure_multiple_of=32, + resize_method="minimal", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + transforms.swin256_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 256, + 256, + resize_target=None, + keep_aspect_ratio=False, + ensure_multiple_of=32, + resize_method="minimal", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + transforms.levit_transform = Compose( + [ + lambda img: {"image": img / 255.0}, + Resize( + 224, + 224, + resize_target=None, + keep_aspect_ratio=False, + ensure_multiple_of=32, + resize_method="minimal", + image_interpolation_method=cv2.INTER_CUBIC, + ), + NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), + PrepareForNet(), + lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0), + ] + ) + + return transforms diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/beit.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/beit.py new file mode 100644 index 0000000000000000000000000000000000000000..8f25dd1ed756f4c468a2753299dc38b8eb101d82 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/beit.py @@ -0,0 +1,196 @@ +import timm +import torch +import types + +import numpy as np +import torch.nn.functional as F + +from .utils import forward_adapted_unflatten, make_backbone_default +from timm.models.beit import gen_relative_position_index +from torch.utils.checkpoint import checkpoint +from typing import Optional + + +def forward_beit(pretrained, x): + return forward_adapted_unflatten(pretrained, x, "forward_features") + + +def patch_embed_forward(self, x): + """ + Modification of timm.models.layers.patch_embed.py: PatchEmbed.forward to support arbitrary window sizes. + """ + x = self.proj(x) + if self.flatten: + x = x.flatten(2).transpose(1, 2) + x = self.norm(x) + return x + + +def _get_rel_pos_bias(self, window_size): + """ + Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes. + """ + old_height = 2 * self.window_size[0] - 1 + old_width = 2 * self.window_size[1] - 1 + + new_height = 2 * window_size[0] - 1 + new_width = 2 * window_size[1] - 1 + + old_relative_position_bias_table = self.relative_position_bias_table + + old_num_relative_distance = self.num_relative_distance + new_num_relative_distance = new_height * new_width + 3 + + old_sub_table = old_relative_position_bias_table[:old_num_relative_distance - 3] + + old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2) + new_sub_table = F.interpolate(old_sub_table, size=(int(new_height), int(new_width)), mode="bilinear") + new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1) + + new_relative_position_bias_table = torch.cat( + [new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3:]]) + + key = str(window_size[1]) + "," + str(window_size[0]) + if key not in self.relative_position_indices.keys(): + self.relative_position_indices[key] = gen_relative_position_index(window_size) + + relative_position_bias = new_relative_position_bias_table[ + self.relative_position_indices[key].view(-1)].view( + window_size[0] * window_size[1] + 1, + window_size[0] * window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + return relative_position_bias.unsqueeze(0) + + +def attention_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.Tensor] = None): + """ + Modification of timm.models.beit.py: Attention.forward to support arbitrary window sizes. + """ + B, N, C = x.shape + + qkv_bias = torch.cat((self.q_bias, self.k_bias, self.v_bias)) if self.q_bias is not None else None + qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) + qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) + + q = q * self.scale + attn = (q @ k.transpose(-2, -1)) + + if self.relative_position_bias_table is not None: + window_size = tuple(np.array(resolution) // 16) + attn = attn + self._get_rel_pos_bias(window_size) + if shared_rel_pos_bias is not None: + attn = attn + shared_rel_pos_bias + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, -1) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +def block_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.Tensor] = None): + """ + Modification of timm.models.beit.py: Block.forward to support arbitrary window sizes. + """ + if self.gamma_1 is None: + x = x + self.drop_path(self.attn(self.norm1(x), resolution, shared_rel_pos_bias=shared_rel_pos_bias)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + else: + x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), resolution, + shared_rel_pos_bias=shared_rel_pos_bias)) + x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) + return x + + +def beit_forward_features(self, x): + """ + Modification of timm.models.beit.py: Beit.forward_features to support arbitrary window sizes. + """ + resolution = x.shape[2:] + + x = self.patch_embed(x) + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + if self.pos_embed is not None: + x = x + self.pos_embed + x = self.pos_drop(x) + + rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None + for blk in self.blocks: + if self.grad_checkpointing and not torch.jit.is_scripting(): + x = checkpoint(blk, x, shared_rel_pos_bias=rel_pos_bias) + else: + x = blk(x, resolution, shared_rel_pos_bias=rel_pos_bias) + x = self.norm(x) + return x + + +def _make_beit_backbone( + model, + features=[96, 192, 384, 768], + size=[384, 384], + hooks=[0, 4, 8, 11], + vit_features=768, + use_readout="ignore", + start_index=1, + start_index_readout=1, +): + backbone = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index, + start_index_readout) + + backbone.model.patch_embed.forward = types.MethodType(patch_embed_forward, backbone.model.patch_embed) + backbone.model.forward_features = types.MethodType(beit_forward_features, backbone.model) + + for block in backbone.model.blocks: + attn = block.attn + attn._get_rel_pos_bias = types.MethodType(_get_rel_pos_bias, attn) + attn.forward = types.MethodType(attention_forward, attn) + attn.relative_position_indices = {} + + block.forward = types.MethodType(block_forward, block) + + return backbone + + +def _make_pretrained_beitl16_512(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("beit_large_patch16_512", pretrained=pretrained) + + hooks = [5, 11, 17, 23] if hooks is None else hooks + + features = [256, 512, 1024, 1024] + + return _make_beit_backbone( + model, + features=features, + size=[512, 512], + hooks=hooks, + vit_features=1024, + use_readout=use_readout, + ) + + +def _make_pretrained_beitl16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("beit_large_patch16_384", pretrained=pretrained) + + hooks = [5, 11, 17, 23] if hooks is None else hooks + return _make_beit_backbone( + model, + features=[256, 512, 1024, 1024], + hooks=hooks, + vit_features=1024, + use_readout=use_readout, + ) + + +def _make_pretrained_beitb16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("beit_base_patch16_384", pretrained=pretrained) + + hooks = [2, 5, 8, 11] if hooks is None else hooks + return _make_beit_backbone( + model, + features=[96, 192, 384, 768], + hooks=hooks, + use_readout=use_readout, + ) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/levit.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/levit.py new file mode 100644 index 0000000000000000000000000000000000000000..6d023a98702a0451806d26f33f8bccf931814f10 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/levit.py @@ -0,0 +1,106 @@ +import timm +import torch +import torch.nn as nn +import numpy as np + +from .utils import activations, get_activation, Transpose + + +def forward_levit(pretrained, x): + pretrained.model.forward_features(x) + + layer_1 = pretrained.activations["1"] + layer_2 = pretrained.activations["2"] + layer_3 = pretrained.activations["3"] + + layer_1 = pretrained.act_postprocess1(layer_1) + layer_2 = pretrained.act_postprocess2(layer_2) + layer_3 = pretrained.act_postprocess3(layer_3) + + return layer_1, layer_2, layer_3 + + +def _make_levit_backbone( + model, + hooks=[3, 11, 21], + patch_grid=[14, 14] +): + pretrained = nn.Module() + + pretrained.model = model + pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1")) + pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2")) + pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3")) + + pretrained.activations = activations + + patch_grid_size = np.array(patch_grid, dtype=int) + + pretrained.act_postprocess1 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size(patch_grid_size.tolist())) + ) + pretrained.act_postprocess2 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size((np.ceil(patch_grid_size / 2).astype(int)).tolist())) + ) + pretrained.act_postprocess3 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size((np.ceil(patch_grid_size / 4).astype(int)).tolist())) + ) + + return pretrained + + +class ConvTransposeNorm(nn.Sequential): + """ + Modification of + https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: ConvNorm + such that ConvTranspose2d is used instead of Conv2d. + """ + + def __init__( + self, in_chs, out_chs, kernel_size=1, stride=1, pad=0, dilation=1, + groups=1, bn_weight_init=1): + super().__init__() + self.add_module('c', + nn.ConvTranspose2d(in_chs, out_chs, kernel_size, stride, pad, dilation, groups, bias=False)) + self.add_module('bn', nn.BatchNorm2d(out_chs)) + + nn.init.constant_(self.bn.weight, bn_weight_init) + + @torch.no_grad() + def fuse(self): + c, bn = self._modules.values() + w = bn.weight / (bn.running_var + bn.eps) ** 0.5 + w = c.weight * w[:, None, None, None] + b = bn.bias - bn.running_mean * bn.weight / (bn.running_var + bn.eps) ** 0.5 + m = nn.ConvTranspose2d( + w.size(1), w.size(0), w.shape[2:], stride=self.c.stride, + padding=self.c.padding, dilation=self.c.dilation, groups=self.c.groups) + m.weight.data.copy_(w) + m.bias.data.copy_(b) + return m + + +def stem_b4_transpose(in_chs, out_chs, activation): + """ + Modification of + https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16 + such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half. + """ + return nn.Sequential( + ConvTransposeNorm(in_chs, out_chs, 3, 2, 1), + activation(), + ConvTransposeNorm(out_chs, out_chs // 2, 3, 2, 1), + activation()) + + +def _make_pretrained_levit_384(pretrained, hooks=None): + model = timm.create_model("levit_384", pretrained=pretrained) + + hooks = [3, 11, 21] if hooks == None else hooks + return _make_levit_backbone( + model, + hooks=hooks + ) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/next_vit.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/next_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..8afdd8b743b5ab023a359dc3b721e601b1a40d11 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/next_vit.py @@ -0,0 +1,39 @@ +import timm + +import torch.nn as nn + +from pathlib import Path +from .utils import activations, forward_default, get_activation + +from ..external.next_vit.classification.nextvit import * + + +def forward_next_vit(pretrained, x): + return forward_default(pretrained, x, "forward") + + +def _make_next_vit_backbone( + model, + hooks=[2, 6, 36, 39], +): + pretrained = nn.Module() + + pretrained.model = model + pretrained.model.features[hooks[0]].register_forward_hook(get_activation("1")) + pretrained.model.features[hooks[1]].register_forward_hook(get_activation("2")) + pretrained.model.features[hooks[2]].register_forward_hook(get_activation("3")) + pretrained.model.features[hooks[3]].register_forward_hook(get_activation("4")) + + pretrained.activations = activations + + return pretrained + + +def _make_pretrained_next_vit_large_6m(hooks=None): + model = timm.create_model("nextvit_large") + + hooks = [2, 6, 36, 39] if hooks == None else hooks + return _make_next_vit_backbone( + model, + hooks=hooks, + ) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c71367e3e78b087f80b2ab3e2f495a9c372f1a --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin.py @@ -0,0 +1,13 @@ +import timm + +from .swin_common import _make_swin_backbone + + +def _make_pretrained_swinl12_384(pretrained, hooks=None): + model = timm.create_model("swin_large_patch4_window12_384", pretrained=pretrained) + + hooks = [1, 1, 17, 1] if hooks == None else hooks + return _make_swin_backbone( + model, + hooks=hooks + ) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin2.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin2.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4c8f1d6fc1807a207dc6b9a261c6f7b14a87a3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin2.py @@ -0,0 +1,34 @@ +import timm + +from .swin_common import _make_swin_backbone + + +def _make_pretrained_swin2l24_384(pretrained, hooks=None): + model = timm.create_model("swinv2_large_window12to24_192to384_22kft1k", pretrained=pretrained) + + hooks = [1, 1, 17, 1] if hooks == None else hooks + return _make_swin_backbone( + model, + hooks=hooks + ) + + +def _make_pretrained_swin2b24_384(pretrained, hooks=None): + model = timm.create_model("swinv2_base_window12to24_192to384_22kft1k", pretrained=pretrained) + + hooks = [1, 1, 17, 1] if hooks == None else hooks + return _make_swin_backbone( + model, + hooks=hooks + ) + + +def _make_pretrained_swin2t16_256(pretrained, hooks=None): + model = timm.create_model("swinv2_tiny_window16_256", pretrained=pretrained) + + hooks = [1, 1, 5, 1] if hooks == None else hooks + return _make_swin_backbone( + model, + hooks=hooks, + patch_grid=[64, 64] + ) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin_common.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin_common.py new file mode 100644 index 0000000000000000000000000000000000000000..94d63d408f18511179d90b3ac6f697385d1e556d --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin_common.py @@ -0,0 +1,52 @@ +import torch + +import torch.nn as nn +import numpy as np + +from .utils import activations, forward_default, get_activation, Transpose + + +def forward_swin(pretrained, x): + return forward_default(pretrained, x) + + +def _make_swin_backbone( + model, + hooks=[1, 1, 17, 1], + patch_grid=[96, 96] +): + pretrained = nn.Module() + + pretrained.model = model + pretrained.model.layers[0].blocks[hooks[0]].register_forward_hook(get_activation("1")) + pretrained.model.layers[1].blocks[hooks[1]].register_forward_hook(get_activation("2")) + pretrained.model.layers[2].blocks[hooks[2]].register_forward_hook(get_activation("3")) + pretrained.model.layers[3].blocks[hooks[3]].register_forward_hook(get_activation("4")) + + pretrained.activations = activations + + if hasattr(model, "patch_grid"): + used_patch_grid = model.patch_grid + else: + used_patch_grid = patch_grid + + patch_grid_size = np.array(used_patch_grid, dtype=int) + + pretrained.act_postprocess1 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size(patch_grid_size.tolist())) + ) + pretrained.act_postprocess2 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size((patch_grid_size // 2).tolist())) + ) + pretrained.act_postprocess3 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size((patch_grid_size // 4).tolist())) + ) + pretrained.act_postprocess4 = nn.Sequential( + Transpose(1, 2), + nn.Unflatten(2, torch.Size((patch_grid_size // 8).tolist())) + ) + + return pretrained diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/utils.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0558899dddcfccec5f01a764d4f21738eb612149 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/utils.py @@ -0,0 +1,249 @@ +import torch + +import torch.nn as nn + + +class Slice(nn.Module): + def __init__(self, start_index=1): + super(Slice, self).__init__() + self.start_index = start_index + + def forward(self, x): + return x[:, self.start_index:] + + +class AddReadout(nn.Module): + def __init__(self, start_index=1): + super(AddReadout, self).__init__() + self.start_index = start_index + + def forward(self, x): + if self.start_index == 2: + readout = (x[:, 0] + x[:, 1]) / 2 + else: + readout = x[:, 0] + return x[:, self.start_index:] + readout.unsqueeze(1) + + +class ProjectReadout(nn.Module): + def __init__(self, in_features, start_index=1): + super(ProjectReadout, self).__init__() + self.start_index = start_index + + self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU()) + + def forward(self, x): + readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index:]) + features = torch.cat((x[:, self.start_index:], readout), -1) + + return self.project(features) + + +class Transpose(nn.Module): + def __init__(self, dim0, dim1): + super(Transpose, self).__init__() + self.dim0 = dim0 + self.dim1 = dim1 + + def forward(self, x): + x = x.transpose(self.dim0, self.dim1) + return x + + +activations = {} + + +def get_activation(name): + def hook(model, input, output): + activations[name] = output + + return hook + + +def forward_default(pretrained, x, function_name="forward_features"): + exec(f"pretrained.model.{function_name}(x)") + + layer_1 = pretrained.activations["1"] + layer_2 = pretrained.activations["2"] + layer_3 = pretrained.activations["3"] + layer_4 = pretrained.activations["4"] + + if hasattr(pretrained, "act_postprocess1"): + layer_1 = pretrained.act_postprocess1(layer_1) + if hasattr(pretrained, "act_postprocess2"): + layer_2 = pretrained.act_postprocess2(layer_2) + if hasattr(pretrained, "act_postprocess3"): + layer_3 = pretrained.act_postprocess3(layer_3) + if hasattr(pretrained, "act_postprocess4"): + layer_4 = pretrained.act_postprocess4(layer_4) + + return layer_1, layer_2, layer_3, layer_4 + + +def forward_adapted_unflatten(pretrained, x, function_name="forward_features"): + b, c, h, w = x.shape + + exec(f"glob = pretrained.model.{function_name}(x)") + + layer_1 = pretrained.activations["1"] + layer_2 = pretrained.activations["2"] + layer_3 = pretrained.activations["3"] + layer_4 = pretrained.activations["4"] + + layer_1 = pretrained.act_postprocess1[0:2](layer_1) + layer_2 = pretrained.act_postprocess2[0:2](layer_2) + layer_3 = pretrained.act_postprocess3[0:2](layer_3) + layer_4 = pretrained.act_postprocess4[0:2](layer_4) + + unflatten = nn.Sequential( + nn.Unflatten( + 2, + torch.Size( + [ + h // pretrained.model.patch_size[1], + w // pretrained.model.patch_size[0], + ] + ), + ) + ) + + if layer_1.ndim == 3: + layer_1 = unflatten(layer_1) + if layer_2.ndim == 3: + layer_2 = unflatten(layer_2) + if layer_3.ndim == 3: + layer_3 = unflatten(layer_3) + if layer_4.ndim == 3: + layer_4 = unflatten(layer_4) + + layer_1 = pretrained.act_postprocess1[3: len(pretrained.act_postprocess1)](layer_1) + layer_2 = pretrained.act_postprocess2[3: len(pretrained.act_postprocess2)](layer_2) + layer_3 = pretrained.act_postprocess3[3: len(pretrained.act_postprocess3)](layer_3) + layer_4 = pretrained.act_postprocess4[3: len(pretrained.act_postprocess4)](layer_4) + + return layer_1, layer_2, layer_3, layer_4 + + +def get_readout_oper(vit_features, features, use_readout, start_index=1): + if use_readout == "ignore": + readout_oper = [Slice(start_index)] * len(features) + elif use_readout == "add": + readout_oper = [AddReadout(start_index)] * len(features) + elif use_readout == "project": + readout_oper = [ + ProjectReadout(vit_features, start_index) for out_feat in features + ] + else: + assert ( + False + ), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'" + + return readout_oper + + +def make_backbone_default( + model, + features=[96, 192, 384, 768], + size=[384, 384], + hooks=[2, 5, 8, 11], + vit_features=768, + use_readout="ignore", + start_index=1, + start_index_readout=1, +): + pretrained = nn.Module() + + pretrained.model = model + pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1")) + pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2")) + pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3")) + pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4")) + + pretrained.activations = activations + + readout_oper = get_readout_oper(vit_features, features, use_readout, start_index_readout) + + # 32, 48, 136, 384 + pretrained.act_postprocess1 = nn.Sequential( + readout_oper[0], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[0], + kernel_size=1, + stride=1, + padding=0, + ), + nn.ConvTranspose2d( + in_channels=features[0], + out_channels=features[0], + kernel_size=4, + stride=4, + padding=0, + bias=True, + dilation=1, + groups=1, + ), + ) + + pretrained.act_postprocess2 = nn.Sequential( + readout_oper[1], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[1], + kernel_size=1, + stride=1, + padding=0, + ), + nn.ConvTranspose2d( + in_channels=features[1], + out_channels=features[1], + kernel_size=2, + stride=2, + padding=0, + bias=True, + dilation=1, + groups=1, + ), + ) + + pretrained.act_postprocess3 = nn.Sequential( + readout_oper[2], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[2], + kernel_size=1, + stride=1, + padding=0, + ), + ) + + pretrained.act_postprocess4 = nn.Sequential( + readout_oper[3], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[3], + kernel_size=1, + stride=1, + padding=0, + ), + nn.Conv2d( + in_channels=features[3], + out_channels=features[3], + kernel_size=3, + stride=2, + padding=1, + ), + ) + + pretrained.model.start_index = start_index + pretrained.model.patch_size = [16, 16] + + return pretrained diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/vit.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..413f9693bd4548342280e329c9128c1a52cea920 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/vit.py @@ -0,0 +1,221 @@ +import torch +import torch.nn as nn +import timm +import types +import math +import torch.nn.functional as F + +from .utils import (activations, forward_adapted_unflatten, get_activation, get_readout_oper, + make_backbone_default, Transpose) + + +def forward_vit(pretrained, x): + return forward_adapted_unflatten(pretrained, x, "forward_flex") + + +def _resize_pos_embed(self, posemb, gs_h, gs_w): + posemb_tok, posemb_grid = ( + posemb[:, : self.start_index], + posemb[0, self.start_index:], + ) + + gs_old = int(math.sqrt(len(posemb_grid))) + + posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) + posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear") + posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1) + + posemb = torch.cat([posemb_tok, posemb_grid], dim=1) + + return posemb + + +def forward_flex(self, x): + b, c, h, w = x.shape + + pos_embed = self._resize_pos_embed( + self.pos_embed, h // self.patch_size[1], w // self.patch_size[0] + ) + + B = x.shape[0] + + if hasattr(self.patch_embed, "backbone"): + x = self.patch_embed.backbone(x) + if isinstance(x, (list, tuple)): + x = x[-1] # last feature if backbone outputs list/tuple of features + + x = self.patch_embed.proj(x).flatten(2).transpose(1, 2) + + if getattr(self, "dist_token", None) is not None: + cls_tokens = self.cls_token.expand( + B, -1, -1 + ) # stole cls_tokens impl from Phil Wang, thanks + dist_token = self.dist_token.expand(B, -1, -1) + x = torch.cat((cls_tokens, dist_token, x), dim=1) + else: + if self.no_embed_class: + x = x + pos_embed + cls_tokens = self.cls_token.expand( + B, -1, -1 + ) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + if not self.no_embed_class: + x = x + pos_embed + x = self.pos_drop(x) + + for blk in self.blocks: + x = blk(x) + + x = self.norm(x) + + return x + + +def _make_vit_b16_backbone( + model, + features=[96, 192, 384, 768], + size=[384, 384], + hooks=[2, 5, 8, 11], + vit_features=768, + use_readout="ignore", + start_index=1, + start_index_readout=1, +): + pretrained = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index, + start_index_readout) + + # We inject this function into the VisionTransformer instances so that + # we can use it with interpolated position embeddings without modifying the library source. + pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model) + pretrained.model._resize_pos_embed = types.MethodType( + _resize_pos_embed, pretrained.model + ) + + return pretrained + + +def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("vit_large_patch16_384", pretrained=pretrained) + + hooks = [5, 11, 17, 23] if hooks == None else hooks + return _make_vit_b16_backbone( + model, + features=[256, 512, 1024, 1024], + hooks=hooks, + vit_features=1024, + use_readout=use_readout, + ) + + +def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("vit_base_patch16_384", pretrained=pretrained) + + hooks = [2, 5, 8, 11] if hooks == None else hooks + return _make_vit_b16_backbone( + model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout + ) + + +def _make_vit_b_rn50_backbone( + model, + features=[256, 512, 768, 768], + size=[384, 384], + hooks=[0, 1, 8, 11], + vit_features=768, + patch_size=[16, 16], + number_stages=2, + use_vit_only=False, + use_readout="ignore", + start_index=1, +): + pretrained = nn.Module() + + pretrained.model = model + + used_number_stages = 0 if use_vit_only else number_stages + for s in range(used_number_stages): + pretrained.model.patch_embed.backbone.stages[s].register_forward_hook( + get_activation(str(s + 1)) + ) + for s in range(used_number_stages, 4): + pretrained.model.blocks[hooks[s]].register_forward_hook(get_activation(str(s + 1))) + + pretrained.activations = activations + + readout_oper = get_readout_oper(vit_features, features, use_readout, start_index) + + for s in range(used_number_stages): + value = nn.Sequential(nn.Identity(), nn.Identity(), nn.Identity()) + exec(f"pretrained.act_postprocess{s + 1}=value") + for s in range(used_number_stages, 4): + if s < number_stages: + final_layer = nn.ConvTranspose2d( + in_channels=features[s], + out_channels=features[s], + kernel_size=4 // (2 ** s), + stride=4 // (2 ** s), + padding=0, + bias=True, + dilation=1, + groups=1, + ) + elif s > number_stages: + final_layer = nn.Conv2d( + in_channels=features[3], + out_channels=features[3], + kernel_size=3, + stride=2, + padding=1, + ) + else: + final_layer = None + + layers = [ + readout_oper[s], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[s], + kernel_size=1, + stride=1, + padding=0, + ), + ] + if final_layer is not None: + layers.append(final_layer) + + value = nn.Sequential(*layers) + exec(f"pretrained.act_postprocess{s + 1}=value") + + pretrained.model.start_index = start_index + pretrained.model.patch_size = patch_size + + # We inject this function into the VisionTransformer instances so that + # we can use it with interpolated position embeddings without modifying the library source. + pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model) + + # We inject this function into the VisionTransformer instances so that + # we can use it with interpolated position embeddings without modifying the library source. + pretrained.model._resize_pos_embed = types.MethodType( + _resize_pos_embed, pretrained.model + ) + + return pretrained + + +def _make_pretrained_vitb_rn50_384( + pretrained, use_readout="ignore", hooks=None, use_vit_only=False +): + model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained) + + hooks = [0, 1, 8, 11] if hooks == None else hooks + return _make_vit_b_rn50_backbone( + model, + features=[256, 512, 768, 768], + size=[384, 384], + hooks=hooks, + use_vit_only=use_vit_only, + use_readout=use_readout, + ) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/base_model.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..5cf430239b47ec5ec07531263f26f5c24a2311cd --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/base_model.py @@ -0,0 +1,16 @@ +import torch + + +class BaseModel(torch.nn.Module): + def load(self, path): + """Load model from file. + + Args: + path (str): file path + """ + parameters = torch.load(path, map_location=torch.device('cpu')) + + if "optimizer" in parameters: + parameters = parameters["model"] + + self.load_state_dict(parameters) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/blocks.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..6d87a00680bb6ed9a6d7c3043ea30a1e90361794 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/blocks.py @@ -0,0 +1,439 @@ +import torch +import torch.nn as nn + +from .backbones.beit import ( + _make_pretrained_beitl16_512, + _make_pretrained_beitl16_384, + _make_pretrained_beitb16_384, + forward_beit, +) +from .backbones.swin_common import ( + forward_swin, +) +from .backbones.swin2 import ( + _make_pretrained_swin2l24_384, + _make_pretrained_swin2b24_384, + _make_pretrained_swin2t16_256, +) +from .backbones.swin import ( + _make_pretrained_swinl12_384, +) +from .backbones.levit import ( + _make_pretrained_levit_384, + forward_levit, +) +from .backbones.vit import ( + _make_pretrained_vitb_rn50_384, + _make_pretrained_vitl16_384, + _make_pretrained_vitb16_384, + forward_vit, +) + +def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, + use_vit_only=False, use_readout="ignore", in_features=[96, 256, 512, 1024]): + if backbone == "beitl16_512": + pretrained = _make_pretrained_beitl16_512( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [256, 512, 1024, 1024], features, groups=groups, expand=expand + ) # BEiT_512-L (backbone) + elif backbone == "beitl16_384": + pretrained = _make_pretrained_beitl16_384( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [256, 512, 1024, 1024], features, groups=groups, expand=expand + ) # BEiT_384-L (backbone) + elif backbone == "beitb16_384": + pretrained = _make_pretrained_beitb16_384( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [96, 192, 384, 768], features, groups=groups, expand=expand + ) # BEiT_384-B (backbone) + elif backbone == "swin2l24_384": + pretrained = _make_pretrained_swin2l24_384( + use_pretrained, hooks=hooks + ) + scratch = _make_scratch( + [192, 384, 768, 1536], features, groups=groups, expand=expand + ) # Swin2-L/12to24 (backbone) + elif backbone == "swin2b24_384": + pretrained = _make_pretrained_swin2b24_384( + use_pretrained, hooks=hooks + ) + scratch = _make_scratch( + [128, 256, 512, 1024], features, groups=groups, expand=expand + ) # Swin2-B/12to24 (backbone) + elif backbone == "swin2t16_256": + pretrained = _make_pretrained_swin2t16_256( + use_pretrained, hooks=hooks + ) + scratch = _make_scratch( + [96, 192, 384, 768], features, groups=groups, expand=expand + ) # Swin2-T/16 (backbone) + elif backbone == "swinl12_384": + pretrained = _make_pretrained_swinl12_384( + use_pretrained, hooks=hooks + ) + scratch = _make_scratch( + [192, 384, 768, 1536], features, groups=groups, expand=expand + ) # Swin-L/12 (backbone) + elif backbone == "next_vit_large_6m": + from .backbones.next_vit import _make_pretrained_next_vit_large_6m + pretrained = _make_pretrained_next_vit_large_6m(hooks=hooks) + scratch = _make_scratch( + in_features, features, groups=groups, expand=expand + ) # Next-ViT-L on ImageNet-1K-6M (backbone) + elif backbone == "levit_384": + pretrained = _make_pretrained_levit_384( + use_pretrained, hooks=hooks + ) + scratch = _make_scratch( + [384, 512, 768], features, groups=groups, expand=expand + ) # LeViT 384 (backbone) + elif backbone == "vitl16_384": + pretrained = _make_pretrained_vitl16_384( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [256, 512, 1024, 1024], features, groups=groups, expand=expand + ) # ViT-L/16 - 85.0% Top1 (backbone) + elif backbone == "vitb_rn50_384": + pretrained = _make_pretrained_vitb_rn50_384( + use_pretrained, + hooks=hooks, + use_vit_only=use_vit_only, + use_readout=use_readout, + ) + scratch = _make_scratch( + [256, 512, 768, 768], features, groups=groups, expand=expand + ) # ViT-H/16 - 85.0% Top1 (backbone) + elif backbone == "vitb16_384": + pretrained = _make_pretrained_vitb16_384( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [96, 192, 384, 768], features, groups=groups, expand=expand + ) # ViT-B/16 - 84.6% Top1 (backbone) + elif backbone == "resnext101_wsl": + pretrained = _make_pretrained_resnext101_wsl(use_pretrained) + scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3 + elif backbone == "efficientnet_lite3": + pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable) + scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3 + else: + print(f"Backbone '{backbone}' not implemented") + assert False + + return pretrained, scratch + + +def _make_scratch(in_shape, out_shape, groups=1, expand=False): + scratch = nn.Module() + + out_shape1 = out_shape + out_shape2 = out_shape + out_shape3 = out_shape + if len(in_shape) >= 4: + out_shape4 = out_shape + + if expand: + out_shape1 = out_shape + out_shape2 = out_shape*2 + out_shape3 = out_shape*4 + if len(in_shape) >= 4: + out_shape4 = out_shape*8 + + scratch.layer1_rn = nn.Conv2d( + in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer2_rn = nn.Conv2d( + in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer3_rn = nn.Conv2d( + in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + if len(in_shape) >= 4: + scratch.layer4_rn = nn.Conv2d( + in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + + return scratch + + +def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False): + efficientnet = torch.hub.load( + "rwightman/gen-efficientnet-pytorch", + "tf_efficientnet_lite3", + pretrained=use_pretrained, + exportable=exportable + ) + return _make_efficientnet_backbone(efficientnet) + + +def _make_efficientnet_backbone(effnet): + pretrained = nn.Module() + + pretrained.layer1 = nn.Sequential( + effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2] + ) + pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3]) + pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5]) + pretrained.layer4 = nn.Sequential(*effnet.blocks[5:9]) + + return pretrained + + +def _make_resnet_backbone(resnet): + pretrained = nn.Module() + pretrained.layer1 = nn.Sequential( + resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1 + ) + + pretrained.layer2 = resnet.layer2 + pretrained.layer3 = resnet.layer3 + pretrained.layer4 = resnet.layer4 + + return pretrained + + +def _make_pretrained_resnext101_wsl(use_pretrained): + resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl") + return _make_resnet_backbone(resnet) + + + +class Interpolate(nn.Module): + """Interpolation module. + """ + + def __init__(self, scale_factor, mode, align_corners=False): + """Init. + + Args: + scale_factor (float): scaling + mode (str): interpolation mode + """ + super(Interpolate, self).__init__() + + self.interp = nn.functional.interpolate + self.scale_factor = scale_factor + self.mode = mode + self.align_corners = align_corners + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: interpolated data + """ + + x = self.interp( + x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners + ) + + return x + + +class ResidualConvUnit(nn.Module): + """Residual convolution module. + """ + + def __init__(self, features): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.conv1 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True + ) + + self.conv2 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True + ) + + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + out = self.relu(x) + out = self.conv1(out) + out = self.relu(out) + out = self.conv2(out) + + return out + x + + +class FeatureFusionBlock(nn.Module): + """Feature fusion block. + """ + + def __init__(self, features): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock, self).__init__() + + self.resConfUnit1 = ResidualConvUnit(features) + self.resConfUnit2 = ResidualConvUnit(features) + + def forward(self, *xs): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if len(xs) == 2: + output += self.resConfUnit1(xs[1]) + + output = self.resConfUnit2(output) + + output = nn.functional.interpolate( + output, scale_factor=2, mode="bilinear", align_corners=True + ) + + return output + + + + +class ResidualConvUnit_custom(nn.Module): + """Residual convolution module. + """ + + def __init__(self, features, activation, bn): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.bn = bn + + self.groups=1 + + self.conv1 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups + ) + + self.conv2 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups + ) + + if self.bn==True: + self.bn1 = nn.BatchNorm2d(features) + self.bn2 = nn.BatchNorm2d(features) + + self.activation = activation + + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + + out = self.activation(x) + out = self.conv1(out) + if self.bn==True: + out = self.bn1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.bn==True: + out = self.bn2(out) + + if self.groups > 1: + out = self.conv_merge(out) + + return self.skip_add.add(out, x) + + # return out + x + + +class FeatureFusionBlock_custom(nn.Module): + """Feature fusion block. + """ + + def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock_custom, self).__init__() + + self.deconv = deconv + self.align_corners = align_corners + + self.groups=1 + + self.expand = expand + out_features = features + if self.expand==True: + out_features = features//2 + + self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1) + + self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn) + self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn) + + self.skip_add = nn.quantized.FloatFunctional() + + self.size=size + + def forward(self, *xs, size=None): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if len(xs) == 2: + res = self.resConfUnit1(xs[1]) + output = self.skip_add.add(output, res) + # output += res + + output = self.resConfUnit2(output) + + if (size is None) and (self.size is None): + modifier = {"scale_factor": 2} + elif size is None: + modifier = {"size": self.size} + else: + modifier = {"size": size} + + output = nn.functional.interpolate( + output, **modifier, mode="bilinear", align_corners=self.align_corners + ) + + output = self.out_conv(output) + + return output + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/dpt_depth.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/dpt_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..456483dbb806b691dd31eb976411e8f2e0f15a55 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/dpt_depth.py @@ -0,0 +1,166 @@ +import torch +import torch.nn as nn + +from .base_model import BaseModel +from .blocks import ( + FeatureFusionBlock_custom, + Interpolate, + _make_encoder, + forward_beit, + forward_swin, + forward_levit, + forward_vit, +) +from .backbones.levit import stem_b4_transpose +from timm.layers import get_act_layer + + +def _make_fusion_block(features, use_bn, size = None): + return FeatureFusionBlock_custom( + features, + nn.ReLU(False), + deconv=False, + bn=use_bn, + expand=False, + align_corners=True, + size=size, + ) + + +class DPT(BaseModel): + def __init__( + self, + head, + features=256, + backbone="vitb_rn50_384", + readout="project", + channels_last=False, + use_bn=False, + **kwargs + ): + + super(DPT, self).__init__() + + self.channels_last = channels_last + + # For the Swin, Swin 2, LeViT and Next-ViT Transformers, the hierarchical architectures prevent setting the + # hooks freely. Instead, the hooks have to be chosen according to the ranges specified in the comments. + hooks = { + "beitl16_512": [5, 11, 17, 23], + "beitl16_384": [5, 11, 17, 23], + "beitb16_384": [2, 5, 8, 11], + "swin2l24_384": [1, 1, 17, 1], # Allowed ranges: [0, 1], [0, 1], [ 0, 17], [ 0, 1] + "swin2b24_384": [1, 1, 17, 1], # [0, 1], [0, 1], [ 0, 17], [ 0, 1] + "swin2t16_256": [1, 1, 5, 1], # [0, 1], [0, 1], [ 0, 5], [ 0, 1] + "swinl12_384": [1, 1, 17, 1], # [0, 1], [0, 1], [ 0, 17], [ 0, 1] + "next_vit_large_6m": [2, 6, 36, 39], # [0, 2], [3, 6], [ 7, 36], [37, 39] + "levit_384": [3, 11, 21], # [0, 3], [6, 11], [14, 21] + "vitb_rn50_384": [0, 1, 8, 11], + "vitb16_384": [2, 5, 8, 11], + "vitl16_384": [5, 11, 17, 23], + }[backbone] + + if "next_vit" in backbone: + in_features = { + "next_vit_large_6m": [96, 256, 512, 1024], + }[backbone] + else: + in_features = None + + # Instantiate backbone and reassemble blocks + self.pretrained, self.scratch = _make_encoder( + backbone, + features, + False, # Set to true of you want to train from scratch, uses ImageNet weights + groups=1, + expand=False, + exportable=False, + hooks=hooks, + use_readout=readout, + in_features=in_features, + ) + + self.number_layers = len(hooks) if hooks is not None else 4 + size_refinenet3 = None + self.scratch.stem_transpose = None + + if "beit" in backbone: + self.forward_transformer = forward_beit + elif "swin" in backbone: + self.forward_transformer = forward_swin + elif "next_vit" in backbone: + from .backbones.next_vit import forward_next_vit + self.forward_transformer = forward_next_vit + elif "levit" in backbone: + self.forward_transformer = forward_levit + size_refinenet3 = 7 + self.scratch.stem_transpose = stem_b4_transpose(256, 128, get_act_layer("hard_swish")) + else: + self.forward_transformer = forward_vit + + self.scratch.refinenet1 = _make_fusion_block(features, use_bn) + self.scratch.refinenet2 = _make_fusion_block(features, use_bn) + self.scratch.refinenet3 = _make_fusion_block(features, use_bn, size_refinenet3) + if self.number_layers >= 4: + self.scratch.refinenet4 = _make_fusion_block(features, use_bn) + + self.scratch.output_conv = head + + + def forward(self, x): + if self.channels_last == True: + x.contiguous(memory_format=torch.channels_last) + + layers = self.forward_transformer(self.pretrained, x) + if self.number_layers == 3: + layer_1, layer_2, layer_3 = layers + else: + layer_1, layer_2, layer_3, layer_4 = layers + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + if self.number_layers >= 4: + layer_4_rn = self.scratch.layer4_rn(layer_4) + + if self.number_layers == 3: + path_3 = self.scratch.refinenet3(layer_3_rn, size=layer_2_rn.shape[2:]) + else: + path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) + path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:]) + path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:]) + path_1 = self.scratch.refinenet1(path_2, layer_1_rn) + + if self.scratch.stem_transpose is not None: + path_1 = self.scratch.stem_transpose(path_1) + + out = self.scratch.output_conv(path_1) + + return out + + +class DPTDepthModel(DPT): + def __init__(self, path=None, non_negative=True, **kwargs): + features = kwargs["features"] if "features" in kwargs else 256 + head_features_1 = kwargs["head_features_1"] if "head_features_1" in kwargs else features + head_features_2 = kwargs["head_features_2"] if "head_features_2" in kwargs else 32 + kwargs.pop("head_features_1", None) + kwargs.pop("head_features_2", None) + + head = nn.Sequential( + nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1), + Interpolate(scale_factor=2, mode="bilinear", align_corners=True), + nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1), + nn.ReLU(True), + nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0), + nn.ReLU(True) if non_negative else nn.Identity(), + nn.Identity(), + ) + + super().__init__(head, **kwargs) + + if path is not None: + self.load(path) + + def forward(self, x): + return super().forward(x).squeeze(dim=1) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net.py new file mode 100644 index 0000000000000000000000000000000000000000..8a954977800b0a0f48807e80fa63041910e33c1f --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net.py @@ -0,0 +1,76 @@ +"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. +This file contains code that is adapted from +https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py +""" +import torch +import torch.nn as nn + +from .base_model import BaseModel +from .blocks import FeatureFusionBlock, Interpolate, _make_encoder + + +class MidasNet(BaseModel): + """Network for monocular depth estimation. + """ + + def __init__(self, path=None, features=256, non_negative=True): + """Init. + + Args: + path (str, optional): Path to saved model. Defaults to None. + features (int, optional): Number of features. Defaults to 256. + backbone (str, optional): Backbone network for encoder. Defaults to resnet50 + """ + print("Loading weights: ", path) + + super(MidasNet, self).__init__() + + use_pretrained = False if path is None else True + + self.pretrained, self.scratch = _make_encoder(backbone="resnext101_wsl", features=features, use_pretrained=use_pretrained) + + self.scratch.refinenet4 = FeatureFusionBlock(features) + self.scratch.refinenet3 = FeatureFusionBlock(features) + self.scratch.refinenet2 = FeatureFusionBlock(features) + self.scratch.refinenet1 = FeatureFusionBlock(features) + + self.scratch.output_conv = nn.Sequential( + nn.Conv2d(features, 128, kernel_size=3, stride=1, padding=1), + Interpolate(scale_factor=2, mode="bilinear"), + nn.Conv2d(128, 32, kernel_size=3, stride=1, padding=1), + nn.ReLU(True), + nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), + nn.ReLU(True) if non_negative else nn.Identity(), + ) + + if path: + self.load(path) + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input data (image) + + Returns: + tensor: depth + """ + + layer_1 = self.pretrained.layer1(x) + layer_2 = self.pretrained.layer2(layer_1) + layer_3 = self.pretrained.layer3(layer_2) + layer_4 = self.pretrained.layer4(layer_3) + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + path_4 = self.scratch.refinenet4(layer_4_rn) + path_3 = self.scratch.refinenet3(path_4, layer_3_rn) + path_2 = self.scratch.refinenet2(path_3, layer_2_rn) + path_1 = self.scratch.refinenet1(path_2, layer_1_rn) + + out = self.scratch.output_conv(path_1) + + return torch.squeeze(out, dim=1) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net_custom.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net_custom.py new file mode 100644 index 0000000000000000000000000000000000000000..50e4acb5e53d5fabefe3dde16ab49c33c2b7797c --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net_custom.py @@ -0,0 +1,128 @@ +"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. +This file contains code that is adapted from +https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py +""" +import torch +import torch.nn as nn + +from .base_model import BaseModel +from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder + + +class MidasNet_small(BaseModel): + """Network for monocular depth estimation. + """ + + def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negative=True, exportable=True, channels_last=False, align_corners=True, + blocks={'expand': True}): + """Init. + + Args: + path (str, optional): Path to saved model. Defaults to None. + features (int, optional): Number of features. Defaults to 256. + backbone (str, optional): Backbone network for encoder. Defaults to resnet50 + """ + print("Loading weights: ", path) + + super(MidasNet_small, self).__init__() + + use_pretrained = False if path else True + + self.channels_last = channels_last + self.blocks = blocks + self.backbone = backbone + + self.groups = 1 + + features1=features + features2=features + features3=features + features4=features + self.expand = False + if "expand" in self.blocks and self.blocks['expand'] == True: + self.expand = True + features1=features + features2=features*2 + features3=features*4 + features4=features*8 + + self.pretrained, self.scratch = _make_encoder(self.backbone, features, use_pretrained, groups=self.groups, expand=self.expand, exportable=exportable) + + self.scratch.activation = nn.ReLU(False) + + self.scratch.refinenet4 = FeatureFusionBlock_custom(features4, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) + self.scratch.refinenet3 = FeatureFusionBlock_custom(features3, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) + self.scratch.refinenet2 = FeatureFusionBlock_custom(features2, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) + self.scratch.refinenet1 = FeatureFusionBlock_custom(features1, self.scratch.activation, deconv=False, bn=False, align_corners=align_corners) + + + self.scratch.output_conv = nn.Sequential( + nn.Conv2d(features, features//2, kernel_size=3, stride=1, padding=1, groups=self.groups), + Interpolate(scale_factor=2, mode="bilinear"), + nn.Conv2d(features//2, 32, kernel_size=3, stride=1, padding=1), + self.scratch.activation, + nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), + nn.ReLU(True) if non_negative else nn.Identity(), + nn.Identity(), + ) + + if path: + self.load(path) + + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input data (image) + + Returns: + tensor: depth + """ + if self.channels_last==True: + print("self.channels_last = ", self.channels_last) + x.contiguous(memory_format=torch.channels_last) + + + layer_1 = self.pretrained.layer1(x) + layer_2 = self.pretrained.layer2(layer_1) + layer_3 = self.pretrained.layer3(layer_2) + layer_4 = self.pretrained.layer4(layer_3) + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + + path_4 = self.scratch.refinenet4(layer_4_rn) + path_3 = self.scratch.refinenet3(path_4, layer_3_rn) + path_2 = self.scratch.refinenet2(path_3, layer_2_rn) + path_1 = self.scratch.refinenet1(path_2, layer_1_rn) + + out = self.scratch.output_conv(path_1) + + return torch.squeeze(out, dim=1) + + + +def fuse_model(m): + prev_previous_type = nn.Identity() + prev_previous_name = '' + previous_type = nn.Identity() + previous_name = '' + for name, module in m.named_modules(): + if prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d and type(module) == nn.ReLU: + # print("FUSED ", prev_previous_name, previous_name, name) + torch.quantization.fuse_modules(m, [prev_previous_name, previous_name, name], inplace=True) + elif prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d: + # print("FUSED ", prev_previous_name, previous_name) + torch.quantization.fuse_modules(m, [prev_previous_name, previous_name], inplace=True) + # elif previous_type == nn.Conv2d and type(module) == nn.ReLU: + # print("FUSED ", previous_name, name) + # torch.quantization.fuse_modules(m, [previous_name, name], inplace=True) + + prev_previous_type = previous_type + prev_previous_name = previous_name + previous_type = type(module) + previous_name = name \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/model_loader.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/model_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cd1f2d43054bfd3d650587c7b2ed35f1347c9e --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/model_loader.py @@ -0,0 +1,242 @@ +import cv2 +import torch + +from midas.dpt_depth import DPTDepthModel +from midas.midas_net import MidasNet +from midas.midas_net_custom import MidasNet_small +from midas.transforms import Resize, NormalizeImage, PrepareForNet + +from torchvision.transforms import Compose + +default_models = { + "dpt_beit_large_512": "weights/dpt_beit_large_512.pt", + "dpt_beit_large_384": "weights/dpt_beit_large_384.pt", + "dpt_beit_base_384": "weights/dpt_beit_base_384.pt", + "dpt_swin2_large_384": "weights/dpt_swin2_large_384.pt", + "dpt_swin2_base_384": "weights/dpt_swin2_base_384.pt", + "dpt_swin2_tiny_256": "weights/dpt_swin2_tiny_256.pt", + "dpt_swin_large_384": "weights/dpt_swin_large_384.pt", + "dpt_next_vit_large_384": "weights/dpt_next_vit_large_384.pt", + "dpt_levit_224": "weights/dpt_levit_224.pt", + "dpt_large_384": "weights/dpt_large_384.pt", + "dpt_hybrid_384": "weights/dpt_hybrid_384.pt", + "midas_v21_384": "weights/midas_v21_384.pt", + "midas_v21_small_256": "weights/midas_v21_small_256.pt", + "openvino_midas_v21_small_256": "weights/openvino_midas_v21_small_256.xml", +} + + +def load_model(device, model_path, model_type="dpt_large_384", optimize=True, height=None, square=False): + """Load the specified network. + + Args: + device (device): the torch device used + model_path (str): path to saved model + model_type (str): the type of the model to be loaded + optimize (bool): optimize the model to half-integer on CUDA? + height (int): inference encoder image height + square (bool): resize to a square resolution? + + Returns: + The loaded network, the transform which prepares images as input to the network and the dimensions of the + network input + """ + if "openvino" in model_type: + from openvino.runtime import Core + + keep_aspect_ratio = not square + + if model_type == "dpt_beit_large_512": + model = DPTDepthModel( + path=model_path, + backbone="beitl16_512", + non_negative=True, + ) + net_w, net_h = 512, 512 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_beit_large_384": + model = DPTDepthModel( + path=model_path, + backbone="beitl16_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_beit_base_384": + model = DPTDepthModel( + path=model_path, + backbone="beitb16_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_swin2_large_384": + model = DPTDepthModel( + path=model_path, + backbone="swin2l24_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + keep_aspect_ratio = False + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_swin2_base_384": + model = DPTDepthModel( + path=model_path, + backbone="swin2b24_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + keep_aspect_ratio = False + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_swin2_tiny_256": + model = DPTDepthModel( + path=model_path, + backbone="swin2t16_256", + non_negative=True, + ) + net_w, net_h = 256, 256 + keep_aspect_ratio = False + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_swin_large_384": + model = DPTDepthModel( + path=model_path, + backbone="swinl12_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + keep_aspect_ratio = False + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_next_vit_large_384": + model = DPTDepthModel( + path=model_path, + backbone="next_vit_large_6m", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + # We change the notation from dpt_levit_224 (MiDaS notation) to levit_384 (timm notation) here, where the 224 refers + # to the resolution 224x224 used by LeViT and 384 is the first entry of the embed_dim, see _cfg and model_cfgs of + # https://github.com/rwightman/pytorch-image-models/blob/main/timm/models/levit.py + # (commit id: 927f031293a30afb940fff0bee34b85d9c059b0e) + elif model_type == "dpt_levit_224": + model = DPTDepthModel( + path=model_path, + backbone="levit_384", + non_negative=True, + head_features_1=64, + head_features_2=8, + ) + net_w, net_h = 224, 224 + keep_aspect_ratio = False + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_large_384": + model = DPTDepthModel( + path=model_path, + backbone="vitl16_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "dpt_hybrid_384": + model = DPTDepthModel( + path=model_path, + backbone="vitb_rn50_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + elif model_type == "midas_v21_384": + model = MidasNet(model_path, non_negative=True) + net_w, net_h = 384, 384 + resize_mode = "upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + + elif model_type == "midas_v21_small_256": + model = MidasNet_small(model_path, features=64, backbone="efficientnet_lite3", exportable=True, + non_negative=True, blocks={'expand': True}) + net_w, net_h = 256, 256 + resize_mode = "upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + + elif model_type == "openvino_midas_v21_small_256": + ie = Core() + uncompiled_model = ie.read_model(model=model_path) + model = ie.compile_model(uncompiled_model, "CPU") + net_w, net_h = 256, 256 + resize_mode = "upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + + else: + print(f"model_type '{model_type}' not implemented, use: --model_type large") + assert False + + if not "openvino" in model_type: + print("Model loaded, number of parameters = {:.0f}M".format(sum(p.numel() for p in model.parameters()) / 1e6)) + else: + print("Model loaded, optimized with OpenVINO") + + if "openvino" in model_type: + keep_aspect_ratio = False + + if height is not None: + net_w, net_h = height, height + + transform = Compose( + [ + Resize( + net_w, + net_h, + resize_target=None, + keep_aspect_ratio=keep_aspect_ratio, + ensure_multiple_of=32, + resize_method=resize_mode, + image_interpolation_method=cv2.INTER_CUBIC, + ), + normalization, + PrepareForNet(), + ] + ) + + if not "openvino" in model_type: + model.eval() + + if optimize and (device == torch.device("cuda")): + if not "openvino" in model_type: + model = model.to(memory_format=torch.channels_last) + model = model.half() + else: + print("Error: OpenVINO models are already optimized. No optimization to half-float possible.") + exit() + + if not "openvino" in model_type: + model.to(device) + + return model, transform, net_w, net_h diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/transforms.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..350cbc11662633ad7f8968eb10be2e7de6e384e9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/transforms.py @@ -0,0 +1,234 @@ +import numpy as np +import cv2 +import math + + +def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): + """Rezise the sample to ensure the given size. Keeps aspect ratio. + + Args: + sample (dict): sample + size (tuple): image size + + Returns: + tuple: new size + """ + shape = list(sample["disparity"].shape) + + if shape[0] >= size[0] and shape[1] >= size[1]: + return sample + + scale = [0, 0] + scale[0] = size[0] / shape[0] + scale[1] = size[1] / shape[1] + + scale = max(scale) + + shape[0] = math.ceil(scale * shape[0]) + shape[1] = math.ceil(scale * shape[1]) + + # resize + sample["image"] = cv2.resize( + sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method + ) + + sample["disparity"] = cv2.resize( + sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST + ) + sample["mask"] = cv2.resize( + sample["mask"].astype(np.float32), + tuple(shape[::-1]), + interpolation=cv2.INTER_NEAREST, + ) + sample["mask"] = sample["mask"].astype(bool) + + return tuple(shape) + + +class Resize(object): + """Resize sample to given size (width, height). + """ + + def __init__( + self, + width, + height, + resize_target=True, + keep_aspect_ratio=False, + ensure_multiple_of=1, + resize_method="lower_bound", + image_interpolation_method=cv2.INTER_AREA, + ): + """Init. + + Args: + width (int): desired output width + height (int): desired output height + resize_target (bool, optional): + True: Resize the full sample (image, mask, target). + False: Resize image only. + Defaults to True. + keep_aspect_ratio (bool, optional): + True: Keep the aspect ratio of the input sample. + Output sample might not have the given width and height, and + resize behaviour depends on the parameter 'resize_method'. + Defaults to False. + ensure_multiple_of (int, optional): + Output width and height is constrained to be multiple of this parameter. + Defaults to 1. + resize_method (str, optional): + "lower_bound": Output will be at least as large as the given size. + "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) + "minimal": Scale as least as possible. (Output size might be smaller than given size.) + Defaults to "lower_bound". + """ + self.__width = width + self.__height = height + + self.__resize_target = resize_target + self.__keep_aspect_ratio = keep_aspect_ratio + self.__multiple_of = ensure_multiple_of + self.__resize_method = resize_method + self.__image_interpolation_method = image_interpolation_method + + def constrain_to_multiple_of(self, x, min_val=0, max_val=None): + y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int) + + if max_val is not None and y > max_val: + y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int) + + if y < min_val: + y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int) + + return y + + def get_size(self, width, height): + # determine new height and width + scale_height = self.__height / height + scale_width = self.__width / width + + if self.__keep_aspect_ratio: + if self.__resize_method == "lower_bound": + # scale such that output size is lower bound + if scale_width > scale_height: + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + elif self.__resize_method == "upper_bound": + # scale such that output size is upper bound + if scale_width < scale_height: + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + elif self.__resize_method == "minimal": + # scale as least as possbile + if abs(1 - scale_width) < abs(1 - scale_height): + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + else: + raise ValueError( + f"resize_method {self.__resize_method} not implemented" + ) + + if self.__resize_method == "lower_bound": + new_height = self.constrain_to_multiple_of( + scale_height * height, min_val=self.__height + ) + new_width = self.constrain_to_multiple_of( + scale_width * width, min_val=self.__width + ) + elif self.__resize_method == "upper_bound": + new_height = self.constrain_to_multiple_of( + scale_height * height, max_val=self.__height + ) + new_width = self.constrain_to_multiple_of( + scale_width * width, max_val=self.__width + ) + elif self.__resize_method == "minimal": + new_height = self.constrain_to_multiple_of(scale_height * height) + new_width = self.constrain_to_multiple_of(scale_width * width) + else: + raise ValueError(f"resize_method {self.__resize_method} not implemented") + + return (new_width, new_height) + + def __call__(self, sample): + width, height = self.get_size( + sample["image"].shape[1], sample["image"].shape[0] + ) + + # resize sample + sample["image"] = cv2.resize( + sample["image"], + (width, height), + interpolation=self.__image_interpolation_method, + ) + + if self.__resize_target: + if "disparity" in sample: + sample["disparity"] = cv2.resize( + sample["disparity"], + (width, height), + interpolation=cv2.INTER_NEAREST, + ) + + if "depth" in sample: + sample["depth"] = cv2.resize( + sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST + ) + + sample["mask"] = cv2.resize( + sample["mask"].astype(np.float32), + (width, height), + interpolation=cv2.INTER_NEAREST, + ) + sample["mask"] = sample["mask"].astype(bool) + + return sample + + +class NormalizeImage(object): + """Normlize image by given mean and std. + """ + + def __init__(self, mean, std): + self.__mean = mean + self.__std = std + + def __call__(self, sample): + sample["image"] = (sample["image"] - self.__mean) / self.__std + + return sample + + +class PrepareForNet(object): + """Prepare sample for usage as network input. + """ + + def __init__(self): + pass + + def __call__(self, sample): + image = np.transpose(sample["image"], (2, 0, 1)) + sample["image"] = np.ascontiguousarray(image).astype(np.float32) + + if "mask" in sample: + sample["mask"] = sample["mask"].astype(np.float32) + sample["mask"] = np.ascontiguousarray(sample["mask"]) + + if "disparity" in sample: + disparity = sample["disparity"].astype(np.float32) + sample["disparity"] = np.ascontiguousarray(disparity) + + if "depth" in sample: + depth = sample["depth"].astype(np.float32) + sample["depth"] = np.ascontiguousarray(depth) + + return sample diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2668792389157609abb2a0846fb620e7d67eb9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/__init__.py @@ -0,0 +1,24 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2668792389157609abb2a0846fb620e7d67eb9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/__init__.py @@ -0,0 +1,24 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/midas.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/midas.py new file mode 100644 index 0000000000000000000000000000000000000000..b32478d3e4aedfbfbb6d31e5e6b43176da12f0e1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/midas.py @@ -0,0 +1,382 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import torch +import torch.nn as nn +import numpy as np +from torchvision.transforms import Normalize +import importlib + +def denormalize(x): + """Reverses the imagenet normalization applied to the input. + + Args: + x (torch.Tensor - shape(N,3,H,W)): input tensor + + Returns: + torch.Tensor - shape(N,3,H,W): Denormalized input + """ + mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(x.device) + std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(x.device) + return x * std + mean + +def get_activation(name, bank): + def hook(model, input, output): + bank[name] = output + return hook + + +class Resize(object): + """Resize sample to given size (width, height). + """ + + def __init__( + self, + width, + height, + resize_target=True, + keep_aspect_ratio=False, + ensure_multiple_of=1, + resize_method="lower_bound", + ): + """Init. + Args: + width (int): desired output width + height (int): desired output height + resize_target (bool, optional): + True: Resize the full sample (image, mask, target). + False: Resize image only. + Defaults to True. + keep_aspect_ratio (bool, optional): + True: Keep the aspect ratio of the input sample. + Output sample might not have the given width and height, and + resize behaviour depends on the parameter 'resize_method'. + Defaults to False. + ensure_multiple_of (int, optional): + Output width and height is constrained to be multiple of this parameter. + Defaults to 1. + resize_method (str, optional): + "lower_bound": Output will be at least as large as the given size. + "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) + "minimal": Scale as least as possible. (Output size might be smaller than given size.) + Defaults to "lower_bound". + """ + print("Params passed to Resize transform:") + print("\twidth: ", width) + print("\theight: ", height) + print("\tresize_target: ", resize_target) + print("\tkeep_aspect_ratio: ", keep_aspect_ratio) + print("\tensure_multiple_of: ", ensure_multiple_of) + print("\tresize_method: ", resize_method) + + self.__width = width + self.__height = height + + self.__keep_aspect_ratio = keep_aspect_ratio + self.__multiple_of = ensure_multiple_of + self.__resize_method = resize_method + + def constrain_to_multiple_of(self, x, min_val=0, max_val=None): + y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int) + + if max_val is not None and y > max_val: + y = (np.floor(x / self.__multiple_of) + * self.__multiple_of).astype(int) + + if y < min_val: + y = (np.ceil(x / self.__multiple_of) + * self.__multiple_of).astype(int) + + return y + + def get_size(self, width, height): + # determine new height and width + scale_height = self.__height / height + scale_width = self.__width / width + + if self.__keep_aspect_ratio: + if self.__resize_method == "lower_bound": + # scale such that output size is lower bound + if scale_width > scale_height: + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + elif self.__resize_method == "upper_bound": + # scale such that output size is upper bound + if scale_width < scale_height: + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + elif self.__resize_method == "minimal": + # scale as least as possbile + if abs(1 - scale_width) < abs(1 - scale_height): + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + else: + raise ValueError( + f"resize_method {self.__resize_method} not implemented" + ) + + if self.__resize_method == "lower_bound": + new_height = self.constrain_to_multiple_of( + scale_height * height, min_val=self.__height + ) + new_width = self.constrain_to_multiple_of( + scale_width * width, min_val=self.__width + ) + elif self.__resize_method == "upper_bound": + new_height = self.constrain_to_multiple_of( + scale_height * height, max_val=self.__height + ) + new_width = self.constrain_to_multiple_of( + scale_width * width, max_val=self.__width + ) + elif self.__resize_method == "minimal": + new_height = self.constrain_to_multiple_of(scale_height * height) + new_width = self.constrain_to_multiple_of(scale_width * width) + else: + raise ValueError( + f"resize_method {self.__resize_method} not implemented") + + return (new_width, new_height) + + def __call__(self, x): + width, height = self.get_size(*x.shape[-2:][::-1]) + return nn.functional.interpolate(x, (int(height), int(width)), mode='bilinear', align_corners=True) + +class PrepForMidas(object): + def __init__(self, resize_mode="minimal", keep_aspect_ratio=True, img_size=384, do_resize=True): + if isinstance(img_size, int): + img_size = (img_size, img_size) + net_h, net_w = img_size + self.normalization = Normalize( + mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + self.resizer = Resize(net_w, net_h, keep_aspect_ratio=keep_aspect_ratio, ensure_multiple_of=32, resize_method=resize_mode) \ + if do_resize else nn.Identity() + + def __call__(self, x): + return self.normalization(self.resizer(x)) + + +class MidasCore(nn.Module): + def __init__(self, midas, trainable=False, fetch_features=True, layer_names=('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1'), freeze_bn=False, keep_aspect_ratio=True, + img_size=384, **kwargs): + """Midas Base model used for multi-scale feature extraction. + + Args: + midas (torch.nn.Module): Midas model. + trainable (bool, optional): Train midas model. Defaults to False. + fetch_features (bool, optional): Extract multi-scale features. Defaults to True. + layer_names (tuple, optional): Layers used for feature extraction. Order = (head output features, last layer features, ...decoder features). Defaults to ('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1'). + freeze_bn (bool, optional): Freeze BatchNorm. Generally results in better finetuning performance. Defaults to False. + keep_aspect_ratio (bool, optional): Keep the aspect ratio of input images while resizing. Defaults to True. + img_size (int, tuple, optional): Input resolution. Defaults to 384. + """ + super().__init__() + self.core = midas + self.output_channels = None + self.core_out = {} + self.trainable = trainable + self.fetch_features = fetch_features + # midas.scratch.output_conv = nn.Identity() + self.handles = [] + # self.layer_names = ['out_conv','l4_rn', 'r4', 'r3', 'r2', 'r1'] + self.layer_names = layer_names + + self.set_trainable(trainable) + self.set_fetch_features(fetch_features) + + self.prep = PrepForMidas(keep_aspect_ratio=keep_aspect_ratio, + img_size=img_size, do_resize=kwargs.get('do_resize', True)) + + if freeze_bn: + self.freeze_bn() + + def set_trainable(self, trainable): + self.trainable = trainable + if trainable: + self.unfreeze() + else: + self.freeze() + return self + + def set_fetch_features(self, fetch_features): + self.fetch_features = fetch_features + if fetch_features: + if len(self.handles) == 0: + self.attach_hooks(self.core) + else: + self.remove_hooks() + return self + + def freeze(self): + for p in self.parameters(): + p.requires_grad = False + self.trainable = False + return self + + def unfreeze(self): + for p in self.parameters(): + p.requires_grad = True + self.trainable = True + return self + + def freeze_bn(self): + for m in self.modules(): + if isinstance(m, nn.BatchNorm2d): + m.eval() + return self + + def forward(self, x, denorm=False, return_rel_depth=False): + with torch.no_grad(): + if denorm: + x = denormalize(x) + x = self.prep(x) + # print("Shape after prep: ", x.shape) + + with torch.set_grad_enabled(self.trainable): + + # print("Input size to Midascore", x.shape) + rel_depth = self.core(x) + # print("Output from midas shape", rel_depth.shape) + if not self.fetch_features: + return rel_depth + out = [self.core_out[k] for k in self.layer_names] + + if return_rel_depth: + return rel_depth, out + return out + + def get_rel_pos_params(self): + for name, p in self.core.pretrained.named_parameters(): + if "relative_position" in name: + yield p + + def get_enc_params_except_rel_pos(self): + for name, p in self.core.pretrained.named_parameters(): + if "relative_position" not in name: + yield p + + def freeze_encoder(self, freeze_rel_pos=False): + if freeze_rel_pos: + for p in self.core.pretrained.parameters(): + p.requires_grad = False + else: + for p in self.get_enc_params_except_rel_pos(): + p.requires_grad = False + return self + + def attach_hooks(self, midas): + if len(self.handles) > 0: + self.remove_hooks() + if "out_conv" in self.layer_names: + self.handles.append(list(midas.scratch.output_conv.children())[ + 3].register_forward_hook(get_activation("out_conv", self.core_out))) + if "r4" in self.layer_names: + self.handles.append(midas.scratch.refinenet4.register_forward_hook( + get_activation("r4", self.core_out))) + if "r3" in self.layer_names: + self.handles.append(midas.scratch.refinenet3.register_forward_hook( + get_activation("r3", self.core_out))) + if "r2" in self.layer_names: + self.handles.append(midas.scratch.refinenet2.register_forward_hook( + get_activation("r2", self.core_out))) + if "r1" in self.layer_names: + self.handles.append(midas.scratch.refinenet1.register_forward_hook( + get_activation("r1", self.core_out))) + if "l4_rn" in self.layer_names: + self.handles.append(midas.scratch.layer4_rn.register_forward_hook( + get_activation("l4_rn", self.core_out))) + + return self + + def remove_hooks(self): + for h in self.handles: + h.remove() + return self + + def __del__(self): + self.remove_hooks() + + def set_output_channels(self, model_type): + self.output_channels = MIDAS_SETTINGS[model_type] + + @staticmethod + def build(midas_model_type="DPT_BEiT_L_384", train_midas=False, use_pretrained_midas=True, fetch_features=False, freeze_bn=True, force_keep_ar=False, force_reload=False, **kwargs): + if midas_model_type not in MIDAS_SETTINGS: + raise ValueError( + f"Invalid model type: {midas_model_type}. Must be one of {list(MIDAS_SETTINGS.keys())}") + if "img_size" in kwargs: + kwargs = MidasCore.parse_img_size(kwargs) + img_size = kwargs.pop("img_size", [384, 384]) + print("img_size", img_size) + hubconf = importlib.import_module(f"models.monoD.zoeDepth.midas_c.hubconf") + midas = getattr(hubconf, midas_model_type)(pretrained=False) + ckpt_path = "models/monoD/zoeDepth/ckpts/dpt_beit_large_384.pt" + midas_ckpt = torch.load(ckpt_path, map_location=torch.device('cpu')) + midas.load_state_dict(midas_ckpt) + # midas = torch.hub.load("intel-isl/MiDaS", midas_model_type, + # pretrained=use_pretrained_midas, force_reload=force_reload) + kwargs.update({'keep_aspect_ratio': force_keep_ar}) + midas_core = MidasCore(midas, trainable=train_midas, fetch_features=fetch_features, + freeze_bn=freeze_bn, img_size=img_size, **kwargs) + midas_core.set_output_channels(midas_model_type) + return midas_core + + @staticmethod + def build_from_config(config): + return MidasCore.build(**config) + + @staticmethod + def parse_img_size(config): + assert 'img_size' in config + if isinstance(config['img_size'], str): + assert "," in config['img_size'], "img_size should be a string with comma separated img_size=H,W" + config['img_size'] = list(map(int, config['img_size'].split(","))) + assert len( + config['img_size']) == 2, "img_size should be a string with comma separated img_size=H,W" + elif isinstance(config['img_size'], int): + config['img_size'] = [config['img_size'], config['img_size']] + else: + assert isinstance(config['img_size'], list) and len( + config['img_size']) == 2, "img_size should be a list of H,W" + return config + + +nchannels2models = { + tuple([256]*5): ["DPT_BEiT_L_384", "DPT_BEiT_L_512", "DPT_BEiT_B_384", "DPT_SwinV2_L_384", "DPT_SwinV2_B_384", "DPT_SwinV2_T_256", "DPT_Large", "DPT_Hybrid"], + (512, 256, 128, 64, 64): ["MiDaS_small"] +} + +# Model name to number of output channels +MIDAS_SETTINGS = {m: k for k, v in nchannels2models.items() + for m in v + } diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/builder.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a42fb42f18dd26e313ef2ed3a983381eaaf36dbd --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/builder.py @@ -0,0 +1,52 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +from importlib import import_module +from models.monoD.zoeDepth.models.depth_model import DepthModel + +def build_model(config) -> DepthModel: + """Builds a model from a config. The model is specified by the model name and version in the config. The model is then constructed using the build_from_config function of the model interface. + This function should be used to construct models for training and evaluation. + + Args: + config (dict): Config dict. Config is constructed in utils/config.py. Each model has its own config file(s) saved in its root model folder. + + Returns: + torch.nn.Module: Model corresponding to name and version as specified in config + """ + module_name = f"models.monoD.zoeDepth.models.{config.model}" + try: + module = import_module(module_name) + except ModuleNotFoundError as e: + # print the original error message + print(e) + raise ValueError( + f"Model {config.model} not found. Refer above error for details.") from e + try: + get_version = getattr(module, "get_version") + except AttributeError as e: + raise ValueError( + f"Model {config.model} has no get_version function.") from e + + return get_version(config.version_name).build_from_config(config) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/depth_model.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/depth_model.py new file mode 100644 index 0000000000000000000000000000000000000000..fc421c108ea3928c9add62b4c190500d9bd4eda1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/depth_model.py @@ -0,0 +1,152 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision import transforms +import PIL.Image +from PIL import Image +from typing import Union + + +class DepthModel(nn.Module): + def __init__(self): + super().__init__() + self.device = 'cpu' + + def to(self, device) -> nn.Module: + self.device = device + return super().to(device) + + def forward(self, x, *args, **kwargs): + raise NotImplementedError + + def _infer(self, x: torch.Tensor): + """ + Inference interface for the model + Args: + x (torch.Tensor): input tensor of shape (b, c, h, w) + Returns: + torch.Tensor: output tensor of shape (b, 1, h, w) + """ + return self(x)['metric_depth'] + + def _infer_with_pad_aug(self, x: torch.Tensor, pad_input: bool=True, fh: float=3, fw: float=3, upsampling_mode: str='bicubic', padding_mode="reflect", **kwargs) -> torch.Tensor: + """ + Inference interface for the model with padding augmentation + Padding augmentation fixes the boundary artifacts in the output depth map. + Boundary artifacts are sometimes caused by the fact that the model is trained on NYU raw dataset which has a black or white border around the image. + This augmentation pads the input image and crops the prediction back to the original size / view. + + Note: This augmentation is not required for the models trained with 'avoid_boundary'=True. + Args: + x (torch.Tensor): input tensor of shape (b, c, h, w) + pad_input (bool, optional): whether to pad the input or not. Defaults to True. + fh (float, optional): height padding factor. The padding is calculated as sqrt(h/2) * fh. Defaults to 3. + fw (float, optional): width padding factor. The padding is calculated as sqrt(w/2) * fw. Defaults to 3. + upsampling_mode (str, optional): upsampling mode. Defaults to 'bicubic'. + padding_mode (str, optional): padding mode. Defaults to "reflect". + Returns: + torch.Tensor: output tensor of shape (b, 1, h, w) + """ + # assert x is nchw and c = 3 + assert x.dim() == 4, "x must be 4 dimensional, got {}".format(x.dim()) + assert x.shape[1] == 3, "x must have 3 channels, got {}".format(x.shape[1]) + + if pad_input: + assert fh > 0 or fw > 0, "atlease one of fh and fw must be greater than 0" + pad_h = int(np.sqrt(x.shape[2]/2) * fh) + pad_w = int(np.sqrt(x.shape[3]/2) * fw) + padding = [pad_w, pad_w] + if pad_h > 0: + padding += [pad_h, pad_h] + + x = F.pad(x, padding, mode=padding_mode, **kwargs) + out = self._infer(x) + if out.shape[-2:] != x.shape[-2:]: + out = F.interpolate(out, size=(x.shape[2], x.shape[3]), mode=upsampling_mode, align_corners=False) + if pad_input: + # crop to the original size, handling the case where pad_h and pad_w is 0 + if pad_h > 0: + out = out[:, :, pad_h:-pad_h,:] + if pad_w > 0: + out = out[:, :, :, pad_w:-pad_w] + return out + + def infer_with_flip_aug(self, x, pad_input: bool=True, **kwargs) -> torch.Tensor: + """ + Inference interface for the model with horizontal flip augmentation + Horizontal flip augmentation improves the accuracy of the model by averaging the output of the model with and without horizontal flip. + Args: + x (torch.Tensor): input tensor of shape (b, c, h, w) + pad_input (bool, optional): whether to use padding augmentation. Defaults to True. + Returns: + torch.Tensor: output tensor of shape (b, 1, h, w) + """ + # infer with horizontal flip and average + out = self._infer_with_pad_aug(x, pad_input=pad_input, **kwargs) + out_flip = self._infer_with_pad_aug(torch.flip(x, dims=[3]), pad_input=pad_input, **kwargs) + out = (out + torch.flip(out_flip, dims=[3])) / 2 + return out + + def infer(self, x, pad_input: bool=True, with_flip_aug: bool=True, **kwargs) -> torch.Tensor: + """ + Inference interface for the model + Args: + x (torch.Tensor): input tensor of shape (b, c, h, w) + pad_input (bool, optional): whether to use padding augmentation. Defaults to True. + with_flip_aug (bool, optional): whether to use horizontal flip augmentation. Defaults to True. + Returns: + torch.Tensor: output tensor of shape (b, 1, h, w) + """ + if with_flip_aug: + return self.infer_with_flip_aug(x, pad_input=pad_input, **kwargs) + else: + return self._infer_with_pad_aug(x, pad_input=pad_input, **kwargs) + + @torch.no_grad() + def infer_pil(self, pil_img, pad_input: bool=True, with_flip_aug: bool=True, output_type: str="numpy", **kwargs) -> Union[np.ndarray, PIL.Image.Image, torch.Tensor]: + """ + Inference interface for the model for PIL image + Args: + pil_img (PIL.Image.Image): input PIL image + pad_input (bool, optional): whether to use padding augmentation. Defaults to True. + with_flip_aug (bool, optional): whether to use horizontal flip augmentation. Defaults to True. + output_type (str, optional): output type. Supported values are 'numpy', 'pil' and 'tensor'. Defaults to "numpy". + """ + x = transforms.ToTensor()(pil_img).unsqueeze(0).to(self.device) + out_tensor = self.infer(x, pad_input=pad_input, with_flip_aug=with_flip_aug, **kwargs) + if output_type == "numpy": + return out_tensor.squeeze().cpu().numpy() + elif output_type == "pil": + # uint16 is required for depth pil image + out_16bit_numpy = (out_tensor.squeeze().cpu().numpy()*256).astype(np.uint16) + return Image.fromarray(out_16bit_numpy) + elif output_type == "tensor": + return out_tensor.squeeze().cpu() + else: + raise ValueError(f"output_type {output_type} not supported. Supported values are 'numpy', 'pil' and 'tensor'") + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/attractor.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/attractor.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8efe645adea1d88a12e2ac5cc6bb2a251eef9d --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/attractor.py @@ -0,0 +1,208 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import torch +import torch.nn as nn + + +@torch.jit.script +def exp_attractor(dx, alpha: float = 300, gamma: int = 2): + """Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor + + Args: + dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. + alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. + gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. + + Returns: + torch.Tensor : Delta shifts - dc; New bin centers = Old bin centers + dc + """ + return torch.exp(-alpha*(torch.abs(dx)**gamma)) * (dx) + + +@torch.jit.script +def inv_attractor(dx, alpha: float = 300, gamma: int = 2): + """Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center + This is the default one according to the accompanying paper. + + Args: + dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. + alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. + gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. + + Returns: + torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc + """ + return dx.div(1+alpha*dx.pow(gamma)) + + +class AttractorLayer(nn.Module): + def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10, + alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False): + """ + Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth) + """ + super().__init__() + + self.n_attractors = n_attractors + self.n_bins = n_bins + self.min_depth = min_depth + self.max_depth = max_depth + self.alpha = alpha + self.gamma = gamma + self.kind = kind + self.attractor_type = attractor_type + self.memory_efficient = memory_efficient + + self._net = nn.Sequential( + nn.Conv2d(in_features, mlp_dim, 1, 1, 0), + nn.ReLU(inplace=True), + nn.Conv2d(mlp_dim, n_attractors*2, 1, 1, 0), # x2 for linear norm + nn.ReLU(inplace=True) + ) + + def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False): + """ + Args: + x (torch.Tensor) : feature block; shape - n, c, h, w + b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w + + Returns: + tuple(torch.Tensor,torch.Tensor) : new bin centers normed and scaled; shape - n, nbins, h, w + """ + if prev_b_embedding is not None: + if interpolate: + prev_b_embedding = nn.functional.interpolate( + prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True) + x = x + prev_b_embedding + + A = self._net(x) + eps = 1e-3 + A = A + eps + n, c, h, w = A.shape + A = A.view(n, self.n_attractors, 2, h, w) + A_normed = A / A.sum(dim=2, keepdim=True) # n, a, 2, h, w + A_normed = A[:, :, 0, ...] # n, na, h, w + + b_prev = nn.functional.interpolate( + b_prev, (h, w), mode='bilinear', align_corners=True) + b_centers = b_prev + + if self.attractor_type == 'exp': + dist = exp_attractor + else: + dist = inv_attractor + + if not self.memory_efficient: + func = {'mean': torch.mean, 'sum': torch.sum}[self.kind] + # .shape N, nbins, h, w + delta_c = func(dist(A_normed.unsqueeze( + 2) - b_centers.unsqueeze(1)), dim=1) + else: + delta_c = torch.zeros_like(b_centers, device=b_centers.device) + for i in range(self.n_attractors): + # .shape N, nbins, h, w + delta_c += dist(A_normed[:, i, ...].unsqueeze(1) - b_centers) + + if self.kind == 'mean': + delta_c = delta_c / self.n_attractors + + b_new_centers = b_centers + delta_c + B_centers = (self.max_depth - self.min_depth) * \ + b_new_centers + self.min_depth + B_centers, _ = torch.sort(B_centers, dim=1) + B_centers = torch.clip(B_centers, self.min_depth, self.max_depth) + return b_new_centers, B_centers + + +class AttractorLayerUnnormed(nn.Module): + def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10, + alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False): + """ + Attractor layer for bin centers. Bin centers are unbounded + """ + super().__init__() + + self.n_attractors = n_attractors + self.n_bins = n_bins + self.min_depth = min_depth + self.max_depth = max_depth + self.alpha = alpha + self.gamma = gamma + self.kind = kind + self.attractor_type = attractor_type + self.memory_efficient = memory_efficient + + self._net = nn.Sequential( + nn.Conv2d(in_features, mlp_dim, 1, 1, 0), + nn.ReLU(inplace=True), + nn.Conv2d(mlp_dim, n_attractors, 1, 1, 0), + nn.Softplus() + ) + + def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False): + """ + Args: + x (torch.Tensor) : feature block; shape - n, c, h, w + b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w + + Returns: + tuple(torch.Tensor,torch.Tensor) : new bin centers unbounded; shape - n, nbins, h, w. Two outputs just to keep the API consistent with the normed version + """ + if prev_b_embedding is not None: + if interpolate: + prev_b_embedding = nn.functional.interpolate( + prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True) + x = x + prev_b_embedding + + A = self._net(x) + n, c, h, w = A.shape + + b_prev = nn.functional.interpolate( + b_prev, (h, w), mode='bilinear', align_corners=True) + b_centers = b_prev + + if self.attractor_type == 'exp': + dist = exp_attractor + else: + dist = inv_attractor + + if not self.memory_efficient: + func = {'mean': torch.mean, 'sum': torch.sum}[self.kind] + # .shape N, nbins, h, w + delta_c = func( + dist(A.unsqueeze(2) - b_centers.unsqueeze(1)), dim=1) + else: + delta_c = torch.zeros_like(b_centers, device=b_centers.device) + for i in range(self.n_attractors): + delta_c += dist(A[:, i, ...].unsqueeze(1) - + b_centers) # .shape N, nbins, h, w + + if self.kind == 'mean': + delta_c = delta_c / self.n_attractors + + b_new_centers = b_centers + delta_c + B_centers = b_new_centers + + return b_new_centers, B_centers diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/dist_layers.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/dist_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..3208405dfb78fdfc28d5765e5a6d5dbe31967a23 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/dist_layers.py @@ -0,0 +1,121 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import torch +import torch.nn as nn + + +def log_binom(n, k, eps=1e-7): + """ log(nCk) using stirling approximation """ + n = n + eps + k = k + eps + return n * torch.log(n) - k * torch.log(k) - (n-k) * torch.log(n-k+eps) + + +class LogBinomial(nn.Module): + def __init__(self, n_classes=256, act=torch.softmax): + """Compute log binomial distribution for n_classes + + Args: + n_classes (int, optional): number of output classes. Defaults to 256. + """ + super().__init__() + self.K = n_classes + self.act = act + self.register_buffer('k_idx', torch.arange( + 0, n_classes).view(1, -1, 1, 1)) + self.register_buffer('K_minus_1', torch.Tensor( + [self.K-1]).view(1, -1, 1, 1)) + + def forward(self, x, t=1., eps=1e-4): + """Compute log binomial distribution for x + + Args: + x (torch.Tensor - NCHW): probabilities + t (float, torch.Tensor - NCHW, optional): Temperature of distribution. Defaults to 1.. + eps (float, optional): Small number for numerical stability. Defaults to 1e-4. + + Returns: + torch.Tensor -NCHW: log binomial distribution logbinomial(p;t) + """ + if x.ndim == 3: + x = x.unsqueeze(1) # make it nchw + + one_minus_x = torch.clamp(1 - x, eps, 1) + x = torch.clamp(x, eps, 1) + y = log_binom(self.K_minus_1, self.k_idx) + self.k_idx * \ + torch.log(x) + (self.K - 1 - self.k_idx) * torch.log(one_minus_x) + return self.act(y/t, dim=1) + + +class ConditionalLogBinomial(nn.Module): + def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax): + """Conditional Log Binomial distribution + + Args: + in_features (int): number of input channels in main feature + condition_dim (int): number of input channels in condition feature + n_classes (int, optional): Number of classes. Defaults to 256. + bottleneck_factor (int, optional): Hidden dim factor. Defaults to 2. + p_eps (float, optional): small eps value. Defaults to 1e-4. + max_temp (float, optional): Maximum temperature of output distribution. Defaults to 50. + min_temp (float, optional): Minimum temperature of output distribution. Defaults to 1e-7. + """ + super().__init__() + self.p_eps = p_eps + self.max_temp = max_temp + self.min_temp = min_temp + self.log_binomial_transform = LogBinomial(n_classes, act=act) + bottleneck = (in_features + condition_dim) // bottleneck_factor + self.mlp = nn.Sequential( + nn.Conv2d(in_features + condition_dim, bottleneck, + kernel_size=1, stride=1, padding=0), + nn.GELU(), + # 2 for p linear norm, 2 for t linear norm + nn.Conv2d(bottleneck, 2+2, kernel_size=1, stride=1, padding=0), + nn.Softplus() + ) + + def forward(self, x, cond): + """Forward pass + + Args: + x (torch.Tensor - NCHW): Main feature + cond (torch.Tensor - NCHW): condition feature + + Returns: + torch.Tensor: Output log binomial distribution + """ + pt = self.mlp(torch.concat((x, cond), dim=1)) + p, t = pt[:, :2, ...], pt[:, 2:, ...] + + p = p + self.p_eps + p = p[:, 0, ...] / (p[:, 0, ...] + p[:, 1, ...]) + + t = t + self.p_eps + t = t[:, 0, ...] / (t[:, 0, ...] + t[:, 1, ...]) + t = t.unsqueeze(1) + t = (self.max_temp - self.min_temp) * t + self.min_temp + + return self.log_binomial_transform(p, t) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/localbins_layers.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/localbins_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..f94481605c3e6958ce50e73b2eb31d9f0c07dc67 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/localbins_layers.py @@ -0,0 +1,169 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import torch +import torch.nn as nn + + +class SeedBinRegressor(nn.Module): + def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10): + """Bin center regressor network. Bin centers are bounded on (min_depth, max_depth) interval. + + Args: + in_features (int): input channels + n_bins (int, optional): Number of bin centers. Defaults to 16. + mlp_dim (int, optional): Hidden dimension. Defaults to 256. + min_depth (float, optional): Min depth value. Defaults to 1e-3. + max_depth (float, optional): Max depth value. Defaults to 10. + """ + super().__init__() + self.version = "1_1" + self.min_depth = min_depth + self.max_depth = max_depth + + self._net = nn.Sequential( + nn.Conv2d(in_features, mlp_dim, 1, 1, 0), + nn.ReLU(inplace=True), + nn.Conv2d(mlp_dim, n_bins, 1, 1, 0), + nn.ReLU(inplace=True) + ) + + def forward(self, x): + """ + Returns tensor of bin_width vectors (centers). One vector b for every pixel + """ + B = self._net(x) + eps = 1e-3 + B = B + eps + B_widths_normed = B / B.sum(dim=1, keepdim=True) + B_widths = (self.max_depth - self.min_depth) * \ + B_widths_normed # .shape NCHW + # pad has the form (left, right, top, bottom, front, back) + B_widths = nn.functional.pad( + B_widths, (0, 0, 0, 0, 1, 0), mode='constant', value=self.min_depth) + B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW + + B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:, 1:, ...]) + return B_widths_normed, B_centers + + +class SeedBinRegressorUnnormed(nn.Module): + def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10): + """Bin center regressor network. Bin centers are unbounded + + Args: + in_features (int): input channels + n_bins (int, optional): Number of bin centers. Defaults to 16. + mlp_dim (int, optional): Hidden dimension. Defaults to 256. + min_depth (float, optional): Not used. (for compatibility with SeedBinRegressor) + max_depth (float, optional): Not used. (for compatibility with SeedBinRegressor) + """ + super().__init__() + self.version = "1_1" + self._net = nn.Sequential( + nn.Conv2d(in_features, mlp_dim, 1, 1, 0), + nn.ReLU(inplace=True), + nn.Conv2d(mlp_dim, n_bins, 1, 1, 0), + nn.Softplus() + ) + + def forward(self, x): + """ + Returns tensor of bin_width vectors (centers). One vector b for every pixel + """ + B_centers = self._net(x) + return B_centers, B_centers + + +class Projector(nn.Module): + def __init__(self, in_features, out_features, mlp_dim=128): + """Projector MLP + + Args: + in_features (int): input channels + out_features (int): output channels + mlp_dim (int, optional): hidden dimension. Defaults to 128. + """ + super().__init__() + + self._net = nn.Sequential( + nn.Conv2d(in_features, mlp_dim, 1, 1, 0), + nn.ReLU(inplace=True), + nn.Conv2d(mlp_dim, out_features, 1, 1, 0), + ) + + def forward(self, x): + return self._net(x) + + + +class LinearSplitter(nn.Module): + def __init__(self, in_features, prev_nbins, split_factor=2, mlp_dim=128, min_depth=1e-3, max_depth=10): + super().__init__() + + self.prev_nbins = prev_nbins + self.split_factor = split_factor + self.min_depth = min_depth + self.max_depth = max_depth + + self._net = nn.Sequential( + nn.Conv2d(in_features, mlp_dim, 1, 1, 0), + nn.GELU(), + nn.Conv2d(mlp_dim, prev_nbins * split_factor, 1, 1, 0), + nn.ReLU() + ) + + def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False): + """ + x : feature block; shape - n, c, h, w + b_prev : previous bin widths normed; shape - n, prev_nbins, h, w + """ + if prev_b_embedding is not None: + if interpolate: + prev_b_embedding = nn.functional.interpolate(prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True) + x = x + prev_b_embedding + S = self._net(x) + eps = 1e-3 + S = S + eps + n, c, h, w = S.shape + S = S.view(n, self.prev_nbins, self.split_factor, h, w) + S_normed = S / S.sum(dim=2, keepdim=True) # fractional splits + + b_prev = nn.functional.interpolate(b_prev, (h,w), mode='bilinear', align_corners=True) + + + b_prev = b_prev / b_prev.sum(dim=1, keepdim=True) # renormalize for gurantees + # print(b_prev.shape, S_normed.shape) + # if is_for_query:(1).expand(-1, b_prev.size(0)//n, -1, -1, -1, -1).flatten(0,1) # TODO ? can replace all this with a single torch.repeat? + b = b_prev.unsqueeze(2) * S_normed + b = b.flatten(1,2) # .shape n, prev_nbins * split_factor, h, w + + # calculate bin centers for loss calculation + B_widths = (self.max_depth - self.min_depth) * b # .shape N, nprev * splitfactor, H, W + # pad has the form (left, right, top, bottom, front, back) + B_widths = nn.functional.pad(B_widths, (0,0,0,0,1,0), mode='constant', value=self.min_depth) + B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW + + B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:,1:,...]) + return b, B_centers \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/patch_transformer.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/patch_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..99d9e51a06b981bae45ce7dd64eaef19a4121991 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/patch_transformer.py @@ -0,0 +1,91 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import torch +import torch.nn as nn + + +class PatchTransformerEncoder(nn.Module): + def __init__(self, in_channels, patch_size=10, embedding_dim=128, num_heads=4, use_class_token=False): + """ViT-like transformer block + + Args: + in_channels (int): Input channels + patch_size (int, optional): patch size. Defaults to 10. + embedding_dim (int, optional): Embedding dimension in transformer model. Defaults to 128. + num_heads (int, optional): number of attention heads. Defaults to 4. + use_class_token (bool, optional): Whether to use extra token at the start for global accumulation (called as "class token"). Defaults to False. + """ + super(PatchTransformerEncoder, self).__init__() + self.use_class_token = use_class_token + encoder_layers = nn.TransformerEncoderLayer( + embedding_dim, num_heads, dim_feedforward=1024) + self.transformer_encoder = nn.TransformerEncoder( + encoder_layers, num_layers=4) # takes shape S,N,E + + self.embedding_convPxP = nn.Conv2d(in_channels, embedding_dim, + kernel_size=patch_size, stride=patch_size, padding=0) + + def positional_encoding_1d(self, sequence_length, batch_size, embedding_dim, device='cpu'): + """Generate positional encodings + + Args: + sequence_length (int): Sequence length + embedding_dim (int): Embedding dimension + + Returns: + torch.Tensor SBE: Positional encodings + """ + position = torch.arange( + 0, sequence_length, dtype=torch.float32, device=device).unsqueeze(1) + index = torch.arange( + 0, embedding_dim, 2, dtype=torch.float32, device=device).unsqueeze(0) + div_term = torch.exp(index * (-torch.log(torch.tensor(10000.0, device=device)) / embedding_dim)) + pos_encoding = position * div_term + pos_encoding = torch.cat([torch.sin(pos_encoding), torch.cos(pos_encoding)], dim=1) + pos_encoding = pos_encoding.unsqueeze(1).repeat(1, batch_size, 1) + return pos_encoding + + + def forward(self, x): + """Forward pass + + Args: + x (torch.Tensor - NCHW): Input feature tensor + + Returns: + torch.Tensor - SNE: Transformer output embeddings. S - sequence length (=HW/patch_size^2), N - batch size, E - embedding dim + """ + embeddings = self.embedding_convPxP(x).flatten( + 2) # .shape = n,c,s = n, embedding_dim, s + if self.use_class_token: + # extra special token at start ? + embeddings = nn.functional.pad(embeddings, (1, 0)) + + # change to S,N,E format required by transformer + embeddings = embeddings.permute(2, 0, 1) + S, N, E = embeddings.shape + embeddings = embeddings + self.positional_encoding_1d(S, N, E, device=embeddings.device) + x = self.transformer_encoder(embeddings) # .shape = S, N, E + return x diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/model_io.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/model_io.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf52b67e94809a052c7af39cae4462f0f974141 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/model_io.py @@ -0,0 +1,91 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import torch + +def load_state_dict(model, state_dict): + """Load state_dict into model, handling DataParallel and DistributedDataParallel. Also checks for "model" key in state_dict. + + DataParallel prefixes state_dict keys with 'module.' when saving. + If the model is not a DataParallel model but the state_dict is, then prefixes are removed. + If the model is a DataParallel model but the state_dict is not, then prefixes are added. + """ + state_dict = state_dict.get('model', state_dict) + # if model is a DataParallel model, then state_dict keys are prefixed with 'module.' + + do_prefix = isinstance( + model, (torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel)) + state = {} + for k, v in state_dict.items(): + if k.startswith('module.') and not do_prefix: + k = k[7:] + + if not k.startswith('module.') and do_prefix: + k = 'module.' + k + + state[k] = v + model.load_state_dict(state) + print("Loaded successfully") + return model + + +def load_wts(model, checkpoint_path): + ckpt = torch.load(checkpoint_path, map_location='cpu') + return load_state_dict(model, ckpt) + + +def load_state_dict_from_url(model, url, **kwargs): + state_dict = torch.hub.load_state_dict_from_url(url, map_location='cpu', **kwargs) + return load_state_dict(model, state_dict) + + +def load_state_from_resource(model, resource: str): + """Loads weights to the model from a given resource. A resource can be of following types: + 1. URL. Prefixed with "url::" + e.g. url::http(s)://url.resource.com/ckpt.pt + + 2. Local path. Prefixed with "local::" + e.g. local::/path/to/ckpt.pt + + + Args: + model (torch.nn.Module): Model + resource (str): resource string + + Returns: + torch.nn.Module: Model with loaded weights + """ + print(f"Using pretrained resource {resource}") + + if resource.startswith('url::'): + url = resource.split('url::')[1] + return load_state_dict_from_url(model, url, progress=True) + + elif resource.startswith('local::'): + path = resource.split('local::')[1] + return load_wts(model, path) + + else: + raise ValueError("Invalid resource type, only url:: and local:: are supported") + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc33f737d238766559f0e3a8def3c0b568f23b7f --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/__init__.py @@ -0,0 +1,31 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +from .zoedepth_v1 import ZoeDepth + +all_versions = { + "v1": ZoeDepth, +} + +get_version = lambda v : all_versions[v] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth.json b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth.json new file mode 100644 index 0000000000000000000000000000000000000000..99beb2dcd886006ba87805bddbe408b6d5fdff78 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth.json @@ -0,0 +1,58 @@ +{ + "model": { + "name": "ZoeDepth", + "version_name": "v1", + "n_bins": 64, + "bin_embedding_dim": 128, + "bin_centers_type": "softplus", + "n_attractors":[16, 8, 4, 1], + "attractor_alpha": 1000, + "attractor_gamma": 2, + "attractor_kind" : "mean", + "attractor_type" : "inv", + "midas_model_type" : "DPT_BEiT_L_384", + "min_temp": 0.0212, + "max_temp": 50.0, + "output_distribution": "logbinomial", + "memory_efficient": true, + "inverse_midas": false, + "img_size": [384, 512] + }, + + "train": { + "train_midas": true, + "use_pretrained_midas": true, + "trainer": "zoedepth", + "epochs": 5, + "bs": 16, + "optim_kwargs": {"lr": 0.000161, "wd": 0.01}, + "sched_kwargs": {"div_factor": 1, "final_div_factor": 10000, "pct_start": 0.7, "three_phase":false, "cycle_momentum": true}, + "same_lr": false, + "w_si": 1, + "w_domain": 0.2, + "w_reg": 0, + "w_grad": 0, + "avoid_boundary": false, + "random_crop": false, + "input_width": 640, + "input_height": 480, + "midas_lr_factor": 1, + "encoder_lr_factor":10, + "pos_enc_lr_factor":10, + "freeze_midas_bn": true + + }, + + "infer":{ + "train_midas": false, + "use_pretrained_midas": false, + "pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_N.pt", + "force_keep_ar": true + }, + + "eval":{ + "train_midas": false, + "use_pretrained_midas": false, + "pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_N.pt" + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth_kitti.json b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth_kitti.json new file mode 100644 index 0000000000000000000000000000000000000000..b51802aa44b91c39e15aacaac4b5ab6bec884414 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth_kitti.json @@ -0,0 +1,22 @@ +{ + "model": { + "bin_centers_type": "normed", + "img_size": [384, 768] + }, + + "train": { + }, + + "infer":{ + "train_midas": false, + "use_pretrained_midas": false, + "pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_K.pt", + "force_keep_ar": true + }, + + "eval":{ + "train_midas": false, + "use_pretrained_midas": false, + "pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_K.pt" + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/zoedepth_v1.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/zoedepth_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..7a10db5655b7002dbed9e75fbf095ed1ca37544b --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/zoedepth_v1.py @@ -0,0 +1,256 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import itertools + +import torch +import torch.nn as nn +from models.monoD.zoeDepth.models.depth_model import DepthModel +from models.monoD.zoeDepth.models.base_models.midas import MidasCore +from models.monoD.zoeDepth.models.layers.attractor import ( + AttractorLayer, AttractorLayerUnnormed +) +from models.monoD.zoeDepth.models.layers.dist_layers import ( + ConditionalLogBinomial + ) +from models.monoD.zoeDepth.models.layers.localbins_layers import ( + Projector, SeedBinRegressor, + SeedBinRegressorUnnormed + ) +from models.monoD.zoeDepth.models.model_io import load_state_from_resource + + +class ZoeDepth(DepthModel): + def __init__(self, core, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, + n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, + midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): + """ZoeDepth model. This is the version of ZoeDepth that has a single metric head + + Args: + core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features + n_bins (int, optional): Number of bin centers. Defaults to 64. + bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. + For "softplus", softplus activation is used and thus are unbounded. Defaults to "softplus". + bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. + min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. + max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. + n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. + attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. + attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. + attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. + attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. + min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. + max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. + train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. + midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. + encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. + pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. + """ + super().__init__() + + self.core = core + self.max_depth = max_depth + self.min_depth = min_depth + self.min_temp = min_temp + self.bin_centers_type = bin_centers_type + + self.midas_lr_factor = midas_lr_factor + self.encoder_lr_factor = encoder_lr_factor + self.pos_enc_lr_factor = pos_enc_lr_factor + self.train_midas = train_midas + self.inverse_midas = inverse_midas + + if self.encoder_lr_factor <= 0: + self.core.freeze_encoder( + freeze_rel_pos=self.pos_enc_lr_factor <= 0) + + N_MIDAS_OUT = 32 + btlnck_features = self.core.output_channels[0] + num_out_features = self.core.output_channels[1:] + + self.conv2 = nn.Conv2d(btlnck_features, btlnck_features, + kernel_size=1, stride=1, padding=0) # btlnck conv + + if bin_centers_type == "normed": + SeedBinRegressorLayer = SeedBinRegressor + Attractor = AttractorLayer + elif bin_centers_type == "softplus": + SeedBinRegressorLayer = SeedBinRegressorUnnormed + Attractor = AttractorLayerUnnormed + elif bin_centers_type == "hybrid1": + SeedBinRegressorLayer = SeedBinRegressor + Attractor = AttractorLayerUnnormed + elif bin_centers_type == "hybrid2": + SeedBinRegressorLayer = SeedBinRegressorUnnormed + Attractor = AttractorLayer + else: + raise ValueError( + "bin_centers_type should be one of 'normed', 'softplus', 'hybrid1', 'hybrid2'") + + self.seed_bin_regressor = SeedBinRegressorLayer( + btlnck_features, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth) + self.seed_projector = Projector(btlnck_features, bin_embedding_dim) + self.projectors = nn.ModuleList([ + Projector(num_out, bin_embedding_dim) + for num_out in num_out_features + ]) + self.attractors = nn.ModuleList([ + Attractor(bin_embedding_dim, n_bins, n_attractors=n_attractors[i], min_depth=min_depth, max_depth=max_depth, + alpha=attractor_alpha, gamma=attractor_gamma, kind=attractor_kind, attractor_type=attractor_type) + for i in range(len(num_out_features)) + ]) + + last_in = N_MIDAS_OUT + 1 # +1 for relative depth + + # use log binomial instead of softmax + self.conditional_log_binomial = ConditionalLogBinomial( + last_in, bin_embedding_dim, n_classes=n_bins, min_temp=min_temp, max_temp=max_temp) + + def forward(self, x, return_final_centers=False, denorm=False, return_probs=False, **kwargs): + """ + Args: + x (torch.Tensor): Input image tensor of shape (B, C, H, W) + return_final_centers (bool, optional): Whether to return the final bin centers. Defaults to False. + denorm (bool, optional): Whether to denormalize the input image. This reverses ImageNet normalization as midas normalization is different. Defaults to False. + return_probs (bool, optional): Whether to return the output probability distribution. Defaults to False. + + Returns: + dict: Dictionary containing the following keys: + - rel_depth (torch.Tensor): Relative depth map of shape (B, H, W) + - metric_depth (torch.Tensor): Metric depth map of shape (B, 1, H, W) + - bin_centers (torch.Tensor): Bin centers of shape (B, n_bins). Present only if return_final_centers is True + - probs (torch.Tensor): Output probability distribution of shape (B, n_bins, H, W). Present only if return_probs is True + + """ + b, c, h, w = x.shape + # print("input shape ", x.shape) + self.orig_input_width = w + self.orig_input_height = h + rel_depth, out = self.core(x, denorm=denorm, return_rel_depth=True) + # print("output shapes", rel_depth.shape, out.shape) + + outconv_activation = out[0] + btlnck = out[1] + x_blocks = out[2:] + + x_d0 = self.conv2(btlnck) + x = x_d0 + _, seed_b_centers = self.seed_bin_regressor(x) + + if self.bin_centers_type == 'normed' or self.bin_centers_type == 'hybrid2': + b_prev = (seed_b_centers - self.min_depth) / \ + (self.max_depth - self.min_depth) + else: + b_prev = seed_b_centers + + prev_b_embedding = self.seed_projector(x) + + # unroll this loop for better performance + for projector, attractor, x in zip(self.projectors, self.attractors, x_blocks): + b_embedding = projector(x) + b, b_centers = attractor( + b_embedding, b_prev, prev_b_embedding, interpolate=True) + b_prev = b.clone() + prev_b_embedding = b_embedding.clone() + + last = outconv_activation + + if self.inverse_midas: + # invert depth followed by normalization + rel_depth = 1.0 / (rel_depth + 1e-6) + rel_depth = (rel_depth - rel_depth.min()) / \ + (rel_depth.max() - rel_depth.min()) + # concat rel depth with last. First interpolate rel depth to last size + rel_cond = rel_depth.unsqueeze(1) + rel_cond = nn.functional.interpolate( + rel_cond, size=last.shape[2:], mode='bilinear', align_corners=True) + last = torch.cat([last, rel_cond], dim=1) + + b_embedding = nn.functional.interpolate( + b_embedding, last.shape[-2:], mode='bilinear', align_corners=True) + x = self.conditional_log_binomial(last, b_embedding) + + # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor + # print(x.shape, b_centers.shape) + b_centers = nn.functional.interpolate( + b_centers, x.shape[-2:], mode='bilinear', align_corners=True) + out = torch.sum(x * b_centers, dim=1, keepdim=True) + + # Structure output dict + output = dict(metric_depth=out) + if return_final_centers or return_probs: + output['bin_centers'] = b_centers + + if return_probs: + output['probs'] = x + + return output + + def get_lr_params(self, lr): + """ + Learning rate configuration for different layers of the model + Args: + lr (float) : Base learning rate + Returns: + list : list of parameters to optimize and their learning rates, in the format required by torch optimizers. + """ + param_conf = [] + if self.train_midas: + if self.encoder_lr_factor > 0: + param_conf.append({'params': self.core.get_enc_params_except_rel_pos( + ), 'lr': lr / self.encoder_lr_factor}) + + if self.pos_enc_lr_factor > 0: + param_conf.append( + {'params': self.core.get_rel_pos_params(), 'lr': lr / self.pos_enc_lr_factor}) + + midas_params = self.core.core.scratch.parameters() + midas_lr_factor = self.midas_lr_factor + param_conf.append( + {'params': midas_params, 'lr': lr / midas_lr_factor}) + + remaining_modules = [] + for name, child in self.named_children(): + if name != 'core': + remaining_modules.append(child) + remaining_params = itertools.chain( + *[child.parameters() for child in remaining_modules]) + + param_conf.append({'params': remaining_params, 'lr': lr}) + + return param_conf + + @staticmethod + def build(midas_model_type="DPT_BEiT_L_384", pretrained_resource=None, use_pretrained_midas=False, train_midas=False, freeze_midas_bn=True, **kwargs): + core = MidasCore.build(midas_model_type=midas_model_type, use_pretrained_midas=use_pretrained_midas, + train_midas=train_midas, fetch_features=True, freeze_bn=freeze_midas_bn, **kwargs) + model = ZoeDepth(core, **kwargs) + if pretrained_resource: + assert isinstance(pretrained_resource, str), "pretrained_resource must be a string" + model = load_state_from_resource(model, pretrained_resource) + return model + + @staticmethod + def build_from_config(config): + return ZoeDepth.build(**config) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..513a278b939c10c010e3c0250ec73544d5663886 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/__init__.py @@ -0,0 +1,31 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +from .zoedepth_nk_v1 import ZoeDepthNK + +all_versions = { + "v1": ZoeDepthNK, +} + +get_version = lambda v : all_versions[v] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/config_zoedepth_nk.json b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/config_zoedepth_nk.json new file mode 100644 index 0000000000000000000000000000000000000000..42bab2a3ad159a09599a5aba270c491021a3cf1a --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/config_zoedepth_nk.json @@ -0,0 +1,67 @@ +{ + "model": { + "name": "ZoeDepthNK", + "version_name": "v1", + "bin_conf" : [ + { + "name": "nyu", + "n_bins": 64, + "min_depth": 1e-3, + "max_depth": 10.0 + }, + { + "name": "kitti", + "n_bins": 64, + "min_depth": 1e-3, + "max_depth": 80.0 + } + ], + "bin_embedding_dim": 128, + "bin_centers_type": "softplus", + "n_attractors":[16, 8, 4, 1], + "attractor_alpha": 1000, + "attractor_gamma": 2, + "attractor_kind" : "mean", + "attractor_type" : "inv", + "min_temp": 0.0212, + "max_temp": 50.0, + "memory_efficient": true, + "midas_model_type" : "DPT_BEiT_L_384", + "img_size": [384, 512] + }, + + "train": { + "train_midas": true, + "use_pretrained_midas": true, + "trainer": "zoedepth_nk", + "epochs": 5, + "bs": 16, + "optim_kwargs": {"lr": 0.0002512, "wd": 0.01}, + "sched_kwargs": {"div_factor": 1, "final_div_factor": 10000, "pct_start": 0.7, "three_phase":false, "cycle_momentum": true}, + "same_lr": false, + "w_si": 1, + "w_domain": 100, + "avoid_boundary": false, + "random_crop": false, + "input_width": 640, + "input_height": 480, + "w_grad": 0, + "w_reg": 0, + "midas_lr_factor": 10, + "encoder_lr_factor":10, + "pos_enc_lr_factor":10 + }, + + "infer": { + "train_midas": false, + "pretrained_resource": "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_NK.pt", + "use_pretrained_midas": false, + "force_keep_ar": true + }, + + "eval": { + "train_midas": false, + "pretrained_resource": "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_NK.pt", + "use_pretrained_midas": false + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/zoedepth_nk_v1.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/zoedepth_nk_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ebad4981c66bcc09bf6894f95134352fe3c31f --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/zoedepth_nk_v1.py @@ -0,0 +1,342 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import itertools + +import torch +import torch.nn as nn + +from models.monoD.zoeDepth.models.depth_model import DepthModel +from models.monoD.zoeDepth.models.base_models.midas import MidasCore +from models.monoD.zoeDepth.models.layers.attractor import ( + AttractorLayer, AttractorLayerUnnormed +) +from models.monoD.zoeDepth.models.layers.dist_layers import ( + ConditionalLogBinomial +) +from models.monoD.zoeDepth.models.layers.localbins_layers import ( + Projector, SeedBinRegressor, SeedBinRegressorUnnormed + ) +from models.monoD.zoeDepth.models.layers.patch_transformer import ( + PatchTransformerEncoder +) +from models.monoD.zoeDepth.models.model_io import load_state_from_resource + + +class ZoeDepthNK(DepthModel): + def __init__(self, core, bin_conf, bin_centers_type="softplus", bin_embedding_dim=128, + n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', + min_temp=5, max_temp=50, + memory_efficient=False, train_midas=True, + is_midas_pretrained=True, midas_lr_factor=1, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): + """ZoeDepthNK model. This is the version of ZoeDepth that has two metric heads and uses a learned router to route to experts. + + Args: + core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features + + bin_conf (List[dict]): A list of dictionaries that contain the bin configuration for each metric head. Each dictionary should contain the following keys: + "name" (str, typically same as the dataset name), "n_bins" (int), "min_depth" (float), "max_depth" (float) + + The length of this list determines the number of metric heads. + bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. + For "softplus", softplus activation is used and thus are unbounded. Defaults to "normed". + bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. + + n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. + attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. + attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. + attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. + attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. + + min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. + max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. + + memory_efficient (bool, optional): Whether to use memory efficient version of attractor layers. Memory efficient version is slower but is recommended incase of multiple metric heads in order save GPU memory. Defaults to False. + + train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. + is_midas_pretrained (bool, optional): Is "core" pretrained? Defaults to True. + midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. + encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. + pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. + + """ + + super().__init__() + + self.core = core + self.bin_conf = bin_conf + self.min_temp = min_temp + self.max_temp = max_temp + self.memory_efficient = memory_efficient + self.train_midas = train_midas + self.is_midas_pretrained = is_midas_pretrained + self.midas_lr_factor = midas_lr_factor + self.encoder_lr_factor = encoder_lr_factor + self.pos_enc_lr_factor = pos_enc_lr_factor + self.inverse_midas = inverse_midas + + N_MIDAS_OUT = 32 + btlnck_features = self.core.output_channels[0] + num_out_features = self.core.output_channels[1:] + # self.scales = [16, 8, 4, 2] # spatial scale factors + + self.conv2 = nn.Conv2d( + btlnck_features, btlnck_features, kernel_size=1, stride=1, padding=0) + + # Transformer classifier on the bottleneck + self.patch_transformer = PatchTransformerEncoder( + btlnck_features, 1, 128, use_class_token=True) + self.mlp_classifier = nn.Sequential( + nn.Linear(128, 128), + nn.ReLU(), + nn.Linear(128, 2) + ) + + if bin_centers_type == "normed": + SeedBinRegressorLayer = SeedBinRegressor + Attractor = AttractorLayer + elif bin_centers_type == "softplus": + SeedBinRegressorLayer = SeedBinRegressorUnnormed + Attractor = AttractorLayerUnnormed + elif bin_centers_type == "hybrid1": + SeedBinRegressorLayer = SeedBinRegressor + Attractor = AttractorLayerUnnormed + elif bin_centers_type == "hybrid2": + SeedBinRegressorLayer = SeedBinRegressorUnnormed + Attractor = AttractorLayer + else: + raise ValueError( + "bin_centers_type should be one of 'normed', 'softplus', 'hybrid1', 'hybrid2'") + self.bin_centers_type = bin_centers_type + # We have bins for each bin conf. + # Create a map (ModuleDict) of 'name' -> seed_bin_regressor + self.seed_bin_regressors = nn.ModuleDict( + {conf['name']: SeedBinRegressorLayer(btlnck_features, conf["n_bins"], mlp_dim=bin_embedding_dim//2, min_depth=conf["min_depth"], max_depth=conf["max_depth"]) + for conf in bin_conf} + ) + + self.seed_projector = Projector( + btlnck_features, bin_embedding_dim, mlp_dim=bin_embedding_dim//2) + self.projectors = nn.ModuleList([ + Projector(num_out, bin_embedding_dim, mlp_dim=bin_embedding_dim//2) + for num_out in num_out_features + ]) + + # Create a map (ModuleDict) of 'name' -> attractors (ModuleList) + self.attractors = nn.ModuleDict( + {conf['name']: nn.ModuleList([ + Attractor(bin_embedding_dim, n_attractors[i], + mlp_dim=bin_embedding_dim, alpha=attractor_alpha, + gamma=attractor_gamma, kind=attractor_kind, + attractor_type=attractor_type, memory_efficient=memory_efficient, + min_depth=conf["min_depth"], max_depth=conf["max_depth"]) + for i in range(len(n_attractors)) + ]) + for conf in bin_conf} + ) + + last_in = N_MIDAS_OUT + # conditional log binomial for each bin conf + self.conditional_log_binomial = nn.ModuleDict( + {conf['name']: ConditionalLogBinomial(last_in, bin_embedding_dim, conf['n_bins'], bottleneck_factor=4, min_temp=self.min_temp, max_temp=self.max_temp) + for conf in bin_conf} + ) + + def forward(self, x, return_final_centers=False, denorm=False, return_probs=False, **kwargs): + """ + Args: + x (torch.Tensor): Input image tensor of shape (B, C, H, W). Assumes all images are from the same domain. + return_final_centers (bool, optional): Whether to return the final centers of the attractors. Defaults to False. + denorm (bool, optional): Whether to denormalize the input image. Defaults to False. + return_probs (bool, optional): Whether to return the probabilities of the bins. Defaults to False. + + Returns: + dict: Dictionary of outputs with keys: + - "rel_depth": Relative depth map of shape (B, 1, H, W) + - "metric_depth": Metric depth map of shape (B, 1, H, W) + - "domain_logits": Domain logits of shape (B, 2) + - "bin_centers": Bin centers of shape (B, N, H, W). Present only if return_final_centers is True + - "probs": Bin probabilities of shape (B, N, H, W). Present only if return_probs is True + """ + b, c, h, w = x.shape + self.orig_input_width = w + self.orig_input_height = h + rel_depth, out = self.core(x, denorm=denorm, return_rel_depth=True) + + outconv_activation = out[0] + btlnck = out[1] + x_blocks = out[2:] + + x_d0 = self.conv2(btlnck) + x = x_d0 + + # Predict which path to take + embedding = self.patch_transformer(x)[0] # N, E + domain_logits = self.mlp_classifier(embedding) # N, 2 + domain_vote = torch.softmax(domain_logits.sum( + dim=0, keepdim=True), dim=-1) # 1, 2 + + # Get the path + bin_conf_name = ["nyu", "kitti"][torch.argmax( + domain_vote, dim=-1).squeeze().item()] + + try: + conf = [c for c in self.bin_conf if c.name == bin_conf_name][0] + except IndexError: + raise ValueError( + f"bin_conf_name {bin_conf_name} not found in bin_confs") + + min_depth = conf['min_depth'] + max_depth = conf['max_depth'] + + seed_bin_regressor = self.seed_bin_regressors[bin_conf_name] + _, seed_b_centers = seed_bin_regressor(x) + if self.bin_centers_type == 'normed' or self.bin_centers_type == 'hybrid2': + b_prev = (seed_b_centers - min_depth)/(max_depth - min_depth) + else: + b_prev = seed_b_centers + prev_b_embedding = self.seed_projector(x) + + attractors = self.attractors[bin_conf_name] + for projector, attractor, x in zip(self.projectors, attractors, x_blocks): + b_embedding = projector(x) + b, b_centers = attractor( + b_embedding, b_prev, prev_b_embedding, interpolate=True) + b_prev = b + prev_b_embedding = b_embedding + + last = outconv_activation + + b_centers = nn.functional.interpolate( + b_centers, last.shape[-2:], mode='bilinear', align_corners=True) + b_embedding = nn.functional.interpolate( + b_embedding, last.shape[-2:], mode='bilinear', align_corners=True) + + clb = self.conditional_log_binomial[bin_conf_name] + x = clb(last, b_embedding) + + # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor + # print(x.shape, b_centers.shape) + # b_centers = nn.functional.interpolate(b_centers, x.shape[-2:], mode='bilinear', align_corners=True) + out = torch.sum(x * b_centers, dim=1, keepdim=True) + + output = dict(domain_logits=domain_logits, metric_depth=out) + if return_final_centers or return_probs: + output['bin_centers'] = b_centers + + if return_probs: + output['probs'] = x + return output + + def get_lr_params(self, lr): + """ + Learning rate configuration for different layers of the model + + Args: + lr (float) : Base learning rate + Returns: + list : list of parameters to optimize and their learning rates, in the format required by torch optimizers. + """ + param_conf = [] + if self.train_midas: + def get_rel_pos_params(): + for name, p in self.core.core.pretrained.named_parameters(): + if "relative_position" in name: + yield p + + def get_enc_params_except_rel_pos(): + for name, p in self.core.core.pretrained.named_parameters(): + if "relative_position" not in name: + yield p + + encoder_params = get_enc_params_except_rel_pos() + rel_pos_params = get_rel_pos_params() + midas_params = self.core.core.scratch.parameters() + midas_lr_factor = self.midas_lr_factor if self.is_midas_pretrained else 1.0 + param_conf.extend([ + {'params': encoder_params, 'lr': lr / self.encoder_lr_factor}, + {'params': rel_pos_params, 'lr': lr / self.pos_enc_lr_factor}, + {'params': midas_params, 'lr': lr / midas_lr_factor} + ]) + + remaining_modules = [] + for name, child in self.named_children(): + if name != 'core': + remaining_modules.append(child) + remaining_params = itertools.chain( + *[child.parameters() for child in remaining_modules]) + param_conf.append({'params': remaining_params, 'lr': lr}) + return param_conf + + def get_conf_parameters(self, conf_name): + """ + Returns parameters of all the ModuleDicts children that are exclusively used for the given bin configuration + """ + params = [] + for name, child in self.named_children(): + if isinstance(child, nn.ModuleDict): + for bin_conf_name, module in child.items(): + if bin_conf_name == conf_name: + params += list(module.parameters()) + return params + + def freeze_conf(self, conf_name): + """ + Freezes all the parameters of all the ModuleDicts children that are exclusively used for the given bin configuration + """ + for p in self.get_conf_parameters(conf_name): + p.requires_grad = False + + def unfreeze_conf(self, conf_name): + """ + Unfreezes all the parameters of all the ModuleDicts children that are exclusively used for the given bin configuration + """ + for p in self.get_conf_parameters(conf_name): + p.requires_grad = True + + def freeze_all_confs(self): + """ + Freezes all the parameters of all the ModuleDicts children + """ + for name, child in self.named_children(): + if isinstance(child, nn.ModuleDict): + for bin_conf_name, module in child.items(): + for p in module.parameters(): + p.requires_grad = False + + @staticmethod + def build(midas_model_type="DPT_BEiT_L_384", pretrained_resource=None, use_pretrained_midas=False, train_midas=False, freeze_midas_bn=True, **kwargs): + core = MidasCore.build(midas_model_type=midas_model_type, use_pretrained_midas=use_pretrained_midas, + train_midas=train_midas, fetch_features=True, freeze_bn=freeze_midas_bn, **kwargs) + model = ZoeDepthNK(core, **kwargs) + if pretrained_resource: + pretrained_resource="local::./models/monoD/zoeDepth/ckpts/ZoeD_M12_NK.pt" + assert isinstance(pretrained_resource, str), "pretrained_resource must be a string" + model = load_state_from_resource(model, pretrained_resource) + return model + + @staticmethod + def build_from_config(config): + + return ZoeDepthNK.build(**config) diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2668792389157609abb2a0846fb620e7d67eb9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/__init__.py @@ -0,0 +1,24 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/arg_utils.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/arg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3004ec3679c0a40fd8961253733fb4343ad545 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/arg_utils.py @@ -0,0 +1,33 @@ + + +def infer_type(x): # hacky way to infer type from string args + if not isinstance(x, str): + return x + + try: + x = int(x) + return x + except ValueError: + pass + + try: + x = float(x) + return x + except ValueError: + pass + + return x + + +def parse_unknown(unknown_args): + clean = [] + for a in unknown_args: + if "=" in a: + k, v = a.split("=") + clean.extend([k, v]) + else: + clean.append(a) + + keys = clean[::2] + values = clean[1::2] + return {k.replace("--", ""): infer_type(v) for k, v in zip(keys, values)} diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/config.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c1b8209af82ae7803ffd1f6f4023b2ffda29f195 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/config.py @@ -0,0 +1,437 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import json +import os + +from models.monoD.zoeDepth.utils.easydict import EasyDict as edict + +from models.monoD.zoeDepth.utils.arg_utils import infer_type +import pathlib +import platform + +ROOT = pathlib.Path(__file__).parent.parent.resolve() + +HOME_DIR = os.path.expanduser("~") + +COMMON_CONFIG = { + "save_dir": os.path.expanduser("~/shortcuts/monodepth3_checkpoints"), + "project": "ZoeDepth", + "tags": '', + "notes": "", + "gpu": None, + "root": ".", + "uid": None, + "print_losses": False +} + +DATASETS_CONFIG = { + "kitti": { + "dataset": "kitti", + "min_depth": 0.001, + "max_depth": 80, + "data_path": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/raw"), + "gt_path": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/gts"), + "filenames_file": "./train_test_inputs/kitti_eigen_train_files_with_gt.txt", + "input_height": 352, + "input_width": 1216, # 704 + "data_path_eval": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/raw"), + "gt_path_eval": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/gts"), + "filenames_file_eval": "./train_test_inputs/kitti_eigen_test_files_with_gt.txt", + + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + + "do_random_rotate": True, + "degree": 1.0, + "do_kb_crop": True, + "garg_crop": True, + "eigen_crop": False, + "use_right": False + }, + "kitti_test": { + "dataset": "kitti", + "min_depth": 0.001, + "max_depth": 80, + "data_path": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/raw"), + "gt_path": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/gts"), + "filenames_file": "./train_test_inputs/kitti_eigen_train_files_with_gt.txt", + "input_height": 352, + "input_width": 1216, + "data_path_eval": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/raw"), + "gt_path_eval": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/gts"), + "filenames_file_eval": "./train_test_inputs/kitti_eigen_test_files_with_gt.txt", + + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + + "do_random_rotate": False, + "degree": 1.0, + "do_kb_crop": True, + "garg_crop": True, + "eigen_crop": False, + "use_right": False + }, + "nyu": { + "dataset": "nyu", + "avoid_boundary": False, + "min_depth": 1e-3, # originally 0.1 + "max_depth": 10, + "data_path": os.path.join(HOME_DIR, "shortcuts/datasets/nyu_depth_v2/sync/"), + "gt_path": os.path.join(HOME_DIR, "shortcuts/datasets/nyu_depth_v2/sync/"), + "filenames_file": "./train_test_inputs/nyudepthv2_train_files_with_gt.txt", + "input_height": 480, + "input_width": 640, + "data_path_eval": os.path.join(HOME_DIR, "shortcuts/datasets/nyu_depth_v2/official_splits/test/"), + "gt_path_eval": os.path.join(HOME_DIR, "shortcuts/datasets/nyu_depth_v2/official_splits/test/"), + "filenames_file_eval": "./train_test_inputs/nyudepthv2_test_files_with_gt.txt", + "min_depth_eval": 1e-3, + "max_depth_eval": 10, + "min_depth_diff": -10, + "max_depth_diff": 10, + + "do_random_rotate": True, + "degree": 1.0, + "do_kb_crop": False, + "garg_crop": False, + "eigen_crop": True + }, + "ibims": { + "dataset": "ibims", + "ibims_root": os.path.join(HOME_DIR, "shortcuts/datasets/ibims/ibims1_core_raw/"), + "eigen_crop": True, + "garg_crop": False, + "do_kb_crop": False, + "min_depth_eval": 0, + "max_depth_eval": 10, + "min_depth": 1e-3, + "max_depth": 10 + }, + "sunrgbd": { + "dataset": "sunrgbd", + "sunrgbd_root": os.path.join(HOME_DIR, "shortcuts/datasets/SUNRGBD/test/"), + "eigen_crop": True, + "garg_crop": False, + "do_kb_crop": False, + "min_depth_eval": 0, + "max_depth_eval": 8, + "min_depth": 1e-3, + "max_depth": 10 + }, + "diml_indoor": { + "dataset": "diml_indoor", + "diml_indoor_root": os.path.join(HOME_DIR, "shortcuts/datasets/diml_indoor_test/"), + "eigen_crop": True, + "garg_crop": False, + "do_kb_crop": False, + "min_depth_eval": 0, + "max_depth_eval": 10, + "min_depth": 1e-3, + "max_depth": 10 + }, + "diml_outdoor": { + "dataset": "diml_outdoor", + "diml_outdoor_root": os.path.join(HOME_DIR, "shortcuts/datasets/diml_outdoor_test/"), + "eigen_crop": False, + "garg_crop": True, + "do_kb_crop": False, + "min_depth_eval": 2, + "max_depth_eval": 80, + "min_depth": 1e-3, + "max_depth": 80 + }, + "diode_indoor": { + "dataset": "diode_indoor", + "diode_indoor_root": os.path.join(HOME_DIR, "shortcuts/datasets/diode_indoor/"), + "eigen_crop": True, + "garg_crop": False, + "do_kb_crop": False, + "min_depth_eval": 1e-3, + "max_depth_eval": 10, + "min_depth": 1e-3, + "max_depth": 10 + }, + "diode_outdoor": { + "dataset": "diode_outdoor", + "diode_outdoor_root": os.path.join(HOME_DIR, "shortcuts/datasets/diode_outdoor/"), + "eigen_crop": False, + "garg_crop": True, + "do_kb_crop": False, + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + "min_depth": 1e-3, + "max_depth": 80 + }, + "hypersim_test": { + "dataset": "hypersim_test", + "hypersim_test_root": os.path.join(HOME_DIR, "shortcuts/datasets/hypersim_test/"), + "eigen_crop": True, + "garg_crop": False, + "do_kb_crop": False, + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + "min_depth": 1e-3, + "max_depth": 10 + }, + "vkitti": { + "dataset": "vkitti", + "vkitti_root": os.path.join(HOME_DIR, "shortcuts/datasets/vkitti_test/"), + "eigen_crop": False, + "garg_crop": True, + "do_kb_crop": True, + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + "min_depth": 1e-3, + "max_depth": 80 + }, + "vkitti2": { + "dataset": "vkitti2", + "vkitti2_root": os.path.join(HOME_DIR, "shortcuts/datasets/vkitti2/"), + "eigen_crop": False, + "garg_crop": True, + "do_kb_crop": True, + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + "min_depth": 1e-3, + "max_depth": 80, + }, + "ddad": { + "dataset": "ddad", + "ddad_root": os.path.join(HOME_DIR, "shortcuts/datasets/ddad/ddad_val/"), + "eigen_crop": False, + "garg_crop": True, + "do_kb_crop": True, + "min_depth_eval": 1e-3, + "max_depth_eval": 80, + "min_depth": 1e-3, + "max_depth": 80, + }, +} + +ALL_INDOOR = ["nyu", "ibims", "sunrgbd", "diode_indoor", "hypersim_test"] +ALL_OUTDOOR = ["kitti", "diml_outdoor", "diode_outdoor", "vkitti2", "ddad"] +ALL_EVAL_DATASETS = ALL_INDOOR + ALL_OUTDOOR + +COMMON_TRAINING_CONFIG = { + "dataset": "nyu", + "distributed": True, + "workers": 16, + "clip_grad": 0.1, + "use_shared_dict": False, + "shared_dict": None, + "use_amp": False, + + "aug": True, + "random_crop": False, + "random_translate": False, + "translate_prob": 0.2, + "max_translation": 100, + + "validate_every": 0.25, + "log_images_every": 0.1, + "prefetch": False, +} + + +def flatten(config, except_keys=('bin_conf')): + def recurse(inp): + if isinstance(inp, dict): + for key, value in inp.items(): + if key in except_keys: + yield (key, value) + if isinstance(value, dict): + yield from recurse(value) + else: + yield (key, value) + + return dict(list(recurse(config))) + + +def split_combined_args(kwargs): + """Splits the arguments that are combined with '__' into multiple arguments. + Combined arguments should have equal number of keys and values. + Keys are separated by '__' and Values are separated with ';'. + For example, '__n_bins__lr=256;0.001' + + Args: + kwargs (dict): key-value pairs of arguments where key-value is optionally combined according to the above format. + + Returns: + dict: Parsed dict with the combined arguments split into individual key-value pairs. + """ + new_kwargs = dict(kwargs) + for key, value in kwargs.items(): + if key.startswith("__"): + keys = key.split("__")[1:] + values = value.split(";") + assert len(keys) == len( + values), f"Combined arguments should have equal number of keys and values. Keys are separated by '__' and Values are separated with ';'. For example, '__n_bins__lr=256;0.001. Given (keys,values) is ({keys}, {values})" + for k, v in zip(keys, values): + new_kwargs[k] = v + return new_kwargs + + +def parse_list(config, key, dtype=int): + """Parse a list of values for the key if the value is a string. The values are separated by a comma. + Modifies the config in place. + """ + if key in config: + if isinstance(config[key], str): + config[key] = list(map(dtype, config[key].split(','))) + assert isinstance(config[key], list) and all([isinstance(e, dtype) for e in config[key]] + ), f"{key} should be a list of values dtype {dtype}. Given {config[key]} of type {type(config[key])} with values of type {[type(e) for e in config[key]]}." + + +def get_model_config(model_name, model_version=None): + """Find and parse the .json config file for the model. + + Args: + model_name (str): name of the model. The config file should be named config_{model_name}[_{model_version}].json under the models/{model_name} directory. + model_version (str, optional): Specific config version. If specified config_{model_name}_{model_version}.json is searched for and used. Otherwise config_{model_name}.json is used. Defaults to None. + + Returns: + easydict: the config dictionary for the model. + """ + config_fname = f"config_{model_name}_{model_version}.json" if model_version is not None else f"config_{model_name}.json" + config_file = os.path.join(ROOT, "models", model_name, config_fname) + if not os.path.exists(config_file): + return None + + with open(config_file, "r") as f: + config = edict(json.load(f)) + + # handle dictionary inheritance + # only training config is supported for inheritance + if "inherit" in config.train and config.train.inherit is not None: + inherit_config = get_model_config(config.train["inherit"]).train + for key, value in inherit_config.items(): + if key not in config.train: + config.train[key] = value + return edict(config) + + +def update_model_config(config, mode, model_name, model_version=None, strict=False): + model_config = get_model_config(model_name, model_version) + if model_config is not None: + config = {**config, ** + flatten({**model_config.model, **model_config[mode]})} + elif strict: + raise ValueError(f"Config file for model {model_name} not found.") + return config + + +def check_choices(name, value, choices): + # return # No checks in dev branch + if value not in choices: + raise ValueError(f"{name} {value} not in supported choices {choices}") + + +KEYS_TYPE_BOOL = ["use_amp", "distributed", "use_shared_dict", "same_lr", "aug", "three_phase", + "prefetch", "cycle_momentum"] # Casting is not necessary as their int casted values in config are 0 or 1 + + +def get_config(model_name, mode='train', dataset=None, **overwrite_kwargs): + """Main entry point to get the config for the model. + + Args: + model_name (str): name of the desired model. + mode (str, optional): "train" or "infer". Defaults to 'train'. + dataset (str, optional): If specified, the corresponding dataset configuration is loaded as well. Defaults to None. + + Keyword Args: key-value pairs of arguments to overwrite the default config. + + The order of precedence for overwriting the config is (Higher precedence first): + # 1. overwrite_kwargs + # 2. "config_version": Config file version if specified in overwrite_kwargs. The corresponding config loaded is config_{model_name}_{config_version}.json + # 3. "version_name": Default Model version specific config specified in overwrite_kwargs. The corresponding config loaded is config_{model_name}_{version_name}.json + # 4. common_config: Default config for all models specified in COMMON_CONFIG + + Returns: + easydict: The config dictionary for the model. + """ + + + check_choices("Model", model_name, ["zoedepth", "zoedepth_nk"]) + check_choices("Mode", mode, ["train", "infer", "eval"]) + if mode == "train": + check_choices("Dataset", dataset, ["nyu", "kitti", "mix", None]) + + config = flatten({**COMMON_CONFIG, **COMMON_TRAINING_CONFIG}) + config = update_model_config(config, mode, model_name) + + # update with model version specific config + version_name = overwrite_kwargs.get("version_name", config["version_name"]) + config = update_model_config(config, mode, model_name, version_name) + + # update with config version if specified + config_version = overwrite_kwargs.get("config_version", None) + if config_version is not None: + print("Overwriting config with config_version", config_version) + config = update_model_config(config, mode, model_name, config_version) + + # update with overwrite_kwargs + # Combined args are useful for hyperparameter search + overwrite_kwargs = split_combined_args(overwrite_kwargs) + config = {**config, **overwrite_kwargs} + + # Casting to bool # TODO: Not necessary. Remove and test + for key in KEYS_TYPE_BOOL: + if key in config: + config[key] = bool(config[key]) + + # Model specific post processing of config + parse_list(config, "n_attractors") + + # adjust n_bins for each bin configuration if bin_conf is given and n_bins is passed in overwrite_kwargs + if 'bin_conf' in config and 'n_bins' in overwrite_kwargs: + bin_conf = config['bin_conf'] # list of dicts + n_bins = overwrite_kwargs['n_bins'] + new_bin_conf = [] + for conf in bin_conf: + conf['n_bins'] = n_bins + new_bin_conf.append(conf) + config['bin_conf'] = new_bin_conf + + if mode == "train": + orig_dataset = dataset + if dataset == "mix": + dataset = 'nyu' # Use nyu as default for mix. Dataset config is changed accordingly while loading the dataloader + if dataset is not None: + config['project'] = f"MonoDepth3-{orig_dataset}" # Set project for wandb + + if dataset is not None: + config['dataset'] = dataset + config = {**DATASETS_CONFIG[dataset], **config} + + + config['model'] = model_name + typed_config = {k: infer_type(v) for k, v in config.items()} + # add hostname to config + config['hostname'] = platform.node() + return edict(typed_config) + + +def change_dataset(config, new_dataset): + config.update(DATASETS_CONFIG[new_dataset]) + return config diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/easydict/__init__.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/easydict/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15928179b0182c6045d98bc0a7be1c6ca45f675e --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/easydict/__init__.py @@ -0,0 +1,158 @@ +""" +EasyDict +Copy/pasted from https://github.com/makinacorpus/easydict +Original author: Mathieu Leplatre +""" + +class EasyDict(dict): + """ + Get attributes + + >>> d = EasyDict({'foo':3}) + >>> d['foo'] + 3 + >>> d.foo + 3 + >>> d.bar + Traceback (most recent call last): + ... + AttributeError: 'EasyDict' object has no attribute 'bar' + + Works recursively + + >>> d = EasyDict({'foo':3, 'bar':{'x':1, 'y':2}}) + >>> isinstance(d.bar, dict) + True + >>> d.bar.x + 1 + + Bullet-proof + + >>> EasyDict({}) + {} + >>> EasyDict(d={}) + {} + >>> EasyDict(None) + {} + >>> d = {'a': 1} + >>> EasyDict(**d) + {'a': 1} + >>> EasyDict((('a', 1), ('b', 2))) + {'a': 1, 'b': 2} + + Set attributes + + >>> d = EasyDict() + >>> d.foo = 3 + >>> d.foo + 3 + >>> d.bar = {'prop': 'value'} + >>> d.bar.prop + 'value' + >>> d + {'foo': 3, 'bar': {'prop': 'value'}} + >>> d.bar.prop = 'newer' + >>> d.bar.prop + 'newer' + + + Values extraction + + >>> d = EasyDict({'foo':0, 'bar':[{'x':1, 'y':2}, {'x':3, 'y':4}]}) + >>> isinstance(d.bar, list) + True + >>> from operator import attrgetter + >>> list(map(attrgetter('x'), d.bar)) + [1, 3] + >>> list(map(attrgetter('y'), d.bar)) + [2, 4] + >>> d = EasyDict() + >>> list(d.keys()) + [] + >>> d = EasyDict(foo=3, bar=dict(x=1, y=2)) + >>> d.foo + 3 + >>> d.bar.x + 1 + + Still like a dict though + + >>> o = EasyDict({'clean':True}) + >>> list(o.items()) + [('clean', True)] + + And like a class + + >>> class Flower(EasyDict): + ... power = 1 + ... + >>> f = Flower() + >>> f.power + 1 + >>> f = Flower({'height': 12}) + >>> f.height + 12 + >>> f['power'] + 1 + >>> sorted(f.keys()) + ['height', 'power'] + + update and pop items + >>> d = EasyDict(a=1, b='2') + >>> e = EasyDict(c=3.0, a=9.0) + >>> d.update(e) + >>> d.c + 3.0 + >>> d['c'] + 3.0 + >>> d.get('c') + 3.0 + >>> d.update(a=4, b=4) + >>> d.b + 4 + >>> d.pop('a') + 4 + >>> d.a + Traceback (most recent call last): + ... + AttributeError: 'EasyDict' object has no attribute 'a' + """ + def __init__(self, d=None, **kwargs): + if d is None: + d = {} + else: + d = dict(d) + if kwargs: + d.update(**kwargs) + for k, v in d.items(): + setattr(self, k, v) + # Class attributes + for k in self.__class__.__dict__.keys(): + if not (k.startswith('__') and k.endswith('__')) and not k in ('update', 'pop'): + setattr(self, k, getattr(self, k)) + + def __setattr__(self, name, value): + if isinstance(value, (list, tuple)): + value = [self.__class__(x) + if isinstance(x, dict) else x for x in value] + elif isinstance(value, dict) and not isinstance(value, self.__class__): + value = self.__class__(value) + super(EasyDict, self).__setattr__(name, value) + super(EasyDict, self).__setitem__(name, value) + + __setitem__ = __setattr__ + + def update(self, e=None, **f): + d = e or dict() + d.update(f) + for k in d: + setattr(self, k, d[k]) + + def pop(self, k, d=None): + delattr(self, k) + return super(EasyDict, self).pop(k, d) + + +if __name__ == "__main__": + import doctest + doctest.testmod() \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/geometry.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..e3da8c75b5a8e39b4b58a4dcd827b84d79b9115c --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/geometry.py @@ -0,0 +1,98 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +import numpy as np + +def get_intrinsics(H,W): + """ + Intrinsics for a pinhole camera model. + Assume fov of 55 degrees and central principal point. + """ + f = 0.5 * W / np.tan(0.5 * 55 * np.pi / 180.0) + cx = 0.5 * W + cy = 0.5 * H + return np.array([[f, 0, cx], + [0, f, cy], + [0, 0, 1]]) + +def depth_to_points(depth, R=None, t=None): + + K = get_intrinsics(depth.shape[1], depth.shape[2]) + Kinv = np.linalg.inv(K) + if R is None: + R = np.eye(3) + if t is None: + t = np.zeros(3) + + # M converts from your coordinate to PyTorch3D's coordinate system + M = np.eye(3) + M[0, 0] = -1.0 + M[1, 1] = -1.0 + + height, width = depth.shape[1:3] + + x = np.arange(width) + y = np.arange(height) + coord = np.stack(np.meshgrid(x, y), -1) + coord = np.concatenate((coord, np.ones_like(coord)[:, :, [0]]), -1) # z=1 + coord = coord.astype(np.float32) + # coord = torch.as_tensor(coord, dtype=torch.float32, device=device) + coord = coord[None] # bs, h, w, 3 + + D = depth[:, :, :, None, None] + # print(D.shape, Kinv[None, None, None, ...].shape, coord[:, :, :, :, None].shape ) + pts3D_1 = D * Kinv[None, None, None, ...] @ coord[:, :, :, :, None] + # pts3D_1 live in your coordinate system. Convert them to Py3D's + pts3D_1 = M[None, None, None, ...] @ pts3D_1 + # from reference to targe tviewpoint + pts3D_2 = R[None, None, None, ...] @ pts3D_1 + t[None, None, None, :, None] + # pts3D_2 = pts3D_1 + # depth_2 = pts3D_2[:, :, :, 2, :] # b,1,h,w + return pts3D_2[:, :, :, :3, 0][0] + + +def create_triangles(h, w, mask=None): + """ + Reference: https://github.com/google-research/google-research/blob/e96197de06613f1b027d20328e06d69829fa5a89/infinite_nature/render_utils.py#L68 + Creates mesh triangle indices from a given pixel grid size. + This function is not and need not be differentiable as triangle indices are + fixed. + Args: + h: (int) denoting the height of the image. + w: (int) denoting the width of the image. + Returns: + triangles: 2D numpy array of indices (int) with shape (2(W-1)(H-1) x 3) + """ + x, y = np.meshgrid(range(w - 1), range(h - 1)) + tl = y * w + x + tr = y * w + x + 1 + bl = (y + 1) * w + x + br = (y + 1) * w + x + 1 + triangles = np.array([tl, bl, tr, br, tr, bl]) + triangles = np.transpose(triangles, (1, 2, 0)).reshape( + ((w - 1) * (h - 1) * 2, 3)) + if mask is not None: + mask = mask.reshape(-1) + triangles = triangles[mask[triangles].all(1)] + return triangles diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/misc.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..4bbe403d3669829eecdf658458c76aa5e87e2b33 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/utils/misc.py @@ -0,0 +1,368 @@ +# MIT License + +# Copyright (c) 2022 Intelligent Systems Lab Org + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# File author: Shariq Farooq Bhat + +"""Miscellaneous utility functions.""" + +from scipy import ndimage + +import base64 +import math +import re +from io import BytesIO + +import matplotlib +import matplotlib.cm +import numpy as np +import requests +import torch +import torch.distributed as dist +import torch.nn +import torch.nn as nn +import torch.utils.data.distributed +from PIL import Image +from torchvision.transforms import ToTensor + + +class RunningAverage: + def __init__(self): + self.avg = 0 + self.count = 0 + + def append(self, value): + self.avg = (value + self.count * self.avg) / (self.count + 1) + self.count += 1 + + def get_value(self): + return self.avg + + +def denormalize(x): + """Reverses the imagenet normalization applied to the input. + + Args: + x (torch.Tensor - shape(N,3,H,W)): input tensor + + Returns: + torch.Tensor - shape(N,3,H,W): Denormalized input + """ + mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(x.device) + std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(x.device) + return x * std + mean + + +class RunningAverageDict: + """A dictionary of running averages.""" + def __init__(self): + self._dict = None + + def update(self, new_dict): + if new_dict is None: + return + + if self._dict is None: + self._dict = dict() + for key, value in new_dict.items(): + self._dict[key] = RunningAverage() + + for key, value in new_dict.items(): + self._dict[key].append(value) + + def get_value(self): + if self._dict is None: + return None + return {key: value.get_value() for key, value in self._dict.items()} + + +def colorize(value, vmin=None, vmax=None, cmap='gray_r', invalid_val=-99, invalid_mask=None, background_color=(128, 128, 128, 255), gamma_corrected=False, value_transform=None): + """Converts a depth map to a color image. + + Args: + value (torch.Tensor, numpy.ndarry): Input depth map. Shape: (H, W) or (1, H, W) or (1, 1, H, W). All singular dimensions are squeezed + vmin (float, optional): vmin-valued entries are mapped to start color of cmap. If None, value.min() is used. Defaults to None. + vmax (float, optional): vmax-valued entries are mapped to end color of cmap. If None, value.max() is used. Defaults to None. + cmap (str, optional): matplotlib colormap to use. Defaults to 'magma_r'. + invalid_val (int, optional): Specifies value of invalid pixels that should be colored as 'background_color'. Defaults to -99. + invalid_mask (numpy.ndarray, optional): Boolean mask for invalid regions. Defaults to None. + background_color (tuple[int], optional): 4-tuple RGB color to give to invalid pixels. Defaults to (128, 128, 128, 255). + gamma_corrected (bool, optional): Apply gamma correction to colored image. Defaults to False. + value_transform (Callable, optional): Apply transform function to valid pixels before coloring. Defaults to None. + + Returns: + numpy.ndarray, dtype - uint8: Colored depth map. Shape: (H, W, 4) + """ + if isinstance(value, torch.Tensor): + value = value.detach().cpu().numpy() + + value = value.squeeze() + if invalid_mask is None: + invalid_mask = value == invalid_val + mask = np.logical_not(invalid_mask) + + # normalize + vmin = np.percentile(value[mask],2) if vmin is None else vmin + vmax = np.percentile(value[mask],85) if vmax is None else vmax + if vmin != vmax: + value = (value - vmin) / (vmax - vmin) # vmin..vmax + else: + # Avoid 0-division + value = value * 0. + + # squeeze last dim if it exists + # grey out the invalid values + + value[invalid_mask] = np.nan + cmapper = matplotlib.cm.get_cmap(cmap) + if value_transform: + value = value_transform(value) + # value = value / value.max() + value = cmapper(value, bytes=True) # (nxmx4) + + # img = value[:, :, :] + img = value[...] + img[invalid_mask] = background_color + + # return img.transpose((2, 0, 1)) + if gamma_corrected: + # gamma correction + img = img / 255 + img = np.power(img, 2.2) + img = img * 255 + img = img.astype(np.uint8) + return img + + +def count_parameters(model, include_all=False): + return sum(p.numel() for p in model.parameters() if p.requires_grad or include_all) + + +def compute_errors(gt, pred): + """Compute metrics for 'pred' compared to 'gt' + + Args: + gt (numpy.ndarray): Ground truth values + pred (numpy.ndarray): Predicted values + + gt.shape should be equal to pred.shape + + Returns: + dict: Dictionary containing the following metrics: + 'a1': Delta1 accuracy: Fraction of pixels that are within a scale factor of 1.25 + 'a2': Delta2 accuracy: Fraction of pixels that are within a scale factor of 1.25^2 + 'a3': Delta3 accuracy: Fraction of pixels that are within a scale factor of 1.25^3 + 'abs_rel': Absolute relative error + 'rmse': Root mean squared error + 'log_10': Absolute log10 error + 'sq_rel': Squared relative error + 'rmse_log': Root mean squared error on the log scale + 'silog': Scale invariant log error + """ + thresh = np.maximum((gt / pred), (pred / gt)) + a1 = (thresh < 1.25).mean() + a2 = (thresh < 1.25 ** 2).mean() + a3 = (thresh < 1.25 ** 3).mean() + + abs_rel = np.mean(np.abs(gt - pred) / gt) + sq_rel = np.mean(((gt - pred) ** 2) / gt) + + rmse = (gt - pred) ** 2 + rmse = np.sqrt(rmse.mean()) + + rmse_log = (np.log(gt) - np.log(pred)) ** 2 + rmse_log = np.sqrt(rmse_log.mean()) + + err = np.log(pred) - np.log(gt) + silog = np.sqrt(np.mean(err ** 2) - np.mean(err) ** 2) * 100 + + log_10 = (np.abs(np.log10(gt) - np.log10(pred))).mean() + return dict(a1=a1, a2=a2, a3=a3, abs_rel=abs_rel, rmse=rmse, log_10=log_10, rmse_log=rmse_log, + silog=silog, sq_rel=sq_rel) + + +def compute_metrics(gt, pred, interpolate=True, garg_crop=False, eigen_crop=True, dataset='nyu', min_depth_eval=0.1, max_depth_eval=10, **kwargs): + """Compute metrics of predicted depth maps. Applies cropping and masking as necessary or specified via arguments. Refer to compute_errors for more details on metrics. + """ + if 'config' in kwargs: + config = kwargs['config'] + garg_crop = config.garg_crop + eigen_crop = config.eigen_crop + min_depth_eval = config.min_depth_eval + max_depth_eval = config.max_depth_eval + + if gt.shape[-2:] != pred.shape[-2:] and interpolate: + pred = nn.functional.interpolate( + pred, gt.shape[-2:], mode='bilinear', align_corners=True) + + pred = pred.squeeze().cpu().numpy() + pred[pred < min_depth_eval] = min_depth_eval + pred[pred > max_depth_eval] = max_depth_eval + pred[np.isinf(pred)] = max_depth_eval + pred[np.isnan(pred)] = min_depth_eval + + gt_depth = gt.squeeze().cpu().numpy() + valid_mask = np.logical_and( + gt_depth > min_depth_eval, gt_depth < max_depth_eval) + + if garg_crop or eigen_crop: + gt_height, gt_width = gt_depth.shape + eval_mask = np.zeros(valid_mask.shape) + + if garg_crop: + eval_mask[int(0.40810811 * gt_height):int(0.99189189 * gt_height), + int(0.03594771 * gt_width):int(0.96405229 * gt_width)] = 1 + + elif eigen_crop: + # print("-"*10, " EIGEN CROP ", "-"*10) + if dataset == 'kitti': + eval_mask[int(0.3324324 * gt_height):int(0.91351351 * gt_height), + int(0.0359477 * gt_width):int(0.96405229 * gt_width)] = 1 + else: + # assert gt_depth.shape == (480, 640), "Error: Eigen crop is currently only valid for (480, 640) images" + eval_mask[45:471, 41:601] = 1 + else: + eval_mask = np.ones(valid_mask.shape) + valid_mask = np.logical_and(valid_mask, eval_mask) + return compute_errors(gt_depth[valid_mask], pred[valid_mask]) + + +#################################### Model uilts ################################################ + + +def parallelize(config, model, find_unused_parameters=True): + + if config.gpu is not None: + torch.cuda.set_device(config.gpu) + model = model.cuda(config.gpu) + + config.multigpu = False + if config.distributed: + # Use DDP + config.multigpu = True + config.rank = config.rank * config.ngpus_per_node + config.gpu + dist.init_process_group(backend=config.dist_backend, init_method=config.dist_url, + world_size=config.world_size, rank=config.rank) + config.batch_size = int(config.batch_size / config.ngpus_per_node) + # config.batch_size = 8 + config.workers = int( + (config.num_workers + config.ngpus_per_node - 1) / config.ngpus_per_node) + print("Device", config.gpu, "Rank", config.rank, "batch size", + config.batch_size, "Workers", config.workers) + torch.cuda.set_device(config.gpu) + model = nn.SyncBatchNorm.convert_sync_batchnorm(model) + model = model.cuda(config.gpu) + model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[config.gpu], output_device=config.gpu, + find_unused_parameters=find_unused_parameters) + + elif config.gpu is None: + # Use DP + config.multigpu = True + model = model.cuda() + model = torch.nn.DataParallel(model) + + return model + + +################################################################################################# + + +##################################################################################################### + + +class colors: + '''Colors class: + Reset all colors with colors.reset + Two subclasses fg for foreground and bg for background. + Use as colors.subclass.colorname. + i.e. colors.fg.red or colors.bg.green + Also, the generic bold, disable, underline, reverse, strikethrough, + and invisible work with the main class + i.e. colors.bold + ''' + reset = '\033[0m' + bold = '\033[01m' + disable = '\033[02m' + underline = '\033[04m' + reverse = '\033[07m' + strikethrough = '\033[09m' + invisible = '\033[08m' + + class fg: + black = '\033[30m' + red = '\033[31m' + green = '\033[32m' + orange = '\033[33m' + blue = '\033[34m' + purple = '\033[35m' + cyan = '\033[36m' + lightgrey = '\033[37m' + darkgrey = '\033[90m' + lightred = '\033[91m' + lightgreen = '\033[92m' + yellow = '\033[93m' + lightblue = '\033[94m' + pink = '\033[95m' + lightcyan = '\033[96m' + + class bg: + black = '\033[40m' + red = '\033[41m' + green = '\033[42m' + orange = '\033[43m' + blue = '\033[44m' + purple = '\033[45m' + cyan = '\033[46m' + lightgrey = '\033[47m' + + +def printc(text, color): + print(f"{color}{text}{colors.reset}") + +############################################ + +def get_image_from_url(url): + response = requests.get(url) + img = Image.open(BytesIO(response.content)).convert("RGB") + return img + +def url_to_torch(url, size=(384, 384)): + img = get_image_from_url(url) + img = img.resize(size, Image.ANTIALIAS) + img = torch.from_numpy(np.asarray(img)).float() + img = img.permute(2, 0, 1) + img.div_(255) + return img + +def pil_to_batched_tensor(img): + return ToTensor()(img).unsqueeze(0) + +def save_raw_16bit(depth, fpath="raw.png"): + if isinstance(depth, torch.Tensor): + depth = depth.squeeze().cpu().numpy() + + assert isinstance(depth, np.ndarray), "Depth must be a torch tensor or numpy array" + assert depth.ndim == 2, "Depth must be 2D" + depth = depth * 256 # scale for 16-bit png + depth = depth.astype(np.uint16) + depth = Image.fromarray(depth) + depth.save(fpath) + print("Saved raw depth to", fpath) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/requirements.txt b/OVOW/engine/oneposeviagen/SpaTrackerV2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ffd8fee5284ada41285d6b9bd0187c74102759f2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/requirements.txt @@ -0,0 +1,34 @@ +gradio==5.31.0 +pydantic==2.10.6 +opencv-python-headless +einops +einx +plotly +prettytable +decord +easydict +flow_vis +moviepy==1.0.0 +safetensors +scikit-learn +hydra-core +omegaconf +albumentations +matplotlib +mediapy +scikit-image +pycolmap==3.11.1 +git+https://github.com/facebookresearch/segment-anything.git +git+https://github.com/EasternJournalist/utils3d.git#egg=utils3d +huggingface_hub +pyceres +kornia==0.8.1 +xformers==0.0.28 +timm +PyJWT +gdown +rich +decord +ray[default] +jaxtyping +transformers \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/scripts/download.sh b/OVOW/engine/oneposeviagen/SpaTrackerV2/scripts/download.sh new file mode 100644 index 0000000000000000000000000000000000000000..7e7c843ddb8a718608718da3634929402ed51d3e --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/scripts/download.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +# Download the example data using gdown +mkdir -p ./assets/example1 +gdown --id 1q6n2R5ihfMoD-dU_u5vfcMALZSihNgiq -O ./assets/example1/snowboard.npz diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/setup.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..570474df15d09c4c5b8fba8d841d7fcc59d90ca7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/setup.py @@ -0,0 +1,9 @@ +# src/fpose/setup.py +from setuptools import setup, find_packages + +setup( + name='models', + version='0.1', + package_dir={'models': 'models'}, + packages=find_packages(where='models', include=['models*']), +) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/tapip3d_viz.py b/OVOW/engine/oneposeviagen/SpaTrackerV2/tapip3d_viz.py new file mode 100644 index 0000000000000000000000000000000000000000..a0db6dc5c5de7be7747582ccdc08400878fe3df5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/tapip3d_viz.py @@ -0,0 +1,208 @@ +# Copyright (c) TAPIP3D team(https://tapip3d.github.io/) + +import os +import numpy as np +import cv2 +import json +import struct +import zlib +import argparse +from einops import rearrange +from pathlib import Path +import shutil +from tempfile import TemporaryDirectory +import http.server +import socketserver +import socket +import sys +from http.server import SimpleHTTPRequestHandler +from socketserver import ThreadingTCPServer +import base64 + +viz_html_path = Path(__file__).parent / "viz.html" +DEFAULT_PORT = 8000 + +def compress_and_write(filename, header, blob): + header_bytes = json.dumps(header).encode("utf-8") + header_len = struct.pack(" T H W C") * 255).astype(np.uint8) + rgb_video = np.stack([cv2.resize(frame, fixed_size, interpolation=cv2.INTER_AREA) + for frame in rgb_video]) + + depth_video = data["depths"].astype(np.float32) + depth_video = np.stack([cv2.resize(frame, fixed_size, interpolation=cv2.INTER_NEAREST) + for frame in depth_video]) + + scale_x = fixed_size[0] / W + scale_y = fixed_size[1] / H + intrinsics = intrinsics.copy() + intrinsics[:, 0, :] *= scale_x + intrinsics[:, 1, :] *= scale_y + + min_depth = float(depth_video.min()) * 0.8 + max_depth = float(depth_video.max()) * 1.5 + + depth_normalized = (depth_video - min_depth) / (max_depth - min_depth) + depth_int = (depth_normalized * ((1 << 16) - 1)).astype(np.uint16) + + depths_rgb = np.zeros((T, fixed_size[1], fixed_size[0], 3), dtype=np.uint8) + depths_rgb[:, :, :, 0] = (depth_int & 0xFF).astype(np.uint8) + depths_rgb[:, :, :, 1] = ((depth_int >> 8) & 0xFF).astype(np.uint8) + + first_frame_inv = np.linalg.inv(extrinsics[0]) + normalized_extrinsics = np.array([first_frame_inv @ ext for ext in extrinsics]) + + normalized_trajs = np.zeros_like(trajs) + for t in range(T): + homogeneous_trajs = np.concatenate([trajs[t], np.ones((trajs.shape[1], 1))], axis=1) + transformed_trajs = (first_frame_inv @ homogeneous_trajs.T).T + normalized_trajs[t] = transformed_trajs[:, :3] + + # Get conf data from npz file + conf_data = data["conf"].item() if "conf" in data else {} + + arrays = { + "rgb_video": rgb_video, + "depths_rgb": depths_rgb, + "intrinsics": intrinsics, + "extrinsics": normalized_extrinsics, + "inv_extrinsics": np.linalg.inv(normalized_extrinsics), + "trajectories": normalized_trajs.astype(np.float32), + "cameraZ": 0.0, + "visibs": data["visibs"] if "visibs" in data else None, + "confs": data["confs"] if "confs" in data else None + } + + header = {} + blob_parts = [] + offset = 0 + for key, arr in arrays.items(): + if arr is not None: + arr = np.ascontiguousarray(arr) + arr_bytes = arr.tobytes() + header[key] = { + "dtype": str(arr.dtype), + "shape": arr.shape, + "offset": offset, + "length": len(arr_bytes) + } + blob_parts.append(arr_bytes) + offset += len(arr_bytes) + + raw_blob = b"".join(blob_parts) + compressed_blob = zlib.compress(raw_blob, level=9) + + header["meta"] = { + "depthRange": [min_depth, max_depth], + "totalFrames": int(T), + "resolution": fixed_size, + "baseFrameRate": fps, + "numTrajectoryPoints": normalized_trajs.shape[1], + "fov": float(fov_y), + "fov_x": float(fov_x), + "original_aspect_ratio": float(original_aspect_ratio), + "fixed_aspect_ratio": float(fixed_size[0]/fixed_size[1]), + "depthFilter": conf_data.get("depthFilter", {}) + } + + compress_and_write(output_file, header, compressed_blob) + + if static_html_file is not None: + # encode the .bin file to a base64 string + with open(output_file, "rb") as f: + encoded_blob = base64.b64encode(f.read()).decode("ascii") + + with open(viz_html_path, "r", encoding="utf-8") as f: + html_template = f.read() + + injected_html = html_template.replace( + "", + f"\n" + ) + + with open(static_html_file, "w", encoding="utf-8") as f: + f.write(injected_html) + + + return None + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('input_file', help='Path to the input .result.npz file') + parser.add_argument('--width', '-W', type=int, default=256, help='Target width') + parser.add_argument('--height', '-H', type=int, default=192, help='Target height') + parser.add_argument('--fps', type=int, default=4, help='Base frame rate for playback') + parser.add_argument('--port', '-p', type=int, default=DEFAULT_PORT, help=f'Port to serve the visualization (default: {DEFAULT_PORT})') + parser.add_argument('--static-html', '-s', type=str, default=None, help='Path to the static HTML file') + + args = parser.parse_args() + + with TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + process_point_cloud_data( + args.input_file, + temp_path / "data.bin", + args.static_html, + width=args.width, + height=args.height, + fps=args.fps + ) + if args.static_html is not None: + return + shutil.copy(viz_html_path, temp_path / "index.html") + + os.chdir(temp_path) + print(f"Files ready in {temp_path}. Starting HTTP server...") + + host = "0.0.0.0" + port = int(args.port) + + Handler = SimpleHTTPRequestHandler + httpd = None + + try: + httpd = ThreadingTCPServer((host, port), Handler) + except OSError as e: + if e.errno == socket.errno.EADDRINUSE: + print(f"Port {port} is already in use, trying a random port...") + try: + httpd = ThreadingTCPServer((host, 0), Handler) + port = httpd.server_address[1] # Get the assigned port + except OSError as e2: + print(f"Failed to bind to a random port: {e2}", file=sys.stderr) + sys.exit(1) + else: + print(f"Failed to start server: {e}", file=sys.stderr) + sys.exit(1) + + if httpd: + print(f"Serving at http://{host}:{port}") + try: + httpd.serve_forever() + except KeyboardInterrupt: + print("\nServer stopped.") + finally: + httpd.server_close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/viz.html b/OVOW/engine/oneposeviagen/SpaTrackerV2/viz.html new file mode 100644 index 0000000000000000000000000000000000000000..7434f08dd51656d82deeaa63d653761b364e788f --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/viz.html @@ -0,0 +1,2115 @@ + + + + + + 3D Point Cloud Visualizer + + + + + + + +
+ +
+
Initializing...
+ +
+ + +
+
+
+ +
Frame 0 / 0
+ +
+ +
+
+ +
+

+ ☰ + Visualization Settings + +

+ +
+

Point Cloud

+
+ + +
+
+ + +
+
+ + +
+
+ +
+

Trajectory

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+

Camera

+
+ + +
+
+ + +
+
+ +
+

Keep History

+
+ + +
+
+ + +
+
+ +
+

Background

+
+ + +
+
+ +
+
+ + +
+
+
+ + +
+ +
+ +
+
Interactive Viewer of 3D Tracking
+
+ + + + + + + + + + + + + + + diff --git a/OVOW/engine/oneposeviagen/SpaTrackerV2/viz_copy.html b/OVOW/engine/oneposeviagen/SpaTrackerV2/viz_copy.html new file mode 100644 index 0000000000000000000000000000000000000000..0d083e2ea79565e1ea096c4907e2325078359be8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/SpaTrackerV2/viz_copy.html @@ -0,0 +1,2115 @@ + + + + + + 3D Point Cloud Visualizer + + + + + + + +
+ +
+
Initializing...
+ +
+ + +
+
+
+ +
Frame 0 / 0
+ +
+ +
+
+ +
+

+ ☰ + Visualization Settings + +

+ +
+

Point Cloud

+
+ + +
+
+ + +
+
+ + +
+
+ +
+

Trajectory

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+

Camera

+
+ + +
+
+ + +
+
+ +
+

Keep History

+
+ + +
+
+ + +
+
+ +
+

Background

+
+ + +
+
+ +
+
+ + +
+
+
+ + +
+ +
+ +
+
Interactive Viewer of 3D Tracking
+
+ + + + + + + + + + + + + + + diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/.gitignore b/OVOW/engine/oneposeviagen/TRELLIS2/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b7faf403d915ca307532bb0eb9cceaf0214e8e5b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/.gitignore @@ -0,0 +1,207 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/.gitmodules b/OVOW/engine/oneposeviagen/TRELLIS2/.gitmodules new file mode 100644 index 0000000000000000000000000000000000000000..d11da70baf0634103157fd411ad6a400269bfe32 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/.gitmodules @@ -0,0 +1,3 @@ +[submodule "o-voxel/third_party/eigen"] + path = o-voxel/third_party/eigen + url = https://gitlab.com/libeigen/eigen.git diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/LICENSE b/OVOW/engine/oneposeviagen/TRELLIS2/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..79656060de00aa4659ad2c276d5be8830664d544 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/README.md b/OVOW/engine/oneposeviagen/TRELLIS2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c0ad06b5dcb3f0ed57ec83bda599c7b00559325 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/README.md @@ -0,0 +1,334 @@ +![](assets/teaser.webp) + +# Native and Compact Structured Latents for 3D Generation + +Paper +Hugging Face + +Project Page +License + +https://github.com/user-attachments/assets/63b43a7e-acc7-4c81-a900-6da450527d8f + +*(Compressed version due to GitHub size limits. See the full-quality video on our project page!)* + +**TRELLIS.2** is a state-of-the-art large 3D generative model (4B parameters) designed for high-fidelity **image-to-3D** generation. It leverages a novel "field-free" sparse voxel structure termed **O-Voxel** to reconstruct and generate arbitrary 3D assets with complex topologies, sharp features, and full PBR materials. + + +## ✨ Features + +### 1. High Quality, Resolution & Efficiency +Our 4B-parameter model generates high-resolution fully textured assets with exceptional fidelity and efficiency using vanilla DiTs. It utilizes a Sparse 3D VAE with 16× spatial downsampling to encode assets into a compact latent space. + +| Resolution | Total Time* | Breakdown (Shape + Mat) | +| :--- | :--- | :--- | +| **512³** | **~3s** | 2s + 1s | +| **1024³** | **~17s** | 10s + 7s | +| **1536³** | **~60s** | 35s + 25s | + +*Tested on NVIDIA H100 GPU. + +### 2. Arbitrary Topology Handling +The **O-Voxel** representation breaks the limits of iso-surface fields. It robustly handles complex structures without lossy conversion: +* ✅ **Open Surfaces** (e.g., clothing, leaves) +* ✅ **Non-manifold Geometry** +* ✅ **Internal Enclosed Structures** + +### 3. Rich Texture Modeling +Beyond basic colors, TRELLIS.2 models arbitrary surface attributes including **Base Color, Roughness, Metallic, and Opacity**, enabling photorealistic rendering and transparency support. + +### 4. Minimalist Processing +Data processing is streamlined for instant conversions that are fully **rendering-free** and **optimization-free**. +* **< 10s** (Single CPU): Textured Mesh → O-Voxel +* **< 100ms** (CUDA): O-Voxel → Textured Mesh + + +## 🗺️ Roadmap + +- [x] Paper release +- [x] Release image-to-3D inference code +- [x] Release pretrained checkpoints (4B) +- [x] Hugging Face Spaces demo +- [x] Release shape-conditioned texture generation inference code +- [x] Release training code + + +## 🛠️ Installation + +### Prerequisites +- **System**: The code is currently tested only on **Linux**. +- **Hardware**: An NVIDIA GPU with at least 24GB of memory is necessary. The code has been verified on NVIDIA A100 and H100 GPUs. +- **Software**: + - The [CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit-archive) is needed to compile certain packages. Recommended version is 12.4. + - [Conda](https://docs.anaconda.com/miniconda/install/#quick-command-line-install) is recommended for managing dependencies. + - Python version 3.8 or higher is required. + +### Installation Steps +1. Clone the repo: + ```sh + git clone -b main https://github.com/microsoft/TRELLIS.2.git --recursive + cd TRELLIS.2 + ``` + +2. Install the dependencies: + + **Before running the following command there are somethings to note:** + - By adding `--new-env`, a new conda environment named `trellis2` will be created. If you want to use an existing conda environment, please remove this flag. + - By default the `trellis2` environment will use pytorch 2.6.0 with CUDA 12.4. If you want to use a different version of CUDA, you can remove the `--new-env` flag and manually install the required dependencies. Refer to [PyTorch](https://pytorch.org/get-started/previous-versions/) for the installation command. + - If you have multiple CUDA Toolkit versions installed, `CUDA_HOME` should be set to the correct version before running the command. For example, if you have CUDA Toolkit 12.4 and 13.0 installed, you can run `export CUDA_HOME=/usr/local/cuda-12.4` before running the command. + - By default, the code uses the `flash-attn` backend for attention. For GPUs do not support `flash-attn` (e.g., NVIDIA V100), you can install `xformers` manually and set the `ATTN_BACKEND` environment variable to `xformers` before running the code. See the [Minimal Example](#minimal-example) for more details. + - The installation may take a while due to the large number of dependencies. Please be patient. If you encounter any issues, you can try to install the dependencies one by one, specifying one flag at a time. + - If you encounter any issues during the installation, feel free to open an issue or contact us. + + Create a new conda environment named `trellis2` and install the dependencies: + ```sh + . ./setup.sh --new-env --basic --flash-attn --nvdiffrast --nvdiffrec --cumesh --o-voxel --flexgemm + ``` + The detailed usage of `setup.sh` can be found by running `. ./setup.sh --help`. + ```sh + Usage: setup.sh [OPTIONS] + Options: + -h, --help Display this help message + --new-env Create a new conda environment + --basic Install basic dependencies + --flash-attn Install flash-attention + --cumesh Install cumesh + --o-voxel Install o-voxel + --flexgemm Install flexgemm + --nvdiffrast Install nvdiffrast + --nvdiffrec Install nvdiffrec + ``` + +## 📦 Pretrained Weights + +The pretrained model **TRELLIS.2-4B** is available on Hugging Face. Please refer to the model card there for more details. + +| Model | Parameters | Resolution | Link | +| :--- | :--- | :--- | :--- | +| **TRELLIS.2-4B** | 4 Billion | 512³ - 1536³ | [Hugging Face](https://huggingface.co/microsoft/TRELLIS.2-4B) | + + +## 🚀 Usage + +### 1. Image to 3D Generation + +#### Minimal Example + +Here is an [example](example.py) of how to use the pretrained models for 3D asset generation. + +```python +import os +os.environ['OPENCV_IO_ENABLE_OPENEXR'] = '1' +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" # Can save GPU memory +import cv2 +import imageio +from PIL import Image +import torch +from trellis2.pipelines import Trellis2ImageTo3DPipeline +from trellis2.utils import render_utils +from trellis2.renderers import EnvMap +import o_voxel + +# 1. Setup Environment Map +envmap = EnvMap(torch.tensor( + cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB), + dtype=torch.float32, device='cuda' +)) + +# 2. Load Pipeline +pipeline = Trellis2ImageTo3DPipeline.from_pretrained("microsoft/TRELLIS.2-4B") +pipeline.cuda() + +# 3. Load Image & Run +image = Image.open("assets/example_image/T.png") +mesh = pipeline.run(image)[0] +mesh.simplify(16777216) # nvdiffrast limit + +# 4. Render Video +video = render_utils.make_pbr_vis_frames(render_utils.render_video(mesh, envmap=envmap)) +imageio.mimsave("sample.mp4", video, fps=15) + +# 5. Export to GLB +glb = o_voxel.postprocess.to_glb( + vertices = mesh.vertices, + faces = mesh.faces, + attr_volume = mesh.attrs, + coords = mesh.coords, + attr_layout = mesh.layout, + voxel_size = mesh.voxel_size, + aabb = [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + decimation_target = 1000000, + texture_size = 4096, + remesh = True, + remesh_band = 1, + remesh_project = 0, + verbose = True +) +glb.export("sample.glb", extension_webp=True) +``` + +Upon execution, the script generates the following files: + - `sample.mp4`: A video visualizing the generated 3D asset with PBR materials and environmental lighting. + - `sample.glb`: The extracted PBR-ready 3D asset in GLB format. + +**Note:** The `.glb` file is exported in `OPAQUE` mode by default. Although the alpha channel is preserved within the texture map, it is not active initially. To enable transparency, import the asset into your 3D software and manually connect the texture's alpha channel to the material's opacity or alpha input. + +#### Web Demo + +[app.py](app.py) provides a simple web demo for image to 3D asset generation. you can run the demo with the following command: +```sh +python app.py +``` + +Then, you can access the demo at the address shown in the terminal. + +### 2. PBR Texture Generation + +Please refer to the [example_texturing.py](example_texturing.py) for an example of how to generate PBR textures for a given 3D shape. Also, you can use the [app_texturing.py](app_texturing.py) to run a web demo for PBR texture generation. + + +## 🏋️ Training + +We provide the full training codebase, enabling users to train **TRELLIS.2** from scratch or fine-tune it on custom datasets. + +### 1. Data Preparation + +Before training, raw 3D assets must be converted into the **O-Voxel** representation. This process includes mesh conversion, compact structured latent generation, and metadata preparation. + +> 📂 **Please refer to [data_toolkit/README.md](data_toolkit/README.md) for detailed instructions on data preprocessing and dataset organization.** + +### 2. Running Training + +Training is managed through the `train.py` script, which accepts multiple command-line arguments to configure experiments: + +* `--config`: Path to the experiment configuration file. +* `--output_dir`: Directory for training outputs. +* `--load_dir`: Directory to load checkpoints from (defaults to `output_dir`). +* `--ckpt`: Checkpoint step to resume from (defaults to the latest). +* `--data_dir`: Dataset path or a JSON string specifying dataset locations. +* `--auto_retry`: Number of automatic retries upon failure. +* `--tryrun`: Perform a dry run without actual training. +* `--profile`: Enable training profiling. +* `--num_nodes`: Number of nodes for distributed training. +* `--node_rank`: Rank of the current node. +* `--num_gpus`: Number of GPUs per node (defaults to all available GPUs). +* `--master_addr`: Master node address for distributed training. +* `--master_port`: Port for distributed training communication. + + +### SC-VAE Training + + +To train the shape SC-VAE, run: + +```sh +python train.py \ + --config configs/scvae/shape_vae_next_dc_f16c32_fp16.json \ + --output_dir results/shape_vae_next_dc_f16c32_fp16 \ + --data_dir "{\"ObjaverseXL_sketchfab\": {\"base\": \"datasets/ObjaverseXL_sketchfab\", \"mesh_dump\": \"datasets/ObjaverseXL_sketchfab/mesh_dumps\", \"dual_grid\": \"datasets/ObjaverseXL_sketchfab/dual_grid_256\", \"asset_stats\": \"datasets/ObjaverseXL_sketchfab/asset_stats\"}}" +``` + +This command trains the shape SC-VAE on the **Objaverse-XL** dataset using the `shape_vae_next_dc_f16c32_fp16.json` configuration. Training outputs will be saved to `results/shape_vae_next_dc_f16c32_fp16`. + +The dataset is specified as a JSON string, where each dataset entry includes: + +* `base`: Root directory of the dataset. +* `mesh_dump`: Directory containing preprocessed mesh dumps. +* `dual_grid`: Directory with precomputed dual-grid representations. +* `asset_stats`: Directory containing precomputed asset statistics. + +To fine-tune the model at a higher resolution, use the `shape_vae_next_dc_f16c32_fp16_ft_512.json` configuration. Remember to update the `finetune_ckpt` field and adjust the dataset paths accordingly. + + +To train the texture SC-VAE, run: + +```sh +python train.py \ + --config configs/scvae/tex_vae_next_dc_f16c32_fp16.json \ + --output_dir results/tex_vae_next_dc_f16c32_fp16 \ + --data_dir "{\"ObjaverseXL_sketchfab\": {\"base\": \"datasets/ObjaverseXL_sketchfab\", \"pbr_dump\": \"datasets/ObjaverseXL_sketchfab/pbr_dumps\", \"pbr_voxel\": \"datasets/ObjaverseXL_sketchfab/pbr_voxels_256\", \"asset_stats\": \"datasets/ObjaverseXL_sketchfab/asset_stats\"}}" +``` + + +### Flow Model Training + +To train the sparse structure flow model, run: + +```sh +python train.py \ + --config configs/gen/ss_flow_img_dit_1_3B_64_bf16.json \ + --output_dir results/ss_flow_img_dit_1_3B_64_bf16 \ + --data_dir "{\"ObjaverseXL_sketchfab\": {\"base\": \"datasets/ObjaverseXL_sketchfab\", \"ss_latent\": \"datasets/ObjaverseXL_sketchfab/ss_latents/ss_enc_conv3d_16l8_fp16_64\", \"render_cond\": \"datasets/ObjaverseXL_sketchfab/renders_cond\"}}" +``` + +This command trains the sparse-structure flow model on the **Objaverse-XL** dataset using the specified configuration file. Outputs are saved to `results/ss_flow_img_dit_1_3B_64_bf16`. + +The dataset configuration includes: + +* `base`: Root dataset directory. +* `ss_latent`: Directory containing precomputed sparse-structure latents. +* `render_cond`: Directory containing conditional rendering images. + + +The second- and third-stage flow models for shape and texture generation can be trained using the following configurations: + +* Shape flow: `slat_flow_img2shape_dit_1_3B_512_bf16.json` +* Texture flow: `slat_flow_imgshape2tex_dit_1_3B_512_bf16.json` + +Example commands: + +```sh +# Shape flow model +python train.py \ + --config configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16.json \ + --output_dir results/slat_flow_img2shape_dit_1_3B_512_bf16 \ + --data_dir "{\"ObjaverseXL_sketchfab\": {\"base\": \"datasets/ObjaverseXL_sketchfab\", \"shape_latent\": \"datasets/ObjaverseXL_sketchfab/shape_latents/shape_enc_next_dc_f16c32_fp16_512\", \"render_cond\": \"datasets/ObjaverseXL_sketchfab/renders_cond\"}}" + +# Texture flow model +python train.py \ + --config configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16.json \ + --output_dir results/slat_flow_imgshape2tex_dit_1_3B_512_bf16 \ + --data_dir "{\"ObjaverseXL_sketchfab\": {\"base\": \"datasets/ObjaverseXL_sketchfab\", \"shape_latent\": \"datasets/ObjaverseXL_sketchfab/shape_latents/shape_enc_next_dc_f16c32_fp16_512\", \"pbr_latent\": \"datasets/ObjaverseXL_sketchfab/pbr_latents/tex_enc_next_dc_f16c32_fp16_512\", \"render_cond\": \"datasets/ObjaverseXL_sketchfab/renders_cond\"}}" +``` + +Higher-resolution fine-tuning can be performed by updating the `finetune_ckpt` field in the following configuration files and adjusting the dataset paths accordingly: + +* `slat_flow_img2shape_dit_1_3B_512_bf16_ft1024.json` +* `slat_flow_imgshape2tex_dit_1_3B_512_bf16_ft1024.json` + + +## 🧩 Related Packages + +TRELLIS.2 is built upon several specialized high-performance packages developed by our team: + +* **[O-Voxel](o-voxel):** + Core library handling the logic for converting between textured meshes and the O-Voxel representation, ensuring instant bidirectional transformation. +* **[FlexGEMM](https://github.com/JeffreyXiang/FlexGEMM):** + Efficient sparse convolution implementation based on Triton, enabling rapid processing of sparse voxel structures. +* **[CuMesh](https://github.com/JeffreyXiang/CuMesh):** + CUDA-accelerated mesh utilities used for high-speed post-processing, remeshing, decimation, and UV-unwrapping. + + +## ⚖️ License + +This model and code are released under the **[MIT License](LICENSE)**. + +Please note that certain dependencies operate under separate license terms: + +- [**nvdiffrast**](https://github.com/NVlabs/nvdiffrast): Utilized for rendering generated 3D assets. This package is governed by its own [License](https://github.com/NVlabs/nvdiffrast/blob/main/LICENSE.txt). + +- [**nvdiffrec**](https://github.com/NVlabs/nvdiffrec): Implements the split-sum renderer for PBR materials. This package is governed by its own [License](https://github.com/NVlabs/nvdiffrec/blob/main/LICENSE.txt). + +## 📚 Citation + +If you find this model useful for your research, please cite our work: + +```bibtex +@article{ + xiang2025trellis2, + title={Native and Compact Structured Latents for 3D Generation}, + author={Xiang, Jianfeng and Chen, Xiaoxue and Xu, Sicheng and Wang, Ruicheng and Lv, Zelong and Deng, Yu and Zhu, Hongyuan and Dong, Yue and Zhao, Hao and Yuan, Nicholas Jing and Yang, Jiaolong}, + journal={Tech report}, + year={2025} +} +``` diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/SECURITY.md b/OVOW/engine/oneposeviagen/TRELLIS2/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..e751608fcd55622cc1f88f30833bffe3e0aed236 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/SECURITY.md @@ -0,0 +1,14 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which +includes all source code repositories in our GitHub organizations. + +**Please do not report security vulnerabilities through public GitHub issues.** + +For security reporting information, locations, contact information, and policies, +please review the latest guidance for Microsoft repositories at +[https://aka.ms/SECURITY.md](https://aka.ms/SECURITY.md). + + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/app.py b/OVOW/engine/oneposeviagen/TRELLIS2/app.py new file mode 100644 index 0000000000000000000000000000000000000000..74b882bdf87aeec9b3053f9b93190780d4697b07 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/app.py @@ -0,0 +1,645 @@ +import gradio as gr + +import os +os.environ['OPENCV_IO_ENABLE_OPENEXR'] = '1' +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" +from datetime import datetime +import shutil +import cv2 +from typing import * +import torch +import numpy as np +from PIL import Image +import base64 +import io +from trellis2.modules.sparse import SparseTensor +from trellis2.pipelines import Trellis2ImageTo3DPipeline +from trellis2.renderers import EnvMap +from trellis2.utils import render_utils +import o_voxel + + +MAX_SEED = np.iinfo(np.int32).max +TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp') +MODES = [ + {"name": "Normal", "icon": "assets/app/normal.png", "render_key": "normal"}, + {"name": "Clay render", "icon": "assets/app/clay.png", "render_key": "clay"}, + {"name": "Base color", "icon": "assets/app/basecolor.png", "render_key": "base_color"}, + {"name": "HDRI forest", "icon": "assets/app/hdri_forest.png", "render_key": "shaded_forest"}, + {"name": "HDRI sunset", "icon": "assets/app/hdri_sunset.png", "render_key": "shaded_sunset"}, + {"name": "HDRI courtyard", "icon": "assets/app/hdri_courtyard.png", "render_key": "shaded_courtyard"}, +] +STEPS = 8 +DEFAULT_MODE = 3 +DEFAULT_STEP = 3 + + +css = """ +/* Overwrite Gradio Default Style */ +.stepper-wrapper { + padding: 0; +} + +.stepper-container { + padding: 0; + align-items: center; +} + +.step-button { + flex-direction: row; +} + +.step-connector { + transform: none; +} + +.step-number { + width: 16px; + height: 16px; +} + +.step-label { + position: relative; + bottom: 0; +} + +.wrap.center.full { + inset: 0; + height: 100%; +} + +.wrap.center.full.translucent { + background: var(--block-background-fill); +} + +.meta-text-center { + display: block !important; + position: absolute !important; + top: unset !important; + bottom: 0 !important; + right: 0 !important; + transform: unset !important; +} + +/* Previewer */ +.previewer-container { + position: relative; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + width: 100%; + height: 722px; + margin: 0 auto; + padding: 20px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; +} + +.previewer-container .tips-icon { + position: absolute; + right: 10px; + top: 10px; + z-index: 10; + border-radius: 10px; + color: #fff; + background-color: var(--color-accent); + padding: 3px 6px; + user-select: none; +} + +.previewer-container .tips-text { + position: absolute; + right: 10px; + top: 50px; + color: #fff; + background-color: var(--color-accent); + border-radius: 10px; + padding: 6px; + text-align: left; + max-width: 300px; + z-index: 10; + transition: all 0.3s; + opacity: 0%; + user-select: none; +} + +.previewer-container .tips-text p { + font-size: 14px; + line-height: 1.2; +} + +.tips-icon:hover + .tips-text { + display: block; + opacity: 100%; +} + +/* Row 1: Display Modes */ +.previewer-container .mode-row { + width: 100%; + display: flex; + gap: 8px; + justify-content: center; + margin-bottom: 20px; + flex-wrap: wrap; +} +.previewer-container .mode-btn { + width: 24px; + height: 24px; + border-radius: 50%; + cursor: pointer; + opacity: 0.5; + transition: all 0.2s; + border: 2px solid #ddd; + object-fit: cover; +} +.previewer-container .mode-btn:hover { opacity: 0.9; transform: scale(1.1); } +.previewer-container .mode-btn.active { + opacity: 1; + border-color: var(--color-accent); + transform: scale(1.1); +} + +/* Row 2: Display Image */ +.previewer-container .display-row { + margin-bottom: 20px; + min-height: 400px; + width: 100%; + flex-grow: 1; + display: flex; + justify-content: center; + align-items: center; +} +.previewer-container .previewer-main-image { + max-width: 100%; + max-height: 100%; + flex-grow: 1; + object-fit: contain; + display: none; +} +.previewer-container .previewer-main-image.visible { + display: block; +} + +/* Row 3: Custom HTML Slider */ +.previewer-container .slider-row { + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 0 10px; +} + +.previewer-container input[type=range] { + -webkit-appearance: none; + width: 100%; + max-width: 400px; + background: transparent; +} +.previewer-container input[type=range]::-webkit-slider-runnable-track { + width: 100%; + height: 8px; + cursor: pointer; + background: #ddd; + border-radius: 5px; +} +.previewer-container input[type=range]::-webkit-slider-thumb { + height: 20px; + width: 20px; + border-radius: 50%; + background: var(--color-accent); + cursor: pointer; + -webkit-appearance: none; + margin-top: -6px; + box-shadow: 0 2px 5px rgba(0,0,0,0.2); + transition: transform 0.1s; +} +.previewer-container input[type=range]::-webkit-slider-thumb:hover { + transform: scale(1.2); +} + +/* Overwrite Previewer Block Style */ +.gradio-container .padded:has(.previewer-container) { + padding: 0 !important; +} + +.gradio-container:has(.previewer-container) [data-testid="block-label"] { + position: absolute; + top: 0; + left: 0; +} +""" + + +head = """ + +""" + + +empty_html = f""" +
+ +
+""" + + +def image_to_base64(image): + buffered = io.BytesIO() + image = image.convert("RGB") + image.save(buffered, format="jpeg", quality=85) + img_str = base64.b64encode(buffered.getvalue()).decode() + return f"data:image/jpeg;base64,{img_str}" + + +def start_session(req: gr.Request): + user_dir = os.path.join(TMP_DIR, str(req.session_hash)) + os.makedirs(user_dir, exist_ok=True) + + +def end_session(req: gr.Request): + user_dir = os.path.join(TMP_DIR, str(req.session_hash)) + shutil.rmtree(user_dir) + + +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. + """ + processed_image = pipeline.preprocess_image(image) + return processed_image + + +def pack_state(latents: Tuple[SparseTensor, SparseTensor, int]) -> dict: + shape_slat, tex_slat, res = latents + return { + 'shape_slat_feats': shape_slat.feats.cpu().numpy(), + 'tex_slat_feats': tex_slat.feats.cpu().numpy(), + 'coords': shape_slat.coords.cpu().numpy(), + 'res': res, + } + + +def unpack_state(state: dict) -> Tuple[SparseTensor, SparseTensor, int]: + shape_slat = SparseTensor( + feats=torch.from_numpy(state['shape_slat_feats']).cuda(), + coords=torch.from_numpy(state['coords']).cuda(), + ) + tex_slat = shape_slat.replace(torch.from_numpy(state['tex_slat_feats']).cuda()) + return shape_slat, tex_slat, state['res'] + + +def get_seed(randomize_seed: bool, seed: int) -> int: + """ + Get the random seed. + """ + return np.random.randint(0, MAX_SEED) if randomize_seed else seed + + +def image_to_3d( + image: Image.Image, + seed: int, + resolution: str, + ss_guidance_strength: float, + ss_guidance_rescale: float, + ss_sampling_steps: int, + ss_rescale_t: float, + shape_slat_guidance_strength: float, + shape_slat_guidance_rescale: float, + shape_slat_sampling_steps: int, + shape_slat_rescale_t: float, + tex_slat_guidance_strength: float, + tex_slat_guidance_rescale: float, + tex_slat_sampling_steps: int, + tex_slat_rescale_t: float, + req: gr.Request, + progress=gr.Progress(track_tqdm=True), +) -> str: + # --- Sampling --- + outputs, latents = pipeline.run( + image, + seed=seed, + preprocess_image=False, + sparse_structure_sampler_params={ + "steps": ss_sampling_steps, + "guidance_strength": ss_guidance_strength, + "guidance_rescale": ss_guidance_rescale, + "rescale_t": ss_rescale_t, + }, + shape_slat_sampler_params={ + "steps": shape_slat_sampling_steps, + "guidance_strength": shape_slat_guidance_strength, + "guidance_rescale": shape_slat_guidance_rescale, + "rescale_t": shape_slat_rescale_t, + }, + tex_slat_sampler_params={ + "steps": tex_slat_sampling_steps, + "guidance_strength": tex_slat_guidance_strength, + "guidance_rescale": tex_slat_guidance_rescale, + "rescale_t": tex_slat_rescale_t, + }, + pipeline_type={ + "512": "512", + "1024": "1024_cascade", + "1536": "1536_cascade", + }[resolution], + return_latent=True, + ) + mesh = outputs[0] + mesh.simplify(16777216) # nvdiffrast limit + images = render_utils.render_snapshot(mesh, resolution=1024, r=2, fov=36, nviews=STEPS, envmap=envmap) + state = pack_state(latents) + torch.cuda.empty_cache() + + # --- HTML Construction --- + # The Stack of 48 Images + images_html = "" + for m_idx, mode in enumerate(MODES): + for s_idx in range(STEPS): + # ID Naming Convention: view-m{mode}-s{step} + unique_id = f"view-m{m_idx}-s{s_idx}" + + # Logic: Only Mode 0, Step 0 is visible initially + is_visible = (m_idx == DEFAULT_MODE and s_idx == DEFAULT_STEP) + vis_class = "visible" if is_visible else "" + + # Image Source + img_base64 = image_to_base64(Image.fromarray(images[mode['render_key']][s_idx])) + + # Render the Tag + images_html += f""" + + """ + + # Button Row HTML + btns_html = "" + for idx, mode in enumerate(MODES): + active_class = "active" if idx == DEFAULT_MODE else "" + # Note: onclick calls the JS function defined in Head + btns_html += f""" + + """ + + # Assemble the full component + full_html = f""" +
+
+
💡Tips
+
+

● Render Mode - Click on the circular buttons to switch between different render modes.

+

● View Angle - Drag the slider to change the view angle.

+
+
+ + +
+ {images_html} +
+ + +
+ {btns_html} +
+ + +
+ +
+
+ """ + + return state, full_html + + +def extract_glb( + state: dict, + decimation_target: int, + texture_size: int, + req: gr.Request, + progress=gr.Progress(track_tqdm=True), +) -> Tuple[str, str]: + """ + Extract a GLB file from the 3D model. + + Args: + state (dict): The state of the generated 3D model. + decimation_target (int): The target face count for decimation. + texture_size (int): The texture resolution. + + Returns: + str: The path to the extracted GLB file. + """ + user_dir = os.path.join(TMP_DIR, str(req.session_hash)) + shape_slat, tex_slat, res = unpack_state(state) + mesh = pipeline.decode_latent(shape_slat, tex_slat, res)[0] + glb = o_voxel.postprocess.to_glb( + vertices=mesh.vertices, + faces=mesh.faces, + attr_volume=mesh.attrs, + coords=mesh.coords, + attr_layout=pipeline.pbr_attr_layout, + grid_size=res, + aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + decimation_target=decimation_target, + texture_size=texture_size, + remesh=True, + remesh_band=1, + remesh_project=0, + use_tqdm=True, + ) + now = datetime.now() + timestamp = now.strftime("%Y-%m-%dT%H%M%S") + f".{now.microsecond // 1000:03d}" + os.makedirs(user_dir, exist_ok=True) + glb_path = os.path.join(user_dir, f'sample_{timestamp}.glb') + glb.export(glb_path, extension_webp=True) + torch.cuda.empty_cache() + return glb_path, glb_path + + +with gr.Blocks(delete_cache=(600, 600)) as demo: + gr.Markdown(""" + ## Image to 3D Asset with [TRELLIS.2](https://microsoft.github.io/TRELLIS.2) + * Upload an image (preferably with an alpha-masked foreground object) and click Generate to create a 3D asset. + * Click Extract GLB to export and download the generated GLB file if you're satisfied with the result. Otherwise, try another time. + """) + + with gr.Row(): + with gr.Column(scale=1, min_width=360): + image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=400) + + resolution = gr.Radio(["512", "1024", "1536"], label="Resolution", value="1024") + seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1) + randomize_seed = gr.Checkbox(label="Randomize Seed", value=True) + decimation_target = gr.Slider(100000, 1000000, label="Decimation Target", value=500000, step=10000) + texture_size = gr.Slider(1024, 4096, label="Texture Size", value=2048, step=1024) + + generate_btn = gr.Button("Generate") + + with gr.Accordion(label="Advanced Settings", open=False): + gr.Markdown("Stage 1: Sparse Structure Generation") + with gr.Row(): + ss_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=7.5, step=0.1) + ss_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.7, step=0.01) + ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1) + ss_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=5.0, step=0.1) + gr.Markdown("Stage 2: Shape Generation") + with gr.Row(): + shape_slat_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=7.5, step=0.1) + shape_slat_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.5, step=0.01) + shape_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1) + shape_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1) + gr.Markdown("Stage 3: Material Generation") + with gr.Row(): + tex_slat_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=1.0, step=0.1) + tex_slat_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.0, step=0.01) + tex_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1) + tex_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1) + + with gr.Column(scale=10): + with gr.Walkthrough(selected=0) as walkthrough: + with gr.Step("Preview", id=0): + preview_output = gr.HTML(empty_html, label="3D Asset Preview", show_label=True, container=True) + extract_btn = gr.Button("Extract GLB") + with gr.Step("Extract", id=1): + glb_output = gr.Model3D(label="Extracted GLB", height=724, show_label=True, display_mode="solid", clear_color=(0.25, 0.25, 0.25, 1.0)) + download_btn = gr.DownloadButton(label="Download GLB") + + with gr.Column(scale=1, min_width=172): + examples = gr.Examples( + examples=[ + f'assets/example_image/{image}' + for image in os.listdir("assets/example_image") + ], + inputs=[image_prompt], + fn=preprocess_image, + outputs=[image_prompt], + run_on_click=True, + examples_per_page=18, + ) + + output_buf = gr.State() + + + # Handlers + demo.load(start_session) + demo.unload(end_session) + + image_prompt.upload( + preprocess_image, + inputs=[image_prompt], + outputs=[image_prompt], + ) + + generate_btn.click( + get_seed, + inputs=[randomize_seed, seed], + outputs=[seed], + ).then( + lambda: gr.Walkthrough(selected=0), outputs=walkthrough + ).then( + image_to_3d, + inputs=[ + image_prompt, seed, resolution, + ss_guidance_strength, ss_guidance_rescale, ss_sampling_steps, ss_rescale_t, + shape_slat_guidance_strength, shape_slat_guidance_rescale, shape_slat_sampling_steps, shape_slat_rescale_t, + tex_slat_guidance_strength, tex_slat_guidance_rescale, tex_slat_sampling_steps, tex_slat_rescale_t, + ], + outputs=[output_buf, preview_output], + ) + + extract_btn.click( + lambda: gr.Walkthrough(selected=1), outputs=walkthrough + ).then( + extract_glb, + inputs=[output_buf, decimation_target, texture_size], + outputs=[glb_output, download_btn], + ) + + +# Launch the Gradio app +if __name__ == "__main__": + os.makedirs(TMP_DIR, exist_ok=True) + + # Construct ui components + btn_img_base64_strs = {} + for i in range(len(MODES)): + icon = Image.open(MODES[i]['icon']) + MODES[i]['icon_base64'] = image_to_base64(icon) + + pipeline = Trellis2ImageTo3DPipeline.from_pretrained('microsoft/TRELLIS.2-4B') + pipeline.cuda() + + envmap = { + 'forest': EnvMap(torch.tensor( + cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB), + dtype=torch.float32, device='cuda' + )), + 'sunset': EnvMap(torch.tensor( + cv2.cvtColor(cv2.imread('assets/hdri/sunset.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB), + dtype=torch.float32, device='cuda' + )), + 'courtyard': EnvMap(torch.tensor( + cv2.cvtColor(cv2.imread('assets/hdri/courtyard.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB), + dtype=torch.float32, device='cuda' + )), + } + + demo.launch(css=css, head=head) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/app_texturing.py b/OVOW/engine/oneposeviagen/TRELLIS2/app_texturing.py new file mode 100644 index 0000000000000000000000000000000000000000..50b28739bc79988afa5e749c7bbdf62a6a23891f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/app_texturing.py @@ -0,0 +1,151 @@ +import gradio as gr + +import os +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" +from datetime import datetime +import shutil +from typing import * +import torch +import numpy as np +import trimesh +from PIL import Image +from trellis2.pipelines import Trellis2TexturingPipeline + + +MAX_SEED = np.iinfo(np.int32).max +TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmp') + + +def start_session(req: gr.Request): + user_dir = os.path.join(TMP_DIR, str(req.session_hash)) + os.makedirs(user_dir, exist_ok=True) + + +def end_session(req: gr.Request): + user_dir = os.path.join(TMP_DIR, str(req.session_hash)) + shutil.rmtree(user_dir) + + +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. + """ + processed_image = pipeline.preprocess_image(image) + return processed_image + + +def get_seed(randomize_seed: bool, seed: int) -> int: + """ + Get the random seed. + """ + return np.random.randint(0, MAX_SEED) if randomize_seed else seed + + +def shapeimage_to_tex( + mesh_file: str, + image: Image.Image, + seed: int, + resolution: str, + texture_size: int, + tex_slat_guidance_strength: float, + tex_slat_guidance_rescale: float, + tex_slat_sampling_steps: int, + tex_slat_rescale_t: float, + req: gr.Request, + progress=gr.Progress(track_tqdm=True), +) -> str: + mesh = trimesh.load(mesh_file) + if isinstance(mesh, trimesh.Scene): + mesh = mesh.to_mesh() + output = pipeline.run( + mesh, + image, + seed=seed, + preprocess_image=False, + tex_slat_sampler_params={ + "steps": tex_slat_sampling_steps, + "guidance_strength": tex_slat_guidance_strength, + "guidance_rescale": tex_slat_guidance_rescale, + "rescale_t": tex_slat_rescale_t, + }, + resolution=int(resolution), + texture_size=texture_size, + ) + now = datetime.now() + timestamp = now.strftime("%Y-%m-%dT%H%M%S") + f".{now.microsecond // 1000:03d}" + user_dir = os.path.join(TMP_DIR, str(req.session_hash)) + os.makedirs(user_dir, exist_ok=True) + glb_path = os.path.join(user_dir, f'sample_{timestamp}.glb') + output.export(glb_path, extension_webp=True) + torch.cuda.empty_cache() + return glb_path, glb_path + + +with gr.Blocks(delete_cache=(600, 600)) as demo: + gr.Markdown(""" + ## Texturing a mesh with [TRELLIS.2](https://microsoft.github.io/TRELLIS.2) + * Upload a mesh and corresponding reference image (preferably with an alpha-masked foreground object) and click Generate to create a textured 3D asset. + """) + + with gr.Row(): + with gr.Column(scale=1, min_width=360): + mesh_file = gr.File(label="Upload Mesh", file_types=[".ply", ".obj", ".glb", ".gltf"], file_count="single") + image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=400) + + resolution = gr.Radio(["512", "1024", "1536"], label="Resolution", value="1024") + seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1) + randomize_seed = gr.Checkbox(label="Randomize Seed", value=True) + texture_size = gr.Slider(1024, 4096, label="Texture Size", value=2048, step=1024) + + generate_btn = gr.Button("Generate") + + with gr.Accordion(label="Advanced Settings", open=False): + with gr.Row(): + tex_slat_guidance_strength = gr.Slider(1.0, 10.0, label="Guidance Strength", value=1.0, step=0.1) + tex_slat_guidance_rescale = gr.Slider(0.0, 1.0, label="Guidance Rescale", value=0.0, step=0.01) + tex_slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1) + tex_slat_rescale_t = gr.Slider(1.0, 6.0, label="Rescale T", value=3.0, step=0.1) + + with gr.Column(scale=10): + glb_output = gr.Model3D(label="Extracted GLB", height=724, show_label=True, display_mode="solid", clear_color=(0.25, 0.25, 0.25, 1.0)) + download_btn = gr.DownloadButton(label="Download GLB") + + + # Handlers + demo.load(start_session) + demo.unload(end_session) + + image_prompt.upload( + preprocess_image, + inputs=[image_prompt], + outputs=[image_prompt], + ) + + generate_btn.click( + get_seed, + inputs=[randomize_seed, seed], + outputs=[seed], + ).then( + shapeimage_to_tex, + inputs=[ + mesh_file, image_prompt, seed, resolution, texture_size, + tex_slat_guidance_strength, tex_slat_guidance_rescale, tex_slat_sampling_steps, tex_slat_rescale_t, + ], + outputs=[glb_output, download_btn], + ) + + +# Launch the Gradio app +if __name__ == "__main__": + os.makedirs(TMP_DIR, exist_ok=True) + + pipeline = Trellis2TexturingPipeline.from_pretrained('microsoft/TRELLIS.2-4B', config_file="texturing_pipeline.json") + pipeline.cuda() + + demo.launch() diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0a34fae7ba57cb8870df5325b9c30ea474def1b0913c19c596655b85a79fdee4.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0a34fae7ba57cb8870df5325b9c30ea474def1b0913c19c596655b85a79fdee4.webp new file mode 100644 index 0000000000000000000000000000000000000000..8cb4652f561eca8ab3aa32f6e00457bc9b9f194a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0a34fae7ba57cb8870df5325b9c30ea474def1b0913c19c596655b85a79fdee4.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83d3765ff57511f11054d62e6beaf52648d277006b6dcb3c1d5f9e03ef502c49 +size 108096 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0e4984a9b3765ce80e9853443f9319ecedf90885c74b56cccfebc09402740f8a.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0e4984a9b3765ce80e9853443f9319ecedf90885c74b56cccfebc09402740f8a.webp new file mode 100644 index 0000000000000000000000000000000000000000..b9dbb51554fe1f2daeb448c0e47cfaa512a07eff --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0e4984a9b3765ce80e9853443f9319ecedf90885c74b56cccfebc09402740f8a.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a31ba3b084757faa66e4bb91a85bd956fcc1eaaaf298a091fd08044351cd0293 +size 184424 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0f168a4b1b6e96c72e9627c97a212c27a4572250ff58e25703b9d0c2bc74191a.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0f168a4b1b6e96c72e9627c97a212c27a4572250ff58e25703b9d0c2bc74191a.webp new file mode 100644 index 0000000000000000000000000000000000000000..62488149f1f5d00ac044ff6f95b91efa6117b7ed --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/0f168a4b1b6e96c72e9627c97a212c27a4572250ff58e25703b9d0c2bc74191a.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8d419ac16852b73fbc7b92c6857ba5d4be2f2dd8056bf44af707e6af4d62207 +size 156794 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/130c2b18f1651a70f8aa15b2c99f8dba29bb943044d92871f9223bd3e989e8b1.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/130c2b18f1651a70f8aa15b2c99f8dba29bb943044d92871f9223bd3e989e8b1.webp new file mode 100644 index 0000000000000000000000000000000000000000..f6a749a33c8ffd111cf198f499bda2b499537d51 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/130c2b18f1651a70f8aa15b2c99f8dba29bb943044d92871f9223bd3e989e8b1.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1a36d67f1cd7bba5c78b429c85346990aa3f269e19eee60b6d8b5d632cd743a +size 100332 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/154c88671d9e8785bd909e9283bc87fb2709ac7ce13890832603ea7533981a46.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/154c88671d9e8785bd909e9283bc87fb2709ac7ce13890832603ea7533981a46.webp new file mode 100644 index 0000000000000000000000000000000000000000..a07c3dd5b1338c39c96a0db011e92b51fec626de --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/154c88671d9e8785bd909e9283bc87fb2709ac7ce13890832603ea7533981a46.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bebc202b8799e2192d170f7ae8508b1b471451a7e91c263e6c49bf43da008bc2 +size 87452 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/1c359e94f2d699055c78487c90626cf5f1d7460c8fc04e60a286507e5286a28d.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/1c359e94f2d699055c78487c90626cf5f1d7460c8fc04e60a286507e5286a28d.webp new file mode 100644 index 0000000000000000000000000000000000000000..b0a5a51cb650bf577b81b6d976e22b717bc0a6e5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/1c359e94f2d699055c78487c90626cf5f1d7460c8fc04e60a286507e5286a28d.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:789396f34fccf83aad2ee59012bb10fb444c4f7ee9e996727dfa2824536dde52 +size 54428 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/22a868bac8e62511fccd2bc82ed31ae77ed31ae2a8a149be7150957f11b30c9b.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/22a868bac8e62511fccd2bc82ed31ae77ed31ae2a8a149be7150957f11b30c9b.webp new file mode 100644 index 0000000000000000000000000000000000000000..287db1bed9d597e5ff7e4a49da4a63c5529f51c7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/22a868bac8e62511fccd2bc82ed31ae77ed31ae2a8a149be7150957f11b30c9b.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb7cdcea3b238d40c7b838659288f5c12febd77292b22d44f54f785e2712d49a +size 159636 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/25d412fe36aab9f33913bc9f5e2fb1ff6458bdb286bf14397162c672c95d3697.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/25d412fe36aab9f33913bc9f5e2fb1ff6458bdb286bf14397162c672c95d3697.webp new file mode 100644 index 0000000000000000000000000000000000000000..bdfc4f52348dc4ea59cae734f9ee0f4aa29484da --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/25d412fe36aab9f33913bc9f5e2fb1ff6458bdb286bf14397162c672c95d3697.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4202eb19d6802319aa140e65385b3474d09aaa7f008218acf1e1f5186b923c90 +size 167372 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/26717a7dad644a5cf7554e8e6d06cf82d3dd9bbae31620b36cc7eb38b8de7ac9.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/26717a7dad644a5cf7554e8e6d06cf82d3dd9bbae31620b36cc7eb38b8de7ac9.webp new file mode 100644 index 0000000000000000000000000000000000000000..ef5029ebcfa044e437caa35458bb6ab860dbda8a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/26717a7dad644a5cf7554e8e6d06cf82d3dd9bbae31620b36cc7eb38b8de7ac9.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d15269d0c0b427eabcca39d6d093cc2cfdaab19cb8a40b6158988a70a91ffe45 +size 207084 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/290af2dd390c95db88a35b8062fdd2ac1a9c28edc6533bc6a26ab2c83c523c61.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/290af2dd390c95db88a35b8062fdd2ac1a9c28edc6533bc6a26ab2c83c523c61.webp new file mode 100644 index 0000000000000000000000000000000000000000..89889d4b276ba78b3fc451ec6a504c1b5089c859 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/290af2dd390c95db88a35b8062fdd2ac1a9c28edc6533bc6a26ab2c83c523c61.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cd45dd941dc559191c71f49ac5841fc6d06d32c7427fcf535f38c007611cd3f +size 109042 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/2bb0932314bae71eec94d0d01a20d3f761ade9664e013b9a9a43c00a2f44163a.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/2bb0932314bae71eec94d0d01a20d3f761ade9664e013b9a9a43c00a2f44163a.webp new file mode 100644 index 0000000000000000000000000000000000000000..962281565b2c60a013e64776313145fd8186e4ef --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/2bb0932314bae71eec94d0d01a20d3f761ade9664e013b9a9a43c00a2f44163a.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4e26e3e2f3de96cf396c64f1cef39ac82c13f231e2567fe0fe902dc103bf949 +size 169506 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/3723615e3766742ae35b09517152a58c36d62b707bc60d7f76f8a6c922add2c0.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/3723615e3766742ae35b09517152a58c36d62b707bc60d7f76f8a6c922add2c0.webp new file mode 100644 index 0000000000000000000000000000000000000000..0af9ee139499ab072b6068e5fb1d974f99103a30 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/3723615e3766742ae35b09517152a58c36d62b707bc60d7f76f8a6c922add2c0.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88c65db47f93beed7d6b184c32f9fa27c5f64ced2e3d4f535ad628179763cff8 +size 115508 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/3903b87907a6b4947006e6fc7c0c64f40cd98932a02bf0ecf7d6dfae776f3a38.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/3903b87907a6b4947006e6fc7c0c64f40cd98932a02bf0ecf7d6dfae776f3a38.webp new file mode 100644 index 0000000000000000000000000000000000000000..35737185bf8984f5fe58a705e57320ec70b98cbf --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/3903b87907a6b4947006e6fc7c0c64f40cd98932a02bf0ecf7d6dfae776f3a38.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca927a5cfe8e58b9e7ba9a9afd2050e23cbfd0cc2fbc5bd3c12ab9688333e290 +size 92512 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/39488b45bb4820ff0f31bb07cb8d0a19ebd991adbcb22a10fc89ee41c59219ee.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/39488b45bb4820ff0f31bb07cb8d0a19ebd991adbcb22a10fc89ee41c59219ee.webp new file mode 100644 index 0000000000000000000000000000000000000000..f87037087750f47fe1e7e1c7c1efaa33ce211ef7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/39488b45bb4820ff0f31bb07cb8d0a19ebd991adbcb22a10fc89ee41c59219ee.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c71e0bf0d49d8f21e13ce1c519110f059bce3e272ac8113bde66a8fecc76788b +size 76812 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/454e7d8a30486c0635369936e7bec5677b78ae5f436d0e46af0d533738be859f.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/454e7d8a30486c0635369936e7bec5677b78ae5f436d0e46af0d533738be859f.webp new file mode 100644 index 0000000000000000000000000000000000000000..0a3a3a893b1fa0914e63d79e82d7894afe552483 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/454e7d8a30486c0635369936e7bec5677b78ae5f436d0e46af0d533738be859f.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47be8271d2d1d27fc334cc470d63534807ad44c6f50cee18a204125a1c6b66a4 +size 140210 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/4bc7abe209c8673dd3766ee4fad14d40acbed02d118e7629f645c60fd77313f1.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/4bc7abe209c8673dd3766ee4fad14d40acbed02d118e7629f645c60fd77313f1.webp new file mode 100644 index 0000000000000000000000000000000000000000..6ae86128b367dc0618fd87e605cd08832b6b931b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/4bc7abe209c8673dd3766ee4fad14d40acbed02d118e7629f645c60fd77313f1.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae7ad70cbb2a616fca63bc73d319172d5fda0930c4aaf9d897e21c09ccf17ad7 +size 167670 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/4dae7ef0224e9305533c4801ce8144d5b3a89d883ca5d35bdb0aebb860ff705f.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/4dae7ef0224e9305533c4801ce8144d5b3a89d883ca5d35bdb0aebb860ff705f.webp new file mode 100644 index 0000000000000000000000000000000000000000..4cb9bdb5ac7fe4bd2ea84771de21eff56dda4cf4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/4dae7ef0224e9305533c4801ce8144d5b3a89d883ca5d35bdb0aebb860ff705f.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b5ca8a0b47aa2dbd5480cd356e7ab574dadd565ed738ac5ed655f36a4349eea +size 175080 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/50b70c5f88a5961d2c786158655d2fce5c3b214b2717956500a66a4e5b5fbe37.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/50b70c5f88a5961d2c786158655d2fce5c3b214b2717956500a66a4e5b5fbe37.webp new file mode 100644 index 0000000000000000000000000000000000000000..01a571a7a2ad661e29c1a4c3b5ba68353451cd70 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/50b70c5f88a5961d2c786158655d2fce5c3b214b2717956500a66a4e5b5fbe37.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:933c10aeebb2920b08cb34a08ab1878817b64eb9e30efdcc3d76731069fc0849 +size 131488 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/51b1b31d40476b123db70a51ae0b5f8b8d0db695b616bc2ec4e6324eb178fc14.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/51b1b31d40476b123db70a51ae0b5f8b8d0db695b616bc2ec4e6324eb178fc14.webp new file mode 100644 index 0000000000000000000000000000000000000000..60375c981e776e3667287f8df99b04f12098f1df --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/51b1b31d40476b123db70a51ae0b5f8b8d0db695b616bc2ec4e6324eb178fc14.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d5224235eeadadfdb93ab37664055ef55ffd930b085d268cd62c5faf9d101de +size 136872 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/52284bf45134c59a94be150a5b18b9cc3619ada4b30ded8d8d0288383b8c016f.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/52284bf45134c59a94be150a5b18b9cc3619ada4b30ded8d8d0288383b8c016f.webp new file mode 100644 index 0000000000000000000000000000000000000000..ddd363de151adc06a1815d148a69fce18a238942 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/52284bf45134c59a94be150a5b18b9cc3619ada4b30ded8d8d0288383b8c016f.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86b909e6847118f2cec6e9c0945e6a78154ce5918f4ba14c0b0afa0be2e8647f +size 150020 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5a020584b95cf3db3b6420e9b09fb93e7c0f4046e61076e5b4c65c63dc1f5837.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5a020584b95cf3db3b6420e9b09fb93e7c0f4046e61076e5b4c65c63dc1f5837.webp new file mode 100644 index 0000000000000000000000000000000000000000..4151759cf55814774c5e1ff29e219e965a21a423 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5a020584b95cf3db3b6420e9b09fb93e7c0f4046e61076e5b4c65c63dc1f5837.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62b7097ce57d01e730a0ce2cc120b6c9d27585026c3de84d6b1a0dcaf5fea9d3 +size 128572 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5a6c81d3b2afca4323e4b8b379e2cf06d18371a57fc8c5dc24b57e60e3216690.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5a6c81d3b2afca4323e4b8b379e2cf06d18371a57fc8c5dc24b57e60e3216690.webp new file mode 100644 index 0000000000000000000000000000000000000000..cd9120b3d0c12fcec01cf68a27060eba6c658e37 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5a6c81d3b2afca4323e4b8b379e2cf06d18371a57fc8c5dc24b57e60e3216690.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47cbe7b6f29adb0f7d02c2cd73f6f8bd90a54b12d416368499458a8c571e35c5 +size 178460 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5c80e5e03a3b60b6f03eaf555ba1dafc0e4230c472d7e8c8e2c5ca0a0dfcef10.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5c80e5e03a3b60b6f03eaf555ba1dafc0e4230c472d7e8c8e2c5ca0a0dfcef10.webp new file mode 100644 index 0000000000000000000000000000000000000000..7a10d813fb288d647e49f2b8bb2f5cdf578f873d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/5c80e5e03a3b60b6f03eaf555ba1dafc0e4230c472d7e8c8e2c5ca0a0dfcef10.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbd98cf5da79c56f8efc6cf86804391e71bdad2e935d21a7262472653a0674dc +size 126914 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/61fea9d08e0bd9a067c9f696621dc89165afb5aab318d0701bc025d7863dabf0.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/61fea9d08e0bd9a067c9f696621dc89165afb5aab318d0701bc025d7863dabf0.webp new file mode 100644 index 0000000000000000000000000000000000000000..021980a74ef652ae55bef0272527aab211275753 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/61fea9d08e0bd9a067c9f696621dc89165afb5aab318d0701bc025d7863dabf0.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfad86b88eb81da36a5acf77891822c042e991436bb004c7d75d8b19e89c45bd +size 110562 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/65433d02fc56dae164719ec29cb9646c0383aa1d0e24f0bb592899f08428d68e.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/65433d02fc56dae164719ec29cb9646c0383aa1d0e24f0bb592899f08428d68e.webp new file mode 100644 index 0000000000000000000000000000000000000000..3fe995897ad1712af150b391a5d91063c3e417b5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/65433d02fc56dae164719ec29cb9646c0383aa1d0e24f0bb592899f08428d68e.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd73dcc5ae5b42a442c87f1522f370869f3d2e63922e6ecf769fd90fdeed1e66 +size 124876 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/6b6d89d46d7f53e6409dbe695a9ef8f97c5257e641da35015a78579e903acdad.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/6b6d89d46d7f53e6409dbe695a9ef8f97c5257e641da35015a78579e903acdad.webp new file mode 100644 index 0000000000000000000000000000000000000000..65d32cc8426a3665fbf42de6c00cb5cf822c57fb --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/6b6d89d46d7f53e6409dbe695a9ef8f97c5257e641da35015a78579e903acdad.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5679bc9d5584361e7d6df4c7aa16c76e4dfce207621a4ee9f441902ecd4e68a3 +size 95672 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/74fe541e8c8eac8d0b5d8ba144307f6c07ed832cd19bf1d431c74292002028cd.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/74fe541e8c8eac8d0b5d8ba144307f6c07ed832cd19bf1d431c74292002028cd.webp new file mode 100644 index 0000000000000000000000000000000000000000..6ac789168f80fd3dba3e99794b220b187ac73d08 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/74fe541e8c8eac8d0b5d8ba144307f6c07ed832cd19bf1d431c74292002028cd.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3648138de19aac4fe23144d1907e04df4f0a65927a0600e0e321c9d27c94f719 +size 92942 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/799ab13a23fe319a6876b8bf48007d0374d514f5e7aa31210e9b2cecfbace082.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/799ab13a23fe319a6876b8bf48007d0374d514f5e7aa31210e9b2cecfbace082.webp new file mode 100644 index 0000000000000000000000000000000000000000..31b50241ad8cc38c4d2b9a00b36dc258dc172b73 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/799ab13a23fe319a6876b8bf48007d0374d514f5e7aa31210e9b2cecfbace082.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0dd605ac2927b56f6ba5ced2d0b56aaba1be9f7dc2ab7f8d558d0f37856f6b5 +size 169830 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7b540da337f576ffce2adc36c7459b9bbbfd845ab2160a6abbe986f1f906f6cd.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7b540da337f576ffce2adc36c7459b9bbbfd845ab2160a6abbe986f1f906f6cd.webp new file mode 100644 index 0000000000000000000000000000000000000000..a857a478e95081d2f753156509ee9081d2561c8e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7b540da337f576ffce2adc36c7459b9bbbfd845ab2160a6abbe986f1f906f6cd.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80d98d69b268e2293a6da40d4be5e95759549c0658eadfef5f0048d4d54d2fbb +size 99630 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7baa867b4790b8596ee120f9b171b727fd9428c41980577a518505507c99d8a0.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7baa867b4790b8596ee120f9b171b727fd9428c41980577a518505507c99d8a0.webp new file mode 100644 index 0000000000000000000000000000000000000000..51557cf27478f8c301978278157bf71c1d4069f1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7baa867b4790b8596ee120f9b171b727fd9428c41980577a518505507c99d8a0.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41fd0f2a1cd66f4615a3947b6fdbddf527d4d628935a6fd208ca32a3b46849b1 +size 111992 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7bd0521d20ee4805d1462a0ffb7d9aacc15180c2b741c9ac42a0d82ad3d340cb.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7bd0521d20ee4805d1462a0ffb7d9aacc15180c2b741c9ac42a0d82ad3d340cb.webp new file mode 100644 index 0000000000000000000000000000000000000000..b07990950bc8f3aee982664d6fd1264570906752 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7bd0521d20ee4805d1462a0ffb7d9aacc15180c2b741c9ac42a0d82ad3d340cb.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5a7835a908470c1142678cddfbfbe093ba0ec1085852ed072ae597f1eae5c37 +size 111836 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d585a8475db078593486367d98b5efa9368a60a3528c555b96026a1a674aa54.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d585a8475db078593486367d98b5efa9368a60a3528c555b96026a1a674aa54.webp new file mode 100644 index 0000000000000000000000000000000000000000..5f10f35ab7a6f2d1d95d40e82c4bb91e30f165b5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d585a8475db078593486367d98b5efa9368a60a3528c555b96026a1a674aa54.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7807391ef76523dab937bfcae5f9fc4803a65b86ab49310c17df0714288b7c48 +size 195232 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d6f4da4eafcc60243daf6ed210853df394a8bad7e701cadf551e21abcc77869.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d6f4da4eafcc60243daf6ed210853df394a8bad7e701cadf551e21abcc77869.webp new file mode 100644 index 0000000000000000000000000000000000000000..ab02dea2e3abcb802b48c82d6e7d670783f1be5e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d6f4da4eafcc60243daf6ed210853df394a8bad7e701cadf551e21abcc77869.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3977e4b323080e122ec297f2fafe1203e717fef8417e82b6ed523e8438f829c6 +size 191642 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d7659d5943e85a73a4ffe33c6dd48f5d79601e9bf11b103516f419ce9fbf713.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d7659d5943e85a73a4ffe33c6dd48f5d79601e9bf11b103516f419ce9fbf713.webp new file mode 100644 index 0000000000000000000000000000000000000000..60dd646a277d93fb76441ec47f88e22c4cf6967a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/7d7659d5943e85a73a4ffe33c6dd48f5d79601e9bf11b103516f419ce9fbf713.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6707893380d3c791a9a2d33bc0caa5f10719f7168d25f8d447fa26f4420919db +size 108942 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/80ad7988fc2ce62fc655b21a8950865566ec3f5a8b4398f2502db6414a3e6834.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/80ad7988fc2ce62fc655b21a8950865566ec3f5a8b4398f2502db6414a3e6834.webp new file mode 100644 index 0000000000000000000000000000000000000000..3d6c84ab1ccc878d9f292a04b579642b92c14fc9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/80ad7988fc2ce62fc655b21a8950865566ec3f5a8b4398f2502db6414a3e6834.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9558307682a1e723f86291af377f0b53970c0d301304c1f43dec741fedc209d7 +size 117870 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8aa698c59aab48d4ce69a558d9159107890e3d64e522af404d9635ad0be21f88.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8aa698c59aab48d4ce69a558d9159107890e3d64e522af404d9635ad0be21f88.webp new file mode 100644 index 0000000000000000000000000000000000000000..f12cbf93875f086f3084efc29072f8fb579f3143 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8aa698c59aab48d4ce69a558d9159107890e3d64e522af404d9635ad0be21f88.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a319ace2549835da92a6ffa5db73eebd7fce29079e5865cb32dfbdac21d9b900 +size 100414 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8ce83f6a28910e755902de10918672e77dd23476f43f0f1521c48667de6cea84.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8ce83f6a28910e755902de10918672e77dd23476f43f0f1521c48667de6cea84.webp new file mode 100644 index 0000000000000000000000000000000000000000..afc4b658a9e2dfefd67a66e91cf60f009b74e8bd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8ce83f6a28910e755902de10918672e77dd23476f43f0f1521c48667de6cea84.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b8373ce90506089d23907895d7efac4c37defb603ea7434bee9c4de870bf7da +size 179774 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8e12cf0977c0476396e7112f04b73d4d73569421173fcb553213d45030bddec3.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8e12cf0977c0476396e7112f04b73d4d73569421173fcb553213d45030bddec3.webp new file mode 100644 index 0000000000000000000000000000000000000000..d4298ffbb33598e6bb6392741f65cc9bc648a468 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/8e12cf0977c0476396e7112f04b73d4d73569421173fcb553213d45030bddec3.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:643b3d426830d89dc62634027f802e3af5450eb45591eeb413ae67d5ba56f557 +size 114408 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/901d8de4c2011a8502a0decd0adec0fc7418f26165cd52ced64fd44f720353ef.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/901d8de4c2011a8502a0decd0adec0fc7418f26165cd52ced64fd44f720353ef.webp new file mode 100644 index 0000000000000000000000000000000000000000..bbd93cd629c4850d0ddfcd65763478d1897cbb1c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/901d8de4c2011a8502a0decd0adec0fc7418f26165cd52ced64fd44f720353ef.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4e65a295b78ca3505337eb1cc58d0e5ff7effc0d500d01e503c4d5243af0a68 +size 103346 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/95db3c13622788ec311ae4dfa24dd88732c66ca5e340a0bf3465d2a528204037.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/95db3c13622788ec311ae4dfa24dd88732c66ca5e340a0bf3465d2a528204037.webp new file mode 100644 index 0000000000000000000000000000000000000000..a0795fe45f2477d4811a07bd2168f08ef9460960 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/95db3c13622788ec311ae4dfa24dd88732c66ca5e340a0bf3465d2a528204037.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23b3f7294731c66a3a9db7ccbd593708e1ba56819cff970b29fd9fbf286588e0 +size 187208 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/9c306c7bd0e857285f536fb500c0828e5fad4e23c3ceeab92c888c568fa19101.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/9c306c7bd0e857285f536fb500c0828e5fad4e23c3ceeab92c888c568fa19101.webp new file mode 100644 index 0000000000000000000000000000000000000000..b668a21a0f5e8a3c0730377da02357cd6e30b869 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/9c306c7bd0e857285f536fb500c0828e5fad4e23c3ceeab92c888c568fa19101.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d42562b49df17554583f2acbe18f8a26c9075cdab278caefab27aa7587df4ac +size 115424 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a13d176cd7a7d457b42d1b32223bcff1a45dafbbb42c6a272b97d65ac2f2eb52.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a13d176cd7a7d457b42d1b32223bcff1a45dafbbb42c6a272b97d65ac2f2eb52.webp new file mode 100644 index 0000000000000000000000000000000000000000..7f764c337d834d1077aef043aa277f360b20d9ba --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a13d176cd7a7d457b42d1b32223bcff1a45dafbbb42c6a272b97d65ac2f2eb52.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94b508edb4a3c49ff4e5c4c583b6980a7d0ef84a2f16a301ac9b671d421b8a52 +size 103072 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a306e2ee5cbc3da45e7db48d75a0cade0bb7eee263a74bc6820c617afaba1302.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a306e2ee5cbc3da45e7db48d75a0cade0bb7eee263a74bc6820c617afaba1302.webp new file mode 100644 index 0000000000000000000000000000000000000000..e4cf1566ad8daa3be8f938d3d3e5b00b297c7414 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a306e2ee5cbc3da45e7db48d75a0cade0bb7eee263a74bc6820c617afaba1302.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71c2035d7968538b51a5edb0d853a310f3f03b9626b705ac7f14398bb72f6093 +size 101638 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a3d0c28c7d9c6f23adb941c4def2523572c903a94469abcaa7dd1398d28af8f1.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a3d0c28c7d9c6f23adb941c4def2523572c903a94469abcaa7dd1398d28af8f1.webp new file mode 100644 index 0000000000000000000000000000000000000000..29b7868f213043532468e2fa1c169c3a9c98ce26 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a3d0c28c7d9c6f23adb941c4def2523572c903a94469abcaa7dd1398d28af8f1.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a8dbf4af05a60591cb157bcbb19c58c05c1d5622aaecddaf5aaabf292e89ea0 +size 208094 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a63d2595e10229067b19cb167fe2bdc152dabfd8b62ae45fc1655a4cf66509bc.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a63d2595e10229067b19cb167fe2bdc152dabfd8b62ae45fc1655a4cf66509bc.webp new file mode 100644 index 0000000000000000000000000000000000000000..242c31ce26348b99d98a69f789cf646ca472db05 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/a63d2595e10229067b19cb167fe2bdc152dabfd8b62ae45fc1655a4cf66509bc.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3786b5f2c6715d02a20abde45f4465883eb8b791a807f9dfc86dc78a17b7c58 +size 180294 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ab3bb3e183991253ae66c06d44dc6105f3c113a1a1f819ab57a93c6f60b0d32b.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ab3bb3e183991253ae66c06d44dc6105f3c113a1a1f819ab57a93c6f60b0d32b.webp new file mode 100644 index 0000000000000000000000000000000000000000..00790a403686c1fb1a78e30b9e0bad269dcb80a6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ab3bb3e183991253ae66c06d44dc6105f3c113a1a1f819ab57a93c6f60b0d32b.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69f3ab098a28bf0c06194ab523ba10e30ce3db331871e2e8fa97cfd5967853b0 +size 180186 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/b205f4483c47bd1fec8e229163361e4fdff9f77923c5e968343b8f1dd76b61dc.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/b205f4483c47bd1fec8e229163361e4fdff9f77923c5e968343b8f1dd76b61dc.webp new file mode 100644 index 0000000000000000000000000000000000000000..dc0630884d160addf2997b2435fd15ea3bece805 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/b205f4483c47bd1fec8e229163361e4fdff9f77923c5e968343b8f1dd76b61dc.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc3d5f2d5228c9314d8037105cc24798499aea1aaf311cde332df74d17f96da6 +size 130468 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/b358d0eb96a68ac4ba1f2fb6d44ea2225f95fdfbf9cf4e0da08650c3704f1d23.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/b358d0eb96a68ac4ba1f2fb6d44ea2225f95fdfbf9cf4e0da08650c3704f1d23.webp new file mode 100644 index 0000000000000000000000000000000000000000..cfa8a87a3b0c0a5ed90f249c030815517317403c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/b358d0eb96a68ac4ba1f2fb6d44ea2225f95fdfbf9cf4e0da08650c3704f1d23.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a77a4ab99beb302c5934efaeaeef2effc48b2c07b9d68cadb06d68396a48abea +size 106998 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/bb3190891dd8341c9d6d3d4faa6525c6ecdac19945526904928f6bcd2f3f45f1.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/bb3190891dd8341c9d6d3d4faa6525c6ecdac19945526904928f6bcd2f3f45f1.webp new file mode 100644 index 0000000000000000000000000000000000000000..9b23b87c2a30e9c704de86bc7c2214a9629661a8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/bb3190891dd8341c9d6d3d4faa6525c6ecdac19945526904928f6bcd2f3f45f1.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01962bf62febbf916100201f915d27ab881c747a9e283228d8b9c890c1eb2fb8 +size 155612 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/be7deb26f4fdd2080d4288668af4c39e526564282c579559ff8a4126ca4ed6c1.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/be7deb26f4fdd2080d4288668af4c39e526564282c579559ff8a4126ca4ed6c1.webp new file mode 100644 index 0000000000000000000000000000000000000000..4ae373686902684181a5f7c84f976a02f3fea9d5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/be7deb26f4fdd2080d4288668af4c39e526564282c579559ff8a4126ca4ed6c1.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed898f0689bd19f163fbfb601b9c9d31c422ab2ad409ec07f61b70471636c164 +size 155628 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c2125d086c2529638841f38918ae1defbf33e6796d827253885b4c51e601034f.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c2125d086c2529638841f38918ae1defbf33e6796d827253885b4c51e601034f.webp new file mode 100644 index 0000000000000000000000000000000000000000..4282564790b1a57ea1d4a7c2f77dd84775cade17 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c2125d086c2529638841f38918ae1defbf33e6796d827253885b4c51e601034f.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:961adcb3c9c10db565957bfcf5d0be49e18c23012363a78bebcf8b49dbd7153c +size 206140 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c3d714bc125f06ce1187799d5ca10736b4064a24c141e627089aad2bdedf7aa5.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c3d714bc125f06ce1187799d5ca10736b4064a24c141e627089aad2bdedf7aa5.webp new file mode 100644 index 0000000000000000000000000000000000000000..4203f61711b705c5e5e0e6f49e52f9b555c878a9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c3d714bc125f06ce1187799d5ca10736b4064a24c141e627089aad2bdedf7aa5.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e211aff13d1e7dcdf592d68ea34e03794c4464c5b159224d7c508d9ecae5eb59 +size 151940 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c9340e744541f310bf89838f652602961d3e5950b31cd349bcbfc7e59e15cd2e.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c9340e744541f310bf89838f652602961d3e5950b31cd349bcbfc7e59e15cd2e.webp new file mode 100644 index 0000000000000000000000000000000000000000..fc11f391f770d92966ef73037c8769f807337875 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/c9340e744541f310bf89838f652602961d3e5950b31cd349bcbfc7e59e15cd2e.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4533ce41604e7aff386c71f37f0b2727242a4615ef0e37c3cd62273678ad1809 +size 142682 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/cd3c309f17eee5ad6afe4e001765893ade20b653f611365c93d158286b4cee96.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/cd3c309f17eee5ad6afe4e001765893ade20b653f611365c93d158286b4cee96.webp new file mode 100644 index 0000000000000000000000000000000000000000..898e801ef377765e4082aa5968db56dd6e696a06 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/cd3c309f17eee5ad6afe4e001765893ade20b653f611365c93d158286b4cee96.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec6060536a5db96092d419be6e0f9d14985f6954ced1605e9d473d415ff29368 +size 764638 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/cdf996a6cc218918eeb90209891ce306a230e6d9cca2a3d9bbb37c6d7b6bd318.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/cdf996a6cc218918eeb90209891ce306a230e6d9cca2a3d9bbb37c6d7b6bd318.webp new file mode 100644 index 0000000000000000000000000000000000000000..6d79bbc33c14ba034cbc6f5dc7ab443e0f92d445 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/cdf996a6cc218918eeb90209891ce306a230e6d9cca2a3d9bbb37c6d7b6bd318.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eaf705e6205f5101af261fac1a3477121cf377f92ff93feaf506eada70de98d7 +size 217676 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/d39c2bd426456bd686de33f924524d18eb47343a5f080826aa3cb8e77de5147b.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/d39c2bd426456bd686de33f924524d18eb47343a5f080826aa3cb8e77de5147b.webp new file mode 100644 index 0000000000000000000000000000000000000000..66bc8713ed9f5a86463850a3dd130f6d9a4953c0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/d39c2bd426456bd686de33f924524d18eb47343a5f080826aa3cb8e77de5147b.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c0c09536a1a6c1c44e7c8649b1fda58ed4404ffa26debdc6f1719aaa7fdc59b +size 235370 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/d64c94dffdadf82d46004d11412b5a3b2a17f1b4ddb428477a7ba38652adf973.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/d64c94dffdadf82d46004d11412b5a3b2a17f1b4ddb428477a7ba38652adf973.webp new file mode 100644 index 0000000000000000000000000000000000000000..2573d75a2a428aef7d4d42daaa29d087b293a461 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/d64c94dffdadf82d46004d11412b5a3b2a17f1b4ddb428477a7ba38652adf973.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:373afe2a56a038d1356f3fc5f1c8fb04778e90cb2216ad1c60ba7e2d2877705f +size 153922 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/dd4c51c13a996b9eec9c954a45cd5cd457059bf9f030aadde48d88225a9f3321.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/dd4c51c13a996b9eec9c954a45cd5cd457059bf9f030aadde48d88225a9f3321.webp new file mode 100644 index 0000000000000000000000000000000000000000..45a585a7aae6829d47306d8d75189c3bfefe44d6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/dd4c51c13a996b9eec9c954a45cd5cd457059bf9f030aadde48d88225a9f3321.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ba2b5b3c76f97fe51194f7b1d8dcee48eb5cb22363d5ef602e9a2d3949cc267 +size 79022 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e10465728ebea1e055524f97ac5d47cebf82a672f07a05409aa07d826c9d9f37.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e10465728ebea1e055524f97ac5d47cebf82a672f07a05409aa07d826c9d9f37.webp new file mode 100644 index 0000000000000000000000000000000000000000..4e5c6543bf42ed397468e44212cb24d125aebf5b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e10465728ebea1e055524f97ac5d47cebf82a672f07a05409aa07d826c9d9f37.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f835e97c2c509610eaebd94d416a0d8c22f1bb01bf8833d854a35561ea674498 +size 86120 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e134444178eae855cfdefb9e5259d076df5e34f780ee44d4ad604483ff69cc74.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e134444178eae855cfdefb9e5259d076df5e34f780ee44d4ad604483ff69cc74.webp new file mode 100644 index 0000000000000000000000000000000000000000..9ffe4be1a5349b8a65b220b6063386831816db4b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e134444178eae855cfdefb9e5259d076df5e34f780ee44d4ad604483ff69cc74.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:309713c97b32a579a232faea918aea7c49d3638b07c47f29072523bb4e95c5a0 +size 167178 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e3c57169ce3d5ce10b3c10acef20b81ca774b54a17aabe74e8aca320c7b07b55.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e3c57169ce3d5ce10b3c10acef20b81ca774b54a17aabe74e8aca320c7b07b55.webp new file mode 100644 index 0000000000000000000000000000000000000000..335531a6f0d695d3463e0bbfc478c08ad19c93ed --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e3c57169ce3d5ce10b3c10acef20b81ca774b54a17aabe74e8aca320c7b07b55.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15e90c0ce28673b896e754ca56060dd840799cb8b95fb4ebeb06661675f8ed07 +size 182650 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e4d6b2f3a18c3e0f5146a5b40cda6c95d7f69372b2e741c023e5ec9661deda2b.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e4d6b2f3a18c3e0f5146a5b40cda6c95d7f69372b2e741c023e5ec9661deda2b.webp new file mode 100644 index 0000000000000000000000000000000000000000..114d6ffaa3545023654eea953aee8c22031e40a1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e4d6b2f3a18c3e0f5146a5b40cda6c95d7f69372b2e741c023e5ec9661deda2b.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05a0cabaea29f4d03c6468d039fe09af8eb8c3647952f3bcb342421445ea00a2 +size 229896 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e513fcd6c897b249fc4bff54268b4d0bbab6403503ecf3846d92feb892536e5e.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e513fcd6c897b249fc4bff54268b4d0bbab6403503ecf3846d92feb892536e5e.webp new file mode 100644 index 0000000000000000000000000000000000000000..26301f9a36cd3507d1c9ffc1bf0cf7b57cc371e0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/e513fcd6c897b249fc4bff54268b4d0bbab6403503ecf3846d92feb892536e5e.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5e3d4de543cc77d360550a9d4fb22bf01fb981df0668a872b3d381a70b9888f +size 96118 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ebd09565cf0b6593aced573dffdfff34915aa359c60ec5dd0b30cd91a7f153c8.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ebd09565cf0b6593aced573dffdfff34915aa359c60ec5dd0b30cd91a7f153c8.webp new file mode 100644 index 0000000000000000000000000000000000000000..08850da10b51022be1509076a797e4b4ea2887a1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ebd09565cf0b6593aced573dffdfff34915aa359c60ec5dd0b30cd91a7f153c8.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:477c0c9ef774e796a27645e1c143e7bd8d574cb6f31f2a0a9f57aaf66e80c0be +size 106434 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ee8ecf658fde9c58830c021b2e30d0d5e7e492ef52febe7192a6c74fbf1b0472.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ee8ecf658fde9c58830c021b2e30d0d5e7e492ef52febe7192a6c74fbf1b0472.webp new file mode 100644 index 0000000000000000000000000000000000000000..ba44a2d028fc04d8b74cef6935f8db9e9df17ce5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/ee8ecf658fde9c58830c021b2e30d0d5e7e492ef52febe7192a6c74fbf1b0472.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b169654d84f98e808a875bc80b47e0cfe988af495250dba4368edf3eea4f633 +size 304284 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f351569ddc61116da4a7b929bccdab144d011f56b9603e6e72abea05236160f4.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f351569ddc61116da4a7b929bccdab144d011f56b9603e6e72abea05236160f4.webp new file mode 100644 index 0000000000000000000000000000000000000000..b9e06fd37eba38547fe24b88ce68c442086a83c7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f351569ddc61116da4a7b929bccdab144d011f56b9603e6e72abea05236160f4.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:242db48e9c2e6e45a888fdd24f133b966f460b583f1e77324252b869d1a7d65d +size 254674 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f5332118a0cda9cd13fe13d4be2b00437e702d1f9af51ebb6b75219a572a6ce9.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f5332118a0cda9cd13fe13d4be2b00437e702d1f9af51ebb6b75219a572a6ce9.webp new file mode 100644 index 0000000000000000000000000000000000000000..16921f8bf9843166dd1e7695fcb5fa13008c75e1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f5332118a0cda9cd13fe13d4be2b00437e702d1f9af51ebb6b75219a572a6ce9.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f669f15496ecc1f3ec9819b40c8ca46ce2c080f49eab342724f2872f5c9dcff +size 186202 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f8920788b704531f7a7e875afd7c5c423d62e0a987e9495c63893c2cb4d2b5dc.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f8920788b704531f7a7e875afd7c5c423d62e0a987e9495c63893c2cb4d2b5dc.webp new file mode 100644 index 0000000000000000000000000000000000000000..c2ab696162c9dae5f90114d4825af5ec30cb28cb --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f8920788b704531f7a7e875afd7c5c423d62e0a987e9495c63893c2cb4d2b5dc.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4d093a8f99f3fc25a588785ceee95180427ff8dd063e2fda9f1e7f41cf40940 +size 247040 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f8a7eafe26a4f3ebd26a9e7d0289e4a40b5a93e9234e94ec3e1071c352acc65a.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f8a7eafe26a4f3ebd26a9e7d0289e4a40b5a93e9234e94ec3e1071c352acc65a.webp new file mode 100644 index 0000000000000000000000000000000000000000..1ae36239b3659bf579bd2588f930cdcd02d68b13 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f8a7eafe26a4f3ebd26a9e7d0289e4a40b5a93e9234e94ec3e1071c352acc65a.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d65e9fdbe6e4b432e34fbae16ea8a3d98e3cef81a9b1613f294039e96805e77 +size 208356 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f94e2b76494ce2cf1874611273e5fb3d76b395793bb5647492fa85c2ce0a248b.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f94e2b76494ce2cf1874611273e5fb3d76b395793bb5647492fa85c2ce0a248b.webp new file mode 100644 index 0000000000000000000000000000000000000000..0c26a3d52e76974f69c583939c563d3638ca9631 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/f94e2b76494ce2cf1874611273e5fb3d76b395793bb5647492fa85c2ce0a248b.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f15023e775bfe77d0a48aae77ffc8a543ed07a40864c54c45af43fdd1d4e4b4f +size 99576 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/fdf979f5227f24b554fca28aa71c351beb7b1be2be236b50bbe07f59e9b8a50c.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/fdf979f5227f24b554fca28aa71c351beb7b1be2be236b50bbe07f59e9b8a50c.webp new file mode 100644 index 0000000000000000000000000000000000000000..534b8ad1415e28164129f9f17c026f07edd9c808 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_image/fdf979f5227f24b554fca28aa71c351beb7b1be2be236b50bbe07f59e9b8a50c.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:595cdf806ce87238ab61a1d12142a4633ac91e3b459febcf785f6d71c619e77f +size 89244 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_texturing/image.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_texturing/image.webp new file mode 100644 index 0000000000000000000000000000000000000000..9daabc59886c806e7f39831a21959d87cfa40c3b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_texturing/image.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5832ccf8b001400c2d66915abab8992dfa5390ff49d0870edcd096e9089b5cdb +size 63284 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_texturing/readme b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_texturing/readme new file mode 100644 index 0000000000000000000000000000000000000000..7f6c799d95a410000c9116e459665339a701c88a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/example_texturing/readme @@ -0,0 +1,11 @@ +## Asset Information + +* Title: The Forgotten Knight +* Author: dark_igorek +* Source: https://sketchfab.com/3d-models/the-forgotten-knight-d14eb14d83bd4e7ba7cbe443d76a10fd +* License: Creative Commons Attribution (CC BY) + +## Usage + +The asset is used for research purposes only. +Please credit the original author and include the Sketchfab link when using or redistributing this model. \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/city.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/city.exr new file mode 100644 index 0000000000000000000000000000000000000000..fac69a5403a2a3b51d725bca679174d2f0208b25 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/city.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e42abcd2fa3231e5c2485ca6dd64800534d157b7194ab7fe9cc3bf5a56d0256 +size 204863 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/courtyard.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/courtyard.exr new file mode 100644 index 0000000000000000000000000000000000000000..142504138fb47eba3024495d69923211ebeda9b0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/courtyard.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6690b47725965531559380121e6878373eb599655e35fefd109a4bd0911366f3 +size 255126 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/forest.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/forest.exr new file mode 100644 index 0000000000000000000000000000000000000000..7809de1141fe935457de0cc73d8fe87ecf924e1a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/forest.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdf2298244affa0f85509380fd130ac6d4dfaa3c856df065998f7f4c1a93dc0d +size 552641 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/interior.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/interior.exr new file mode 100644 index 0000000000000000000000000000000000000000..ddb91daa8b222bedea152d60221499768d0e0fd7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/interior.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e945ff5c1ddd7a3aaf05e9fb5c3bc9cb93c5518414febd44ed2c394e013f0cbd +size 189416 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/license.txt b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..eba5cb8037c9eb45e8c8638c99b39f7160a69214 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/license.txt @@ -0,0 +1,15 @@ +All HDRIs are licensed as CC0. + +These were created by Greg Zaal (Poly Haven https://polyhaven.com). +Originals used for each HDRI: +- City: https://polyhaven.com/a/portland_landing_pad +- Courtyard: https://polyhaven.com/a/courtyard +- Forest: https://polyhaven.com/a/ninomaru_teien +- Interior: https://polyhaven.com/a/hotel_room +- Night: Probably https://polyhaven.com/a/moonless_golf +- Studio: Probably https://polyhaven.com/a/studio_small_01 +- Sunrise: https://polyhaven.com/a/spruit_sunrise +- Sunset: https://polyhaven.com/a/venice_sunset + +1K resolution of each was taken, and compressed with oiiotool: +oiiotool input.exr --ch R,G,B -d float --compression dwab:300 --clamp:min=0.0:max=32000.0 -o output.exr diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr new file mode 100644 index 0000000000000000000000000000000000000000..380591f26bebbd1419b703145dedb20cab765f59 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17480af5547465d160f7307c92585cf30820ca563f87f066395decbad8ac32a4 +size 139959 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/studio.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/studio.exr new file mode 100644 index 0000000000000000000000000000000000000000..baf478da00acddbd70593e36d90146eb15c8939d Binary files /dev/null and b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/studio.exr differ diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr new file mode 100644 index 0000000000000000000000000000000000000000..b0689a58e51c6527ed8810186644dd482f96799a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a1180126e4db7d01f134c5430ea43c1b263ab1a12faf58a444d9ce9c03f3a84 +size 251877 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr new file mode 100644 index 0000000000000000000000000000000000000000..bf0414b39faf538b48baa62257aa6e5ff168928f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bcafdda4f2d7b9759cc1d73004d34d721a274c29b1a0947be88a602dbac426b +size 171164 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/assets/teaser.webp b/OVOW/engine/oneposeviagen/TRELLIS2/assets/teaser.webp new file mode 100644 index 0000000000000000000000000000000000000000..d8b89bd17c1fdf5831bb79a3989bf428086c6a7b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/assets/teaser.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b110c904037017d996933cc318ba948bb2dec7691d5a709568e2e0d9ae86068b +size 290204 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16.json new file mode 100644 index 0000000000000000000000000000000000000000..8c5f28640b66911772c953a2b5e79d049c73ad85 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16.json @@ -0,0 +1,98 @@ +{ + "models": { + "denoiser": { + "name": "ElasticSLatFlowModel", + "args": { + "resolution": 32, + "in_channels": 32, + "out_channels": 32, + "model_channels": 1536, + "cond_channels": 1024, + "num_blocks": 30, + "num_heads": 12, + "mlp_ratio": 5.3334, + "pe_mode": "rope", + "share_mod": true, + "initialization": "scaled", + "qk_rms_norm": true, + "qk_rms_norm_cross": true + } + } + }, + "dataset": { + "name": "ImageConditionedSLatShape", + "args": { + "resolution": 512, + "image_size": 512, + "min_aesthetic_score": 4.5, + "max_tokens": 8192, + "normalization": { + "mean": [ + 0.781296, 0.018091, -0.495192, -0.558457, 1.060530, 0.093252, 1.518149, -0.933218, + -0.732996, 2.604095, -0.118341, -2.143904, 0.495076, -2.179512, -2.130751, -0.996944, + 0.261421, -2.217463, 1.260067, -0.150213, 3.790713, 1.481266, -1.046058, -1.523667, + -0.059621, 2.220780, 1.621212, 0.877230, 0.567247, -3.175944, -3.186688, 1.578665 + ], + "std": [ + 5.972266, 4.706852, 5.445010, 5.209927, 5.320220, 4.547237, 5.020802, 5.444004, + 5.226681, 5.683095, 4.831436, 5.286469, 5.652043, 5.367606, 5.525084, 4.730578, + 4.805265, 5.124013, 5.530808, 5.619001, 5.103930, 5.417670, 5.269677, 5.547194, + 5.634698, 5.235274, 6.110351, 5.511298, 6.237273, 4.879207, 5.347008, 5.405691 + ] + }, + "pretrained_slat_dec": "microsoft/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16" + } + }, + "trainer": { + "name": "ImageConditionedSparseFlowMatchingCFGTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 8, + "batch_split": 2, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-4, + "weight_decay": 0.01, + "betas": [0.9, 0.95], + "eps": 1e-8 + } + }, + "ema_rate": [ + 0.9999 + ], + "mix_precision_mode": "amp", + "mix_precision_dtype": "bfloat16", + "elastic": { + "name": "LinearMemoryController", + "args": { + "target_ratio": 0.75, + "max_mem_ratio_start": 0.5 + } + }, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "p_uncond": 0.1, + "t_schedule": { + "name": "uniform", + "args": {} + }, + "sigma_min": 1e-5, + "image_cond_model": { + "name": "DinoV3FeatureExtractor", + "args": { + "model_name": "facebook/dinov3-vitl16-pretrain-lvd1689m", + "image_size": 512 + } + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16_ft1024.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16_ft1024.json new file mode 100644 index 0000000000000000000000000000000000000000..997563a974a54e82cbfd1f0ebfc2b3f5a2b69578 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_img2shape_dit_1_3B_512_bf16_ft1024.json @@ -0,0 +1,101 @@ +{ + "models": { + "denoiser": { + "name": "ElasticSLatFlowModel", + "args": { + "resolution": 64, + "in_channels": 32, + "out_channels": 32, + "model_channels": 1536, + "cond_channels": 1024, + "num_blocks": 30, + "num_heads": 12, + "mlp_ratio": 5.3334, + "pe_mode": "rope", + "share_mod": true, + "initialization": "scaled", + "qk_rms_norm": true, + "qk_rms_norm_cross": true + } + } + }, + "dataset": { + "name": "ImageConditionedSLatShape", + "args": { + "resolution": 1024, + "image_size": 1024, + "min_aesthetic_score": 4.5, + "max_tokens": 32768, + "normalization": { + "mean": [ + 0.781296, 0.018091, -0.495192, -0.558457, 1.060530, 0.093252, 1.518149, -0.933218, + -0.732996, 2.604095, -0.118341, -2.143904, 0.495076, -2.179512, -2.130751, -0.996944, + 0.261421, -2.217463, 1.260067, -0.150213, 3.790713, 1.481266, -1.046058, -1.523667, + -0.059621, 2.220780, 1.621212, 0.877230, 0.567247, -3.175944, -3.186688, 1.578665 + ], + "std": [ + 5.972266, 4.706852, 5.445010, 5.209927, 5.320220, 4.547237, 5.020802, 5.444004, + 5.226681, 5.683095, 4.831436, 5.286469, 5.652043, 5.367606, 5.525084, 4.730578, + 4.805265, 5.124013, 5.530808, 5.619001, 5.103930, 5.417670, 5.269677, 5.547194, + 5.634698, 5.235274, 6.110351, 5.511298, 6.237273, 4.879207, 5.347008, 5.405691 + ] + }, + "pretrained_slat_dec": "microsoft/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16" + } + }, + "trainer": { + "name": "ImageConditionedSparseFlowMatchingCFGTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 2, + "batch_split": 1, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 2e-5, + "weight_decay": 0.01, + "betas": [0.9, 0.95], + "eps": 1e-8 + } + }, + "ema_rate": [ + 0.9999 + ], + "mix_precision_mode": "amp", + "mix_precision_dtype": "bfloat16", + "elastic": { + "name": "LinearMemoryController", + "args": { + "target_ratio": 0.75, + "max_mem_ratio_start": 0.25 + } + }, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "finetune_ckpt": { + "denoiser": "PATH_TO_512_CKPT" + }, + "i_log": 500, + "i_sample": 1000, + "i_save": 1000, + "p_uncond": 0.1, + "t_schedule": { + "name": "uniform", + "args": {} + }, + "sigma_min": 1e-5, + "image_cond_model": { + "name": "DinoV3FeatureExtractor", + "args": { + "model_name": "facebook/dinov3-vitl16-pretrain-lvd1689m", + "image_size": 1024 + } + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16.json new file mode 100644 index 0000000000000000000000000000000000000000..746c5260a4f6eab23d070ddad3b64762b4d3612b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16.json @@ -0,0 +1,119 @@ +{ + "models": { + "denoiser": { + "name": "ElasticSLatFlowModel", + "args": { + "resolution": 32, + "in_channels": 64, + "out_channels": 32, + "model_channels": 1536, + "cond_channels": 1024, + "num_blocks": 30, + "num_heads": 12, + "mlp_ratio": 5.3334, + "pe_mode": "rope", + "share_mod": true, + "initialization": "scaled", + "qk_rms_norm": true, + "qk_rms_norm_cross": true + } + } + }, + "dataset": { + "name": "ImageConditionedSLatPbr", + "args": { + "resolution": 512, + "image_size": 512, + "min_aesthetic_score": 4.5, + "max_tokens": 8192, + "pbr_slat_normalization": { + "mean": [ + 3.501659, 2.212398, 2.226094, 0.251093, -0.026248, -0.687364, 0.439898, -0.928075, + 0.029398, -0.339596, -0.869527, 1.038479, -0.972385, 0.126042, -1.129303, 0.455149, + -1.209521, 2.069067, 0.544735, 2.569128, -0.323407, 2.293000, -1.925608, -1.217717, + 1.213905, 0.971588, -0.023631, 0.106750, 2.021786, 0.250524, -0.662387, -0.768862 + ], + "std": [ + 2.665652, 2.743913, 2.765121, 2.595319, 3.037293, 2.291316, 2.144656, 2.911822, + 2.969419, 2.501689, 2.154811, 3.163343, 2.621215, 2.381943, 3.186697, 3.021588, + 2.295916, 3.234985, 3.233086, 2.260140, 2.874801, 2.810596, 3.292720, 2.674999, + 2.680878, 2.372054, 2.451546, 2.353556, 2.995195, 2.379849, 2.786195, 2.775190 + ] + }, + "shape_slat_normalization": { + "mean": [ + 0.781296, 0.018091, -0.495192, -0.558457, 1.060530, 0.093252, 1.518149, -0.933218, + -0.732996, 2.604095, -0.118341, -2.143904, 0.495076, -2.179512, -2.130751, -0.996944, + 0.261421, -2.217463, 1.260067, -0.150213, 3.790713, 1.481266, -1.046058, -1.523667, + -0.059621, 2.220780, 1.621212, 0.877230, 0.567247, -3.175944, -3.186688, 1.578665 + ], + "std": [ + 5.972266, 4.706852, 5.445010, 5.209927, 5.320220, 4.547237, 5.020802, 5.444004, + 5.226681, 5.683095, 4.831436, 5.286469, 5.652043, 5.367606, 5.525084, 4.730578, + 4.805265, 5.124013, 5.530808, 5.619001, 5.103930, 5.417670, 5.269677, 5.547194, + 5.634698, 5.235274, 6.110351, 5.511298, 6.237273, 4.879207, 5.347008, 5.405691 + ] + }, + "attrs": [ + "base_color", + "metallic", + "roughness", + "alpha" + ], + "pretrained_pbr_slat_dec": "microsoft/TRELLIS.2-4B/ckpts/tex_dec_next_dc_f16c32_fp16", + "pretrained_shape_slat_dec": "microsoft/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16" + } + }, + "trainer": { + "name": "ImageConditionedSparseFlowMatchingCFGTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 8, + "batch_split": 2, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-4, + "weight_decay": 0.01, + "betas": [0.9, 0.95], + "eps": 1e-8 + } + }, + "ema_rate": [ + 0.9999 + ], + "mix_precision_mode": "amp", + "mix_precision_dtype": "bfloat16", + "elastic": { + "name": "LinearMemoryController", + "args": { + "target_ratio": 0.75, + "max_mem_ratio_start": 0.5 + } + }, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "p_uncond": 0.1, + "t_schedule": { + "name": "uniform", + "args": {} + }, + "sigma_min": 1e-5, + "image_cond_model": { + "name": "DinoV3FeatureExtractor", + "args": { + "model_name": "facebook/dinov3-vitl16-pretrain-lvd1689m", + "image_size": 512 + } + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16_ft1024.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16_ft1024.json new file mode 100644 index 0000000000000000000000000000000000000000..d9aba8df1b287e3afc24f7d99f4535abba761c0e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/slat_flow_imgshape2tex_dit_1_3B_512_bf16_ft1024.json @@ -0,0 +1,120 @@ +{ + "models": { + "denoiser": { + "name": "ElasticSLatFlowModel", + "args": { + "resolution": 32, + "in_channels": 64, + "out_channels": 32, + "model_channels": 1536, + "cond_channels": 1024, + "num_blocks": 30, + "num_heads": 12, + "mlp_ratio": 5.3334, + "pe_mode": "rope", + "share_mod": true, + "initialization": "scaled", + "qk_rms_norm": true, + "qk_rms_norm_cross": true + } + } + }, + "dataset": { + "name": "ImageConditionedSLatPbr", + "args": { + "resolution": 1024, + "image_size": 1024, + "min_aesthetic_score": 4.5, + "max_tokens": 32768, + "full_pbr": true, + "pbr_slat_normalization": { + "mean": [ + 3.501659, 2.212398, 2.226094, 0.251093, -0.026248, -0.687364, 0.439898, -0.928075, + 0.029398, -0.339596, -0.869527, 1.038479, -0.972385, 0.126042, -1.129303, 0.455149, + -1.209521, 2.069067, 0.544735, 2.569128, -0.323407, 2.293000, -1.925608, -1.217717, + 1.213905, 0.971588, -0.023631, 0.106750, 2.021786, 0.250524, -0.662387, -0.768862 + ], + "std": [ + 2.665652, 2.743913, 2.765121, 2.595319, 3.037293, 2.291316, 2.144656, 2.911822, + 2.969419, 2.501689, 2.154811, 3.163343, 2.621215, 2.381943, 3.186697, 3.021588, + 2.295916, 3.234985, 3.233086, 2.260140, 2.874801, 2.810596, 3.292720, 2.674999, + 2.680878, 2.372054, 2.451546, 2.353556, 2.995195, 2.379849, 2.786195, 2.775190 + ] + }, + "shape_slat_normalization": { + "mean": [ + 0.781296, 0.018091, -0.495192, -0.558457, 1.060530, 0.093252, 1.518149, -0.933218, + -0.732996, 2.604095, -0.118341, -2.143904, 0.495076, -2.179512, -2.130751, -0.996944, + 0.261421, -2.217463, 1.260067, -0.150213, 3.790713, 1.481266, -1.046058, -1.523667, + -0.059621, 2.220780, 1.621212, 0.877230, 0.567247, -3.175944, -3.186688, 1.578665 + ], + "std": [ + 5.972266, 4.706852, 5.445010, 5.209927, 5.320220, 4.547237, 5.020802, 5.444004, + 5.226681, 5.683095, 4.831436, 5.286469, 5.652043, 5.367606, 5.525084, 4.730578, + 4.805265, 5.124013, 5.530808, 5.619001, 5.103930, 5.417670, 5.269677, 5.547194, + 5.634698, 5.235274, 6.110351, 5.511298, 6.237273, 4.879207, 5.347008, 5.405691 + ] + }, + "attrs": [ + "base_color", + "metallic", + "roughness", + "alpha" + ], + "pretrained_pbr_slat_dec": "microsoft/TRELLIS.2-4B/ckpts/tex_dec_next_dc_f16c32_fp16", + "pretrained_shape_slat_dec": "microsoft/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16" + } + }, + "trainer": { + "name": "ImageConditionedSparseFlowMatchingCFGTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 2, + "batch_split": 1, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 2e-5, + "weight_decay": 0.01, + "betas": [0.9, 0.95], + "eps": 1e-8 + } + }, + "ema_rate": [ + 0.9999 + ], + "mix_precision_mode": "amp", + "mix_precision_dtype": "bfloat16", + "elastic": { + "name": "LinearMemoryController", + "args": { + "target_ratio": 0.75, + "max_mem_ratio_start": 0.25 + } + }, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "i_log": 500, + "i_sample": 1000, + "i_save": 1000, + "p_uncond": 0.1, + "t_schedule": { + "name": "uniform", + "args": {} + }, + "sigma_min": 1e-5, + "image_cond_model": { + "name": "DinoV3FeatureExtractor", + "args": { + "model_name": "facebook/dinov3-vitl16-pretrain-lvd1689m", + "image_size": 1024 + } + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/ss_flow_img_dit_1_3B_64_bf16.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/ss_flow_img_dit_1_3B_64_bf16.json new file mode 100644 index 0000000000000000000000000000000000000000..fb04dbadb0b45dfc164903c005d9c65f990227d5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/gen/ss_flow_img_dit_1_3B_64_bf16.json @@ -0,0 +1,78 @@ +{ + "models": { + "denoiser": { + "name": "SparseStructureFlowModel", + "args": { + "resolution": 16, + "in_channels": 8, + "out_channels": 8, + "model_channels": 1536, + "cond_channels": 1024, + "num_blocks": 30, + "num_heads": 12, + "mlp_ratio": 5.3334, + "pe_mode": "rope", + "share_mod": true, + "initialization": "scaled", + "qk_rms_norm": true, + "qk_rms_norm_cross": true + } + } + }, + "dataset": { + "name": "ImageConditionedSparseStructureLatent", + "args": { + "min_aesthetic_score": 4.5, + "image_size": 512, + "pretrained_ss_dec": "microsoft/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16" + } + }, + "trainer": { + "name": "ImageConditionedFlowMatchingCFGTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 8, + "batch_split": 4, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-4, + "weight_decay": 0.01, + "betas": [0.9, 0.95], + "eps": 1e-8 + } + }, + "ema_rate": [ + 0.9999 + ], + "mix_precision_mode": "amp", + "mix_precision_dtype": "bfloat16", + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "p_uncond": 0.1, + "t_schedule": { + "name": "logitNormal", + "args": { + "mean": 1.0, + "std": 1.0 + } + }, + "sigma_min": 1e-5, + "image_cond_model": { + "name": "DinoV3FeatureExtractor", + "args": { + "model_name": "facebook/dinov3-vitl16-pretrain-lvd1689m", + "image_size": 512 + } + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/shape_vae_next_dc_f16c32_fp16.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/shape_vae_next_dc_f16c32_fp16.json new file mode 100644 index 0000000000000000000000000000000000000000..916a0d99d0d1ecb709553d83246aa9043e25f6be --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/shape_vae_next_dc_f16c32_fp16.json @@ -0,0 +1,134 @@ +{ + "models": { + "encoder": { + "name": "FlexiDualGridVaeEncoder", + "args": { + "model_channels": [64, 128, 256, 512, 1024], + "latent_channels": 32, + "num_blocks": [0, 4, 8, 16, 4], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "down_block_type": [ + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d" + ], + "block_args": [ + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + } + ], + "use_fp16": true + } + }, + "decoder": { + "name": "FlexiDualGridVaeDecoder", + "args": { + "resolution": 256, + "model_channels": [1024, 512, 256, 128, 64], + "latent_channels": 32, + "num_blocks": [4, 16, 8, 4, 0], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "up_block_type": [ + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d" + ], + "block_args": [ + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + } + ], + "use_fp16": true + } + } + }, + "dataset": { + "name": "FlexiDualGridDataset", + "args": { + "resolution": 256, + "max_active_voxels": 1000000, + "max_num_faces": 1000000, + "min_aesthetic_score": 4.5 + } + }, + "trainer": { + "name": "ShapeVaeTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 8, + "batch_split": 2, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-4, + "weight_decay": 0.0 + } + }, + "ema_rate": [ + 0.9999 + ], + "fp16_mode": "inflat_all", + "fp16_scale_growth": 0.001, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "lambda_subdiv": 0.1, + "lambda_intersected": 0.1, + "lambda_vertice": 1e-2, + "lambda_mask": 1, + "lambda_depth": 10, + "lambda_normal": 1, + "lambda_kl": 1e-6, + "lambda_ssim": 0.2, + "lambda_lpips": 0.2, + "camera_randomization_config": { + "radius_range": [2, 100] + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/shape_vae_next_dc_f16c32_fp16_ft_512.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/shape_vae_next_dc_f16c32_fp16_ft_512.json new file mode 100644 index 0000000000000000000000000000000000000000..907d87ec2f53d17f2bfbff793b021d4a62dc4135 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/shape_vae_next_dc_f16c32_fp16_ft_512.json @@ -0,0 +1,140 @@ +{ + "models": { + "encoder": { + "name": "FlexiDualGridVaeEncoder", + "args": { + "model_channels": [64, 128, 256, 512, 1024], + "latent_channels": 32, + "num_blocks": [0, 4, 8, 16, 4], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "down_block_type": [ + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d" + ], + "block_args": [ + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + } + ], + "use_fp16": true + } + }, + "decoder": { + "name": "FlexiDualGridVaeDecoder", + "args": { + "resolution": 512, + "model_channels": [1024, 512, 256, 128, 64], + "latent_channels": 32, + "num_blocks": [4, 16, 8, 4, 0], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "up_block_type": [ + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d" + ], + "block_args": [ + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + } + ], + "use_fp16": true + } + } + }, + "dataset": { + "name": "FlexiDualGridDataset", + "args": { + "resolution": 512, + "max_active_voxels": 1000000, + "max_num_faces": 1000000, + "min_aesthetic_score": 4.5 + } + }, + "trainer": { + "name": "ShapeVaeTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 4, + "batch_split": 2, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-5, + "weight_decay": 0.0 + } + }, + "ema_rate": [ + 0.9999 + ], + "fp16_mode": "inflat_all", + "fp16_scale_growth": 0.001, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "finetune_ckpt": { + "encoder": "PATH_TO_ENCODER_CKPT", + "decoder": "PATH_TO_DECODER_CKPT" + }, + "snapshot_batch_size": 1, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "lambda_subdiv": 0.1, + "lambda_intersected": 0.1, + "lambda_vertice": 1e-2, + "lambda_mask": 1, + "lambda_depth": 10, + "lambda_normal": 1, + "lambda_kl": 1e-6, + "lambda_ssim": 0.2, + "lambda_lpips": 0.2, + "render_resolution": 1024, + "camera_randomization_config": { + "radius_range": [2, 100] + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/tex_vae_next_dc_f16c32_fp16.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/tex_vae_next_dc_f16c32_fp16.json new file mode 100644 index 0000000000000000000000000000000000000000..bd1565e37853df70464c058d335484cdcb238434 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/tex_vae_next_dc_f16c32_fp16.json @@ -0,0 +1,134 @@ +{ + "models": { + "encoder": { + "name": "SparseUnetVaeEncoder", + "args": { + "in_channels": 6, + "model_channels": [64, 128, 256, 512, 1024], + "latent_channels": 32, + "num_blocks": [0, 4, 8, 16, 4], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "down_block_type": [ + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d" + ], + "block_args": [ + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + } + ], + "use_fp16": true + } + }, + "decoder": { + "name": "SparseUnetVaeDecoder", + "args": { + "out_channels": 6, + "model_channels": [1024, 512, 256, 128, 64], + "latent_channels": 32, + "num_blocks": [4, 16, 8, 4, 0], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "up_block_type": [ + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d" + ], + "block_args": [ + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": false + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + } + ], + "use_fp16": true, + "pred_subdiv": false + } + } + }, + "dataset": { + "name": "SparseVoxelPbrDataset", + "args": { + "resolution": 256, + "min_aesthetic_score": 4.5, + "max_active_voxels": 1000000, + "max_num_faces": 1000000, + "with_mesh": false, + "attrs": [ + "base_color", + "metallic", + "roughness", + "alpha" + ] + } + }, + "trainer": { + "name": "PbrVaeTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 8, + "batch_split": 1, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-4, + "weight_decay": 0.0 + } + }, + "ema_rate": [ + 0.9999 + ], + "fp16_mode": "inflat_all", + "fp16_scale_growth": 0.001, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "lambda_kl": 1e-6, + "loss_type": "l1", + "lambda_render": 0.0 + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/tex_vae_next_dc_f16c32_fp16_ft_512.json b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/tex_vae_next_dc_f16c32_fp16_ft_512.json new file mode 100644 index 0000000000000000000000000000000000000000..76c07c875a3960b3276ba0191b2289af2af2ece1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/configs/scvae/tex_vae_next_dc_f16c32_fp16_ft_512.json @@ -0,0 +1,144 @@ +{ + "models": { + "encoder": { + "name": "SparseUnetVaeEncoder", + "args": { + "in_channels": 6, + "model_channels": [64, 128, 256, 512, 1024], + "latent_channels": 32, + "num_blocks": [0, 4, 8, 16, 4], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "down_block_type": [ + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d", + "SparseResBlockS2C3d" + ], + "block_args": [ + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + } + ], + "use_fp16": true + } + }, + "decoder": { + "name": "SparseUnetVaeDecoder", + "args": { + "out_channels": 6, + "model_channels": [1024, 512, 256, 128, 64], + "latent_channels": 32, + "num_blocks": [4, 16, 8, 4, 0], + "block_type": [ + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d", + "SparseConvNeXtBlock3d" + ], + "up_block_type": [ + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d", + "SparseResBlockC2S3d" + ], + "block_args": [ + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + }, + { + "use_checkpoint": true + } + ], + "use_fp16": true, + "pred_subdiv": false + } + } + }, + "dataset": { + "name": "SparseVoxelPbrDataset", + "args": { + "resolution": 512, + "min_aesthetic_score": 4.5, + "max_active_voxels": 1000000, + "max_num_faces": 1000000, + "attrs": [ + "base_color", + "metallic", + "roughness", + "alpha" + ] + } + }, + "trainer": { + "name": "PbrVaeTrainer", + "args": { + "max_steps": 1000000, + "batch_size_per_gpu": 4, + "batch_split": 2, + "optimizer": { + "name": "AdamW", + "args": { + "lr": 1e-5, + "weight_decay": 0.0 + } + }, + "ema_rate": [ + 0.9999 + ], + "fp16_mode": "inflat_all", + "fp16_scale_growth": 0.001, + "grad_clip": { + "name": "AdaptiveGradClipper", + "args": { + "max_norm": 1.0, + "clip_percentile": 95 + } + }, + "finetune_ckpt": { + "encoder": "PATH_TO_ENCODER_CKPT", + "decoder": "PATH_TO_DECODER_CKPT" + }, + "snapshot_batch_size": 1, + "render_resolution": 512, + "i_log": 500, + "i_sample": 10000, + "i_save": 10000, + "lambda_kl": 1e-6, + "lambda_render": 1.0, + "loss_type": "l1", + "lambda_ssim": 0.2, + "lambda_lpips": 0.2, + "camera_randomization_config": { + "radius_range": [2, 100] + } + } + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/README.md b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0eb09fad15bc9f960a81952631483879d2766a5e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/README.md @@ -0,0 +1,172 @@ +# Dataset Preparation Toolkit + +This toolkit provides a comprehensive pipeline for preparing 3D datasets, including downloading, processing, voxelizing, and latent encoding for SC-VAE and Flow Model training. + +### Step 1: Install Dependencies + +Initialize the environment and install necessary dependencies: + +```bash +. ./data_toolkit/setup.sh +``` + +### Step 2: Initialize Metadata + +Before processing, load the dataset metadata. + +```bash +python data_toolkit/build_metadata.py --root [--source ] +``` + +**Arguments:** +- `SUBSET`: Target dataset subset. Options: `ObjaverseXL`, `ABO`, `HSSD`, `TexVerse` (Training sets); `SketchfabPicked`, `Toys4k` (Test sets). +- `ROOT`: Root directory to save the data. +- `SOURCE`: Data source (Required if `SUBSET` is `ObjaverseXL`). Options: `sketchfab`, `github`. + +**Example:** +Load metadata for `ObjaverseXL` (sketchfab) and save to `datasets/ObjaverseXL_sketchfab`: +```bash +python data_toolkit/build_metadata.py ObjaverseXL --source sketchfab --root datasets/ObjaverseXL_sketchfab +``` + +### Step 3: Download Data + +Download the 3D assets to the local storage. + +```bash +python data_toolkit/download.py --root [--rank --world_size ] +``` + +**Arguments:** +- `RANK` / `WORLD_SIZE`: Parameters for multi-node distributed downloading. + +**Example:** +To download the `ObjaverseXL` subset: + +> **Note:** The example below sets a large `WORLD_SIZE` (160,000) for demonstration purposes, meaning only a tiny fraction of the dataset will be downloaded by this single process. + +```bash +python data_toolkit/download.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab --world_size 160000 +``` + +*Attention: Some datasets may require an interactive Hugging Face login or manual steps. Please follow any on-screen instructions.* + +**Update Metadata:** +After downloading, update the metadata registry: +```bash +python data_toolkit/build_metadata.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +``` + +### Step 4: Process Mesh and PBR Textures + +Standardize 3D assets by dumping mesh and PBR textures. +*Note: This process utilizes the CPU.* + +```bash +# Dump Meshes +python data_toolkit/dump_mesh.py --root [--rank --world_size ] + +# Dump PBR Textures +python data_toolkit/dump_pbr.py --root [--rank --world_size ] + +# Get statisitics of the asset +python asset_stats.py --root [--rank --world_size ] +``` + +**Example:** +```bash +python data_toolkit/dump_mesh.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +python data_toolkit/dump_pbr.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +python asset_stats.py --root datasets/ObjaverseXL_sketchfab +``` + +**Update Metadata:** +```bash +python data_toolkit/build_metadata.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +``` + +### Step 5: Convert to O-Voxels + +Convert the processed meshes and textures into O-Voxels format. +*Note: This process utilizes the CPU.* + +```bash +python data_toolkit/dual_grid.py --root [--rank --world_size ] [--resolution ] + +python data_toolkit/voxelize_pbr.py --root [--rank --world_size ] [--resolution ] +``` + +**Arguments:** +- `RESOLUTION`: Target resolutions for O-Voxels, comma-separated (e.g., `256,512,1024`). Default is `256`. + +**Example:** +Convert `ObjaverseXL` to resolutions 256, 512, and 1024: +```bash +python data_toolkit/dual_grid.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab --resolution 256,512,1024 +python data_toolkit/voxelize_pbr.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab --resolution 256,512,1024 +``` + + +### At this point, the dataset is ready for SC-VAE Training + +### Step 6: Encode Latents + +Encode sparse structures into latents to train the first-stage generator. + +```bash +# 1. Encode Shape Latents +python data_toolkit/encode_shape_latent.py --root [--rank --world_size ] [--resolution ] + +# 2. Encode PBR Latents +python data_toolkit/encode_pbr_latent.py --root [--rank --world_size ] [--resolution ] + +# 3. Update Metadata (Required before next step) +python data_toolkit/build_metadata.py --root + +# 4. Encode Sparse Structure (SS) Latents +python data_toolkit/encode_ss_latent.py --root --shape_latent_name [--rank --world_size ] [--resolution ] +``` + +**Arguments:** +- `RESOLUTION`: Input O-Voxel resolution. Default is `1024`. +- `SS_RESOLUTION`: Resolution for sparse structures. Default is `64`. +- `SHAPE_LATENT_NAME`: The specific version name of the shape latent. + +**Example:** +```bash +python data_toolkit/encode_shape_latent.py --root datasets/ObjaverseXL_sketchfab --resolution 512 +python data_toolkit/encode_pbr_latent.py --root datasets/ObjaverseXL_sketchfab --resolution 512 +python data_toolkit/encode_shape_latent.py --root datasets/ObjaverseXL_sketchfab --resolution 1024 +python data_toolkit/encode_pbr_latent.py --root datasets/ObjaverseXL_sketchfab --resolution 1024 + +# Update metadata +python data_toolkit/build_metadata.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab + +# Encode SS Latents +python data_toolkit/encode_ss_latent.py --root datasets/ObjaverseXL_sketchfab --shape_latent_name shape_enc_next_dc_f16c32_fp16_1024 --resolution 64 + +# Final Metadata Update +python data_toolkit/build_metadata.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +``` + +### Step 7: Render Image Conditions + +Render multi-view images to train the image-conditioned generator. +*Note: This process may utilize the CPU.* + +```bash +python data_toolkit/render_cond.py --root [--num_views ] [--rank --world_size ] +``` + +**Arguments:** +- `NUM_VIEWS`: Number of views to render per asset. Default is `16`. + +**Example:** +```bash +python data_toolkit/render_cond.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +``` + +**Final Metadata Update:** +```bash +python data_toolkit/build_metadata.py ObjaverseXL --root datasets/ObjaverseXL_sketchfab +``` \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/asset_stats.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/asset_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..8e269333f6d9b4d205e93a8443d3f813e3f54b41 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/asset_stats.py @@ -0,0 +1,132 @@ +import os +import argparse +import pickle +from tqdm import tqdm +import pandas as pd +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--mesh_dump_root', type=str, default=None, + help='Directory to save the mesh dumps') + parser.add_argument('--pbr_dump_root', type=str, default=None, + help='Directory to save the pbr dumps') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=0) + opt = parser.parse_args() + opt = edict(vars(opt)) + opt.mesh_dump_root = opt.mesh_dump_root or opt.root + opt.pbr_dump_root = opt.pbr_dump_root or opt.root + + os.makedirs(os.path.join(opt.root, 'asset_stats', 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'asset_stats', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'asset_stats','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.mesh_dump_root, 'mesh_dumps','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + if 'num_faces' in metadata.columns: + metadata = metadata[metadata['num_faces'].isnull()] + metadata = metadata[(metadata['mesh_dumped'] == True) | (metadata['pbr_dumped'] == True)] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + + print(f'Processing {len(metadata)} objects...') + + # process objects + records = [] + with ThreadPoolExecutor(max_workers=opt.max_workers or os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc='Processing objects') as pbar: + def worker(metadatum): + try: + sha256 = metadatum['sha256'] + if metadatum['pbr_dumped'] == True: + with open(os.path.join(opt.pbr_dump_root, 'pbr_dumps', f'{sha256}.pickle'), 'rb') as f: + dump = pickle.load(f) + + num_faces = 0 + num_vertices = 0 + for obj in dump['objects']: + if obj['vertices'].size == 0 or obj['faces'].size == 0: + continue + num_faces += obj['faces'].shape[0] + num_vertices += obj['vertices'].shape[0] + + num_basecolor_tex = 0 + num_metallic_tex = 0 + num_roughness_tex = 0 + num_alpha_tex = 0 + for mat in dump['materials']: + if mat['baseColorTexture'] is not None: + num_basecolor_tex += 1 + if mat['metallicTexture'] is not None: + num_metallic_tex += 1 + if mat['roughnessTexture'] is not None: + num_roughness_tex += 1 + if mat['alphaTexture'] is not None: + num_alpha_tex += 1 + + record = { + 'sha256': sha256, + 'num_faces': num_faces, + 'num_vertices': num_vertices, + 'num_basecolor_tex': num_basecolor_tex, + 'num_metallic_tex': num_metallic_tex, + 'num_roughness_tex': num_roughness_tex, + 'num_alpha_tex': num_alpha_tex, + } + records.append(record) + else: + with open(os.path.join(opt.mesh_dump_root,'mesh_dumps', f'{sha256}.pickle'), 'rb') as f: + dump = pickle.load(f) + + num_faces = 0 + num_vertices = 0 + for obj in dump['objects']: + if obj['vertices'].size == 0 or obj['faces'].size == 0: + continue + num_faces += obj['faces'].shape[0] + num_vertices += obj['vertices'].shape[0] + + record = { + 'sha256': sha256, + 'num_faces': num_faces, + 'num_vertices': num_vertices, + } + records.append(record) + pbar.update() + except Exception as e: + print(f'Error processing {sha256}: {e}') + pbar.update() + + for metadatum in metadata.to_dict('records'): + executor.submit(worker, metadatum) + + executor.shutdown(wait=True) + + # save records + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.root, 'asset_stats', 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/dump_mesh.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/dump_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa5d5596a2a8fb94ed041e93588792d2fb58341 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/dump_mesh.py @@ -0,0 +1,242 @@ +import argparse, sys, os, math, io +from typing import * +import bpy +import bmesh +from mathutils import Vector, Matrix +import numpy as np +import pickle + + +"""=============== BLENDER ===============""" + +IMPORT_FUNCTIONS: Dict[str, Callable] = { + "obj": bpy.ops.import_scene.obj if bpy.app.version[0] < 4 else bpy.ops.wm.obj_import, + "glb": bpy.ops.import_scene.gltf, + "gltf": bpy.ops.import_scene.gltf, + "usd": bpy.ops.import_scene.usd, + "fbx": bpy.ops.import_scene.fbx, + "stl": bpy.ops.import_mesh.stl if bpy.app.version[0] < 4 else bpy.ops.wm.stl_import, + "usda": bpy.ops.import_scene.usda, + "dae": bpy.ops.wm.collada_import, + "ply": bpy.ops.import_mesh.ply if bpy.app.version[0] < 4 else bpy.ops.wm.ply_import, + "abc": bpy.ops.wm.alembic_import, + "blend": bpy.ops.wm.append, +} + + +def init_scene() -> None: + """Resets the scene to a clean state. + + Returns: + None + """ + # delete everything + for obj in bpy.data.objects: + bpy.data.objects.remove(obj, do_unlink=True) + + # delete all the materials + for material in bpy.data.materials: + bpy.data.materials.remove(material, do_unlink=True) + + # delete all the textures + for texture in bpy.data.textures: + bpy.data.textures.remove(texture, do_unlink=True) + + # delete all the images + for image in bpy.data.images: + bpy.data.images.remove(image, do_unlink=True) + + +def load_object(object_path: str) -> None: + """Loads a model with a supported file extension into the scene. + + Args: + object_path (str): Path to the model file. + + Raises: + ValueError: If the file extension is not supported. + + Returns: + None + """ + file_extension = object_path.split(".")[-1].lower() + if file_extension is None: + raise ValueError(f"Unsupported file type: {object_path}") + + if file_extension == "usdz": + # install usdz io package + dirname = os.path.dirname(os.path.realpath(__file__)) + usdz_package = os.path.join(dirname, "io_scene_usdz.zip") + bpy.ops.preferences.addon_install(filepath=usdz_package) + # enable it + addon_name = "io_scene_usdz" + bpy.ops.preferences.addon_enable(module=addon_name) + # import the usdz + from io_scene_usdz.import_usdz import import_usdz + + import_usdz(context, filepath=object_path, materials=True, animations=True) + return None + + # load from existing import functions + import_function = IMPORT_FUNCTIONS[file_extension] + + print(f"Loading object from {object_path}") + if file_extension == "blend": + import_function(directory=object_path, link=False) + elif file_extension in {"glb", "gltf"}: + import_function(filepath=object_path, merge_vertices=True, import_shading='NORMALS', bone_heuristic='TEMPERANCE') + else: + import_function(filepath=object_path) + + +def delete_invisible_objects() -> None: + """Deletes all invisible objects in the scene. + + Returns: + None + """ + to_remove = [] + for obj in bpy.context.scene.objects: + if obj.hide_viewport or obj.hide_render: + obj.hide_viewport = False + obj.hide_render = False + obj.hide_select = False + to_remove.append(obj) + for obj in to_remove: + bpy.data.objects.remove(obj, do_unlink=True) + + # Delete invisible collections + invisible_collections = [col for col in bpy.data.collections if col.hide_viewport] + for col in invisible_collections: + bpy.data.collections.remove(col) + + +def scene_bbox() -> Tuple[Vector, Vector]: + """Returns the bounding box of the scene. + + Taken from Shap-E rendering script + (https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82) + + Returns: + Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box. + """ + bbox_min = (math.inf,) * 3 + bbox_max = (-math.inf,) * 3 + found = False + scene_meshes = [obj for obj in bpy.context.scene.objects.values() if isinstance(obj.data, bpy.types.Mesh)] + for obj in scene_meshes: + found = True + for coord in obj.bound_box: + coord = Vector(coord) + coord = obj.matrix_world @ coord + bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord)) + bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord)) + if not found: + raise RuntimeError("no objects in scene to compute bounding box for") + return Vector(bbox_min), Vector(bbox_max) + + +def normalize_scene() -> Tuple[float, Vector]: + """Normalizes the scene by scaling and translating it to fit in a unit cube centered + at the origin. + + Mostly taken from the Point-E / Shap-E rendering script + (https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112), + but fix for multiple root objects: (see bug report here: + https://github.com/openai/shap-e/pull/60). + + Returns: + Tuple[float, Vector]: The scale factor and the offset applied to the scene. + """ + scene_root_objects = [obj for obj in bpy.context.scene.objects.values() if not obj.parent] + if len(scene_root_objects) > 1: + # create an empty object to be used as a parent for all root objects + scene = bpy.data.objects.new("ParentEmpty", None) + bpy.context.scene.collection.objects.link(scene) + + # parent all root objects to the empty object + for obj in scene_root_objects: + obj.parent = scene + else: + scene = scene_root_objects[0] + + bbox_min, bbox_max = scene_bbox() + scale = 1 / max(bbox_max - bbox_min) + scene.scale = scene.scale * scale + + # Apply scale to matrix_world. + bpy.context.view_layer.update() + bbox_min, bbox_max = scene_bbox() + offset = -(bbox_min + bbox_max) / 2 + scene.matrix_world.translation += offset + + return scale, offset + + +def main(arg): + # Initialize context + if arg.object.endswith(".blend"): + delete_invisible_objects() + else: + init_scene() + load_object(arg.object) + print('[INFO] Scene initialized.') + + # Normalize scene + scale, offset = normalize_scene() + print('[INFO] Scene normalized.') + + # Start dumping + depsgraph = bpy.context.evaluated_depsgraph_get() + scene = bpy.context.scene + output = { + 'objects': [], + } + + # Dumping meshes + for obj in scene.objects: + if obj.type != 'MESH': + continue + + pack = { + "vertices": None, + "faces": None, + } + + eval_obj = obj.evaluated_get(depsgraph) + eval_mesh = eval_obj.to_mesh() + + bm = bmesh.new() + bm.from_mesh(eval_mesh) + bm.transform(obj.matrix_world) + bmesh.ops.triangulate(bm, faces=bm.faces) + bm.to_mesh(eval_mesh) + bm.free() + + pack["vertices"] = np.array([ + v.co[:] for v in eval_mesh.vertices + ], dtype=np.float32) # (N, 3) + + pack["faces"] = np.array([ + [eval_mesh.loops[i].vertex_index for i in poly.loop_indices] + for poly in eval_mesh.polygons + ], dtype=np.int32) # (F, 3) + + output['objects'].append(pack) + + # Save output + os.makedirs(os.path.dirname(arg.output_path), exist_ok=True) + with open(arg.output_path, 'wb') as f: + pickle.dump(output, f) + print('[INFO] Output saved to {}.'.format(arg.output_path)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.') + parser.add_argument('--object', type=str, help='Path to the 3D model file to be rendered.') + parser.add_argument('--output_path', type=str, default='/tmp', help='The path the output will be dumped to.') + argv = sys.argv[sys.argv.index("--") + 1:] + args = parser.parse_args(argv) + + main(args) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/dump_pbr.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/dump_pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..302df2c355f687fc7a8a077d24cf1d37a015150b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/dump_pbr.py @@ -0,0 +1,485 @@ +import argparse, sys, os, math, io +from typing import * +import bpy +import bmesh +from mathutils import Vector, Matrix +import numpy as np +from PIL import Image +import pickle + + +"""=============== BLENDER ===============""" + +IMPORT_FUNCTIONS: Dict[str, Callable] = { + "obj": bpy.ops.import_scene.obj if bpy.app.version[0] < 4 else bpy.ops.wm.obj_import, + "glb": bpy.ops.import_scene.gltf, + "gltf": bpy.ops.import_scene.gltf, + "usd": bpy.ops.import_scene.usd, + "fbx": bpy.ops.import_scene.fbx, + "stl": bpy.ops.import_mesh.stl if bpy.app.version[0] < 4 else bpy.ops.wm.stl_import, + "usda": bpy.ops.import_scene.usda, + "dae": bpy.ops.wm.collada_import, + "ply": bpy.ops.import_mesh.ply if bpy.app.version[0] < 4 else bpy.ops.wm.ply_import, + "abc": bpy.ops.wm.alembic_import, + "blend": bpy.ops.wm.append, +} + + +def init_scene() -> None: + """Resets the scene to a clean state. + + Returns: + None + """ + # delete everything + for obj in bpy.data.objects: + bpy.data.objects.remove(obj, do_unlink=True) + + # delete all the materials + for material in bpy.data.materials: + bpy.data.materials.remove(material, do_unlink=True) + + # delete all the textures + for texture in bpy.data.textures: + bpy.data.textures.remove(texture, do_unlink=True) + + # delete all the images + for image in bpy.data.images: + bpy.data.images.remove(image, do_unlink=True) + + +def load_object(object_path: str) -> None: + """Loads a model with a supported file extension into the scene. + + Args: + object_path (str): Path to the model file. + + Raises: + ValueError: If the file extension is not supported. + + Returns: + None + """ + file_extension = object_path.split(".")[-1].lower() + if file_extension is None: + raise ValueError(f"Unsupported file type: {object_path}") + + if file_extension == "usdz": + # install usdz io package + dirname = os.path.dirname(os.path.realpath(__file__)) + usdz_package = os.path.join(dirname, "io_scene_usdz.zip") + bpy.ops.preferences.addon_install(filepath=usdz_package) + # enable it + addon_name = "io_scene_usdz" + bpy.ops.preferences.addon_enable(module=addon_name) + # import the usdz + from io_scene_usdz.import_usdz import import_usdz + + import_usdz(context, filepath=object_path, materials=True, animations=True) + return None + + # load from existing import functions + import_function = IMPORT_FUNCTIONS[file_extension] + + print(f"Loading object from {object_path}") + if file_extension == "blend": + import_function(directory=object_path, link=False) + elif file_extension in {"glb", "gltf"}: + import_function(filepath=object_path, merge_vertices=True, import_shading='NORMALS', bone_heuristic='TEMPERANCE') + else: + import_function(filepath=object_path) + + +def delete_invisible_objects() -> None: + """Deletes all invisible objects in the scene. + + Returns: + None + """ + to_remove = [] + for obj in bpy.context.scene.objects: + if obj.hide_viewport or obj.hide_render: + obj.hide_viewport = False + obj.hide_render = False + obj.hide_select = False + to_remove.append(obj) + for obj in to_remove: + bpy.data.objects.remove(obj, do_unlink=True) + + # Delete invisible collections + invisible_collections = [col for col in bpy.data.collections if col.hide_viewport] + for col in invisible_collections: + bpy.data.collections.remove(col) + + +def scene_bbox() -> Tuple[Vector, Vector]: + """Returns the bounding box of the scene. + + Taken from Shap-E rendering script + (https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82) + + Returns: + Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box. + """ + bbox_min = (math.inf,) * 3 + bbox_max = (-math.inf,) * 3 + found = False + scene_meshes = [obj for obj in bpy.context.scene.objects.values() if isinstance(obj.data, bpy.types.Mesh)] + for obj in scene_meshes: + found = True + for coord in obj.bound_box: + coord = Vector(coord) + coord = obj.matrix_world @ coord + bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord)) + bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord)) + if not found: + raise RuntimeError("no objects in scene to compute bounding box for") + return Vector(bbox_min), Vector(bbox_max) + + +def normalize_scene() -> Tuple[float, Vector]: + """Normalizes the scene by scaling and translating it to fit in a unit cube centered + at the origin. + + Mostly taken from the Point-E / Shap-E rendering script + (https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112), + but fix for multiple root objects: (see bug report here: + https://github.com/openai/shap-e/pull/60). + + Returns: + Tuple[float, Vector]: The scale factor and the offset applied to the scene. + """ + scene_root_objects = [obj for obj in bpy.context.scene.objects.values() if not obj.parent] + if len(scene_root_objects) > 1: + # create an empty object to be used as a parent for all root objects + scene = bpy.data.objects.new("ParentEmpty", None) + bpy.context.scene.collection.objects.link(scene) + + # parent all root objects to the empty object + for obj in scene_root_objects: + obj.parent = scene + else: + scene = scene_root_objects[0] + + bbox_min, bbox_max = scene_bbox() + scale = 1 / max(bbox_max - bbox_min) + scene.scale = scene.scale * scale + + # Apply scale to matrix_world. + bpy.context.view_layer.update() + bbox_min, bbox_max = scene_bbox() + offset = -(bbox_min + bbox_max) / 2 + scene.matrix_world.translation += offset + + return scale, offset + + +# =============== NODE TREE PARSING =============== + +def extract_image(tex_node, channels): + image = tex_node.image + pixels = np.array(image.pixels[:]) + data = pixels.reshape(image.size[1], image.size[0], -1) + data = data[..., channels] + + if data.dtype != np.uint8: + data = np.clip(data, 0.0, 1.0) + data = (data * 255).astype(np.uint8) + + if len(data.shape) == 2: # Single channel + pil_image = Image.fromarray(data, mode='L') + elif data.shape[2] == 3: + pil_image = Image.fromarray(data, mode='RGB') + elif data.shape[2] == 4: + pil_image = Image.fromarray(data, mode='RGBA') + else: + raise ValueError("Unsupported channel shape for image") + + buffer = io.BytesIO() + pil_image.save(buffer, format='PNG') + png_bytes = buffer.getvalue() + + return { + 'image': png_bytes, + 'interpolation': tex_node.interpolation, + 'extension': tex_node.extension, + } + + +def try_extract_image(link, expected_channel='RGB'): + """ + Tries to extract an image from a texture node link. + Supported sub tree modes: + - RGB: + TEX_IMAGE -> + - R, G, B: + TEX_IMAGE -> SEPARATE_COLOR -> + - A: + TEX_IMAGE -> + """ + assert expected_channel in ['RGB', 'R', 'G', 'B', 'A'], "Unsupported channel" + + if expected_channel == 'RGB': + assert link.from_node.type == 'TEX_IMAGE', "Material is not supported" + assert link.from_socket.name == 'Color', "Material is not supported" + tex_node = link.from_node + return extract_image(tex_node, [0, 1, 2]) + + if expected_channel in ['R', 'G', 'B']: + socket_name = { + 'R': 'Red', + 'G': 'Green', + 'B': 'Blue', + }[expected_channel] + assert link.from_node.type == 'SEPARATE_COLOR' and link.from_node.mode == 'RGB', \ + f"Material is not supported, {link.from_node.type}, {link.from_node.mode}" + assert link.from_socket.name == socket_name, "Material is not supported" + sep_node = link.from_node + assert sep_node.inputs[0].is_linked and sep_node.inputs[0].links[0].from_node.type == 'TEX_IMAGE', \ + "Material is not supported" + assert sep_node.inputs[0].links[0].from_socket.name == 'Color', "Material is not supported" + tex_node = sep_node.inputs[0].links[0].from_node + channel_index = { + 'R': 0, + 'G': 1, + 'B': 2, + }[expected_channel] + return extract_image(tex_node, channel_index) + + if expected_channel == 'A': + assert link.from_node.type == 'TEX_IMAGE', "Material is not supported" + assert link.from_socket.name == 'Alpha', "Material is not supported" + tex_node = link.from_node + return extract_image(tex_node, 3) + + +def try_extract_factor(link, mode='color'): + """ + Tries to extract a factor from a math node link. + Supported sub tree modes: + - color: + ANY -> MIX(MULTIPLY) -> + - scalar: + ANY -> MATH(MULTIPLY) -> + """ + assert mode in ['color','scalar'], "Unsupported mode" + + if mode == 'color': + if link.from_node.type == 'MIX': + mix_node = link.from_node + assert mix_node.data_type == 'RGBA' and mix_node.blend_type == 'MULTIPLY', f"Material is not supported, {mix_node.data_type}, {mix_node.blend_type}" + assert not mix_node.inputs['Factor'].is_linked and mix_node.inputs['Factor'].default_value == 1.0, \ + "Material is not supported" + if mix_node.inputs['A'].is_linked: + assert not mix_node.inputs['B'].is_linked, "Material is not supported" + return (list(mix_node.inputs['B'].default_value)[:3], mix_node.inputs['A'].links[0]) + else: + assert not mix_node.inputs['A'].is_linked, "Material is not supported" + assert mix_node.inputs['B'].is_linked, "Material is not supported" + return (list(mix_node.inputs['A'].default_value)[:3], mix_node.inputs['B'].links[0]) + return ([1.0, 1.0, 1.0], link) + + if mode =='scalar': + if link.from_node.type == 'MATH': + math_node = link.from_node + assert math_node.operation == 'MULTIPLY', "Material is not supported" + assert math_node.inputs[0].is_linked, "Material is not supported" + assert not math_node.inputs[1].is_linked, "Material is not supported" + return (math_node.inputs[1].default_value, math_node.inputs[0].links[0]) + return (1.0, link) + + +def try_extract_image_with_factor(link, expected_channel='RGB'): + """ + Tries to extract an image and a factor from a texture node link. + """ + factor, link = try_extract_factor(link, 'color' if expected_channel in ['RGB'] else 'scalar') + image = try_extract_image(link, expected_channel) + return (factor, image) + + +def main(arg): + # Initialize context + if arg.object.endswith(".blend"): + delete_invisible_objects() + else: + init_scene() + load_object(arg.object) + print('[INFO] Scene initialized.') + + # Normalize scene + scale, offset = normalize_scene() + print('[INFO] Scene normalized.') + + # Start dumping + depsgraph = bpy.context.evaluated_depsgraph_get() + scene = bpy.context.scene + output = { + 'materials': [], + 'objects': [], + } + + # Dumping materials + for mat in bpy.data.materials: + assert mat.use_nodes == True, "Material is not supported" + + pack = { + "baseColorFactor": [1.0, 1.0, 1.0], + "alphaFactor": 1.0, + "metallicFactor": 1.0, + "roughnessFactor": 1.0, + "alphaMode": "OPAQUE", + "alphaCutoff": 0.5, + "baseColorTexture": None, + "alphaTexture": None, + "metallicTexture": None, + "roughnessTexture": None, + } + + try: + principled_node = mat.node_tree.nodes.get('Principled BSDF') + assert principled_node is not None, "Material is not supported" + + # Handle base color + if not principled_node.inputs['Base Color'].is_linked: + pack["baseColorFactor"] = list(principled_node.inputs['Base Color'].default_value) + else: + link = principled_node.inputs['Base Color'].links[0] + if link.from_node.type == 'RGB': + pack["baseColorFactor"] = list(link.from_node.outputs[0].default_value) + else: + factor, image = try_extract_image_with_factor(link, 'RGB') + pack["baseColorFactor"] = factor + pack["baseColorTexture"] = image + + # Handle alpha + if not principled_node.inputs['Alpha'].is_linked: + pack["alphaFactor"] = principled_node.inputs['Alpha'].default_value + if pack["alphaFactor"] < 1.0: + pack["alphaMode"] = "BLEND" + else: + link = principled_node.inputs['Alpha'].links[0] + node = link.from_node + if node.type == 'VALUE': + pack["alphaFactor"] = node.outputs[0].default_value + if pack["alphaFactor"] < 1.0: + pack["alphaMode"] = "BLEND" + else: + pack["alphaMode"] = "BLEND" + if node.type == 'MATH': + if node.operation == 'ROUND': + assert node.inputs[0].is_linked, "Material is not supported" + pack["alphaMode"] = "MASK" + link = node.inputs[0].links[0] + elif node.operation == 'SUBTRACT': + assert node.inputs[0].default_value == 1.0 and \ + node.inputs[1].is_linked and \ + node.inputs[1].links[0].from_node.type == 'MATH' and \ + node.inputs[1].links[0].from_node.operation == 'LESS_THAN', \ + "Material is not supported" + assert node.inputs[1].links[0].from_node.inputs[0].is_linked, "Material is not supported" + pack["alphaMode"] = "MASK" + pack["alphaCutoff"] = node.inputs[1].links[0].from_node.inputs[1].default_value + link = node.inputs[1].links[0].from_node.inputs[0].links[0] + factor, image = try_extract_image_with_factor(link, 'A') + pack["alphaFactor"] = factor + pack["alphaTexture"] = image + + # Handle metallic + if not principled_node.inputs['Metallic'].is_linked: + pack["metallicFactor"] = principled_node.inputs['Metallic'].default_value + else: + link = principled_node.inputs['Metallic'].links[0] + node = link.from_node + if node.type == 'VALUE': + pack["metallicFactor"] = node.outputs[0].default_value + else: + factor, image = try_extract_image_with_factor(link, 'B') + pack["metallicFactor"] = factor + pack["metallicTexture"] = image + + # Handle roughness + if not principled_node.inputs['Roughness'].is_linked: + pack["roughnessFactor"] = principled_node.inputs['Roughness'].default_value + else: + link = principled_node.inputs['Roughness'].links[0] + node = link.from_node + if node.type == 'VALUE': + pack["roughnessFactor"] = node.outputs[0].default_value + else: + factor, image = try_extract_image_with_factor(link, 'G') + pack["roughnessFactor"] = factor + pack["roughnessTexture"] = image + + output['materials'].append(pack) + except: + with open(arg.output_path + '_error.txt', 'w') as f: + f.write(str([[n.name] for n in mat.node_tree.nodes])) + raise RuntimeError("Material is not supported") + + # Dumping meshes + for obj in scene.objects: + if obj.type != 'MESH': + continue + + pack = { + "vertices": None, + "faces": None, + "uvs": None, + "matIDs": None, + } + + eval_obj = obj.evaluated_get(depsgraph) + eval_mesh = eval_obj.to_mesh() + + bm = bmesh.new() + bm.from_mesh(eval_mesh) + bm.transform(obj.matrix_world) + bmesh.ops.triangulate(bm, faces=bm.faces) + bm.to_mesh(eval_mesh) + bm.free() + + pack["vertices"] = np.array([ + v.co[:] for v in eval_mesh.vertices + ], dtype=np.float32) # (N, 3) + + pack["faces"] = np.array([ + [eval_mesh.loops[i].vertex_index for i in poly.loop_indices] + for poly in eval_mesh.polygons + ], dtype=np.int32) # (F, 3) + + pack["normals"] = np.array([ + [eval_mesh.loops[i].normal for i in poly.loop_indices] + for poly in eval_mesh.polygons + ], dtype=np.float32) # (F, 3, 3) + + if eval_mesh.uv_layers.active is not None: + pack["uvs"] = np.array([ + [eval_mesh.uv_layers.active.data[i].uv for i in poly.loop_indices] + for poly in eval_mesh.polygons + ], dtype=np.float32) # (F, 3, 2) + + pack["mat_ids"] = np.array([ + bpy.data.materials.find(obj.material_slots[poly.material_index].name) + if len(obj.material_slots) > 0 and obj.material_slots[poly.material_index].material is not None else -1 + for poly in eval_mesh.polygons + ], dtype=np.int32) + + output['objects'].append(pack) + + # Save output + os.makedirs(os.path.dirname(arg.output_path), exist_ok=True) + with open(arg.output_path, 'wb') as f: + pickle.dump(output, f) + print('[INFO] Output saved to {}.'.format(arg.output_path)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.') + parser.add_argument('--object', type=str, help='Path to the 3D model file to be rendered.') + parser.add_argument('--output_path', type=str, default='/tmp', help='The path the output will be dumped to.') + argv = sys.argv[sys.argv.index("--") + 1:] + args = parser.parse_args(argv) + + main(args) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/install_pillow.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/install_pillow.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b0b0c4a7c345ed2c86a80307840805eb64bd47 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/install_pillow.py @@ -0,0 +1,6 @@ +import subprocess +import sys +import ensurepip + +ensurepip.bootstrap() +subprocess.check_call([sys.executable, "-m", "pip", "install", "Pillow"]) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/io_scene_usdz.zip b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/io_scene_usdz.zip new file mode 100644 index 0000000000000000000000000000000000000000..153a9d97245cfbf98c2c53869987d82f1396922e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/io_scene_usdz.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec07ab6125fe0a021ed08c64169eceda126330401aba3d494d5203d26ac4b093 +size 34685 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/render_cond.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/render_cond.py new file mode 100644 index 0000000000000000000000000000000000000000..c3f87e23f7a2217619b13e1982c04224aa5bfc13 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/blender_script/render_cond.py @@ -0,0 +1,437 @@ +import argparse, sys, os, math, re, glob +from typing import * +import bpy +from mathutils import Vector, Matrix +import numpy as np +import json +import glob + + +"""=============== BLENDER ===============""" + +IMPORT_FUNCTIONS: Dict[str, Callable] = { + "obj": bpy.ops.import_scene.obj, + "glb": bpy.ops.import_scene.gltf, + "gltf": bpy.ops.import_scene.gltf, + "usd": bpy.ops.import_scene.usd, + "fbx": bpy.ops.import_scene.fbx, + "stl": bpy.ops.import_mesh.stl, + "usda": bpy.ops.import_scene.usda, + "dae": bpy.ops.wm.collada_import, + "ply": bpy.ops.import_mesh.ply, + "abc": bpy.ops.wm.alembic_import, + "blend": bpy.ops.wm.append, +} + +EXT = { + 'PNG': 'png', + 'JPEG': 'jpg', + 'OPEN_EXR': 'exr', + 'TIFF': 'tiff', + 'BMP': 'bmp', + 'HDR': 'hdr', + 'TARGA': 'tga' +} + + +def init_render(engine='CYCLES', resolution=512): + bpy.context.scene.render.engine = engine + bpy.context.scene.render.resolution_x = resolution + bpy.context.scene.render.resolution_y = resolution + bpy.context.scene.render.resolution_percentage = 100 + bpy.context.scene.render.image_settings.file_format = 'PNG' + bpy.context.scene.render.image_settings.color_mode = 'RGBA' + bpy.context.scene.render.film_transparent = True + + bpy.context.scene.cycles.device = 'GPU' + bpy.context.scene.cycles.samples = 32 + bpy.context.scene.cycles.filter_type = 'BOX' + bpy.context.scene.cycles.filter_width = 1 + bpy.context.scene.cycles.diffuse_bounces = 1 + bpy.context.scene.cycles.glossy_bounces = 1 + bpy.context.scene.cycles.transparent_max_bounces = 3 + bpy.context.scene.cycles.transmission_bounces = 3 + bpy.context.scene.cycles.use_denoising = True + + bpy.context.preferences.addons['cycles'].preferences.get_devices() + bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA' + + +def init_scene() -> None: + """Resets the scene to a clean state. + + Returns: + None + """ + # delete everything + for obj in bpy.data.objects: + bpy.data.objects.remove(obj, do_unlink=True) + + # delete all the materials + for material in bpy.data.materials: + bpy.data.materials.remove(material, do_unlink=True) + + # delete all the textures + for texture in bpy.data.textures: + bpy.data.textures.remove(texture, do_unlink=True) + + # delete all the images + for image in bpy.data.images: + bpy.data.images.remove(image, do_unlink=True) + + +def init_camera(): + cam = bpy.data.objects.new('Camera', bpy.data.cameras.new('Camera')) + bpy.context.collection.objects.link(cam) + bpy.context.scene.camera = cam + cam.data.sensor_height = cam.data.sensor_width = 32 + cam_constraint = cam.constraints.new(type='TRACK_TO') + cam_constraint.track_axis = 'TRACK_NEGATIVE_Z' + cam_constraint.up_axis = 'UP_Y' + cam_empty = bpy.data.objects.new("Empty", None) + cam_empty.location = (0, 0, 0) + bpy.context.scene.collection.objects.link(cam_empty) + cam_constraint.target = cam_empty + return cam + + +def init_uniform_lighting(): + # Clear existing lights + bpy.ops.object.select_all(action="DESELECT") + bpy.ops.object.select_by_type(type="LIGHT") + bpy.ops.object.delete() + + # Create environment light + if bpy.context.scene.world is None: + world = bpy.data.worlds.new("World") + bpy.context.scene.world = world + else: + world = bpy.context.scene.world + + # Enabling nodes + world.use_nodes = True + node_tree = world.node_tree + nodes = node_tree.nodes + links = node_tree.links + + # Remove default nodes + for node in nodes: + nodes.remove(node) + + # Create background node + bg_node = nodes.new(type="ShaderNodeBackground") + bg_node.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0) + bg_node.inputs["Strength"].default_value = 1.0 + output_node = nodes.new(type="ShaderNodeOutputWorld") + links.new(bg_node.outputs["Background"], output_node.inputs["Surface"]) + + +def init_random_lighting(camera_dir: np.ndarray) -> None: + # Clear existing lights + bpy.ops.object.select_all(action="DESELECT") + bpy.ops.object.select_by_type(type="LIGHT") + bpy.ops.object.delete() + + # Create environment light + if bpy.context.scene.world is None: + world = bpy.data.worlds.new("World") + bpy.context.scene.world = world + else: + world = bpy.context.scene.world + + # Enabling nodes + world.use_nodes = True + node_tree = world.node_tree + nodes = node_tree.nodes + links = node_tree.links + + # Remove default nodes + for node in nodes: + nodes.remove(node) + + # Random place lights + num_lights = np.random.randint(1, 4) + total_strength = 1.5 + for i in range(num_lights): + new_light = bpy.data.objects.new(f"Light_{i}", bpy.data.lights.new(f"Light_{i}", type="POINT")) + bpy.context.collection.objects.link(new_light) + + new_light_distance = 1 / np.random.uniform(1/100, 1/10) + new_light_dir = np.random.randn(3) + new_light_dir[2] += 0.6 + new_light_dir = new_light_dir / np.linalg.norm(new_light_dir) + new_light_location = new_light_dir * new_light_distance + new_light_camera_strength_ratio = max(np.sum(camera_dir * new_light_dir) * 0.5 + 0.5, 0) + new_light_max_energy = total_strength / (np.sum(camera_dir * new_light_dir) * 0.45 + 0.55) + new_light_strength = np.sqrt(np.random.uniform(0.01, 1)) * new_light_max_energy + new_light_camera_strength = new_light_camera_strength_ratio * new_light_strength + total_strength -= new_light_camera_strength + + new_light.location = (new_light_location[0], new_light_location[1], new_light_location[2]) + new_light.data.color = (1.0, 1.0, 1.0) + new_light.data.energy = new_light_strength * new_light_distance**2 * 31.4 + new_light.data.shadow_soft_size = np.random.uniform(0.1, 0.1 * new_light_distance) + + # Create background node + bg_node = nodes.new(type="ShaderNodeBackground") + bg_node.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0) + bg_node.inputs["Strength"].default_value = total_strength + output_node = nodes.new(type="ShaderNodeOutputWorld") + links.new(bg_node.outputs["Background"], output_node.inputs["Surface"]) + + +def load_object(object_path: str) -> None: + """Loads a model with a supported file extension into the scene. + + Args: + object_path (str): Path to the model file. + + Raises: + ValueError: If the file extension is not supported. + + Returns: + None + """ + file_extension = object_path.split(".")[-1].lower() + if file_extension is None: + raise ValueError(f"Unsupported file type: {object_path}") + + if file_extension == "usdz": + # install usdz io package + dirname = os.path.dirname(os.path.realpath(__file__)) + usdz_package = os.path.join(dirname, "io_scene_usdz.zip") + bpy.ops.preferences.addon_install(filepath=usdz_package) + # enable it + addon_name = "io_scene_usdz" + bpy.ops.preferences.addon_enable(module=addon_name) + # import the usdz + from io_scene_usdz.import_usdz import import_usdz + + import_usdz(context, filepath=object_path, materials=True, animations=True) + return None + + # load from existing import functions + import_function = IMPORT_FUNCTIONS[file_extension] + + print(f"Loading object from {object_path}") + if file_extension == "blend": + import_function(directory=object_path, link=False) + elif file_extension in {"glb", "gltf"}: + import_function(filepath=object_path, merge_vertices=True, import_shading='NORMALS') + else: + import_function(filepath=object_path) + + +def delete_invisible_objects() -> None: + """Deletes all invisible objects in the scene. + + Returns: + None + """ + # bpy.ops.object.mode_set(mode="OBJECT") + bpy.ops.object.select_all(action="DESELECT") + for obj in bpy.context.scene.objects: + if obj.hide_viewport or obj.hide_render: + obj.hide_viewport = False + obj.hide_render = False + obj.hide_select = False + obj.select_set(True) + bpy.ops.object.delete() + + # Delete invisible collections + invisible_collections = [col for col in bpy.data.collections if col.hide_viewport] + for col in invisible_collections: + bpy.data.collections.remove(col) + + +def unhide_all_objects() -> None: + """Unhides all objects in the scene. + + Returns: + None + """ + for obj in bpy.context.scene.objects: + obj.hide_set(False) + + +def convert_to_meshes() -> None: + """Converts all objects in the scene to meshes. + + Returns: + None + """ + bpy.ops.object.select_all(action="DESELECT") + bpy.context.view_layer.objects.active = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"][0] + for obj in bpy.context.scene.objects: + obj.select_set(True) + bpy.ops.object.convert(target="MESH") + + +def triangulate_meshes() -> None: + """Triangulates all meshes in the scene. + + Returns: + None + """ + bpy.ops.object.select_all(action="DESELECT") + objs = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"] + bpy.context.view_layer.objects.active = objs[0] + for obj in objs: + obj.select_set(True) + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.reveal() + bpy.ops.mesh.select_all(action="SELECT") + bpy.ops.mesh.quads_convert_to_tris(quad_method="BEAUTY", ngon_method="BEAUTY") + bpy.ops.object.mode_set(mode="OBJECT") + bpy.ops.object.select_all(action="DESELECT") + + +def scene_bbox() -> Tuple[Vector, Vector]: + """Returns the bounding box of the scene. + + Taken from Shap-E rendering script + (https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82) + + Returns: + Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box. + """ + bbox_min = (math.inf,) * 3 + bbox_max = (-math.inf,) * 3 + found = False + scene_meshes = [obj for obj in bpy.context.scene.objects.values() if isinstance(obj.data, bpy.types.Mesh)] + for obj in scene_meshes: + found = True + for coord in obj.bound_box: + coord = Vector(coord) + coord = obj.matrix_world @ coord + bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord)) + bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord)) + if not found: + raise RuntimeError("no objects in scene to compute bounding box for") + return Vector(bbox_min), Vector(bbox_max) + + +def normalize_scene() -> Tuple[float, Vector]: + """Normalizes the scene by scaling and translating it to fit in a unit cube centered + at the origin. + + Mostly taken from the Point-E / Shap-E rendering script + (https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112), + but fix for multiple root objects: (see bug report here: + https://github.com/openai/shap-e/pull/60). + + Returns: + Tuple[float, Vector]: The scale factor and the offset applied to the scene. + """ + scene_root_objects = [obj for obj in bpy.context.scene.objects.values() if not obj.parent] + if len(scene_root_objects) > 1: + # create an empty object to be used as a parent for all root objects + scene = bpy.data.objects.new("ParentEmpty", None) + bpy.context.scene.collection.objects.link(scene) + + # parent all root objects to the empty object + for obj in scene_root_objects: + obj.parent = scene + else: + scene = scene_root_objects[0] + + bbox_min, bbox_max = scene_bbox() + scale = 1 / max(bbox_max - bbox_min) + scene.scale = scene.scale * scale + + # Apply scale to matrix_world. + bpy.context.view_layer.update() + bbox_min, bbox_max = scene_bbox() + offset = -(bbox_min + bbox_max) / 2 + scene.matrix_world.translation += offset + bpy.ops.object.select_all(action="DESELECT") + + return scale, offset + + +def get_transform_matrix(obj: bpy.types.Object) -> list: + pos, rt, _ = obj.matrix_world.decompose() + rt = rt.to_matrix() + matrix = [] + for ii in range(3): + a = [] + for jj in range(3): + a.append(rt[ii][jj]) + a.append(pos[ii]) + matrix.append(a) + matrix.append([0, 0, 0, 1]) + return matrix + + +def main(arg): + if arg.object.endswith(".blend"): + delete_invisible_objects() + else: + init_scene() + load_object(arg.object) + print('[INFO] Scene initialized.') + + # normalize scene + scale, offset = normalize_scene() + print('[INFO] Scene normalized.') + + # Initialize camera and lighting + cam = init_camera() + init_uniform_lighting() + print('[INFO] Camera and lighting initialized.') + + # ============= Render conditional views ============= + init_render(engine=arg.engine, resolution=arg.cond_resolution) + # Create a list of views + to_export = { + "aabb": [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + "scale": scale, + "offset": [offset.x, offset.y, offset.z], + "frames": [] + } + views = json.loads(arg.cond_views) + for i, view in enumerate(views): + cam_dir = np.array([ + np.cos(view['yaw']) * np.cos(view['pitch']), + np.sin(view['yaw']) * np.cos(view['pitch']), + np.sin(view['pitch']) + ]) + init_random_lighting(cam_dir) + cam.location = ( + view['radius'] * cam_dir[0], + view['radius'] * cam_dir[1], + view['radius'] * cam_dir[2] + ) + cam.data.lens = 16 / np.tan(view['fov'] / 2) + + bpy.context.scene.render.filepath = os.path.join(arg.cond_output_folder, f'{i:03d}.png') + + # Render the scene + bpy.ops.render.render(write_still=True) + bpy.context.view_layer.update() + + # Save camera parameters + metadata = { + "file_path": f'{i:03d}.png', + "camera_angle_x": view['fov'], + "transform_matrix": get_transform_matrix(cam) + } + to_export["frames"].append(metadata) + + # Save the camera parameters + with open(os.path.join(arg.cond_output_folder, 'transforms.json'), 'w') as f: + json.dump(to_export, f, indent=4) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.') + parser.add_argument('--object', type=str, help='Path to the 3D model file to be rendered.') + parser.add_argument('--cond_views', type=str, help='JSON string of views. Contains a list of {yaw, pitch, radius, fov} object.') + parser.add_argument('--cond_output_folder', type=str, default='/tmp', help='The path the output will be dumped to.') + parser.add_argument('--cond_resolution', type=int, default=1024, help='Resolution of the conditional images.') + parser.add_argument('--engine', type=str, default='CYCLES', help='Blender internal engine for rendering. E.g. CYCLES, BLENDER_EEVEE, ...') + argv = sys.argv[sys.argv.index("--") + 1:] + args = parser.parse_args(argv) + + main(args) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/build_metadata.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/build_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..7ffee647385cf0b302a497d9fd602f059cb10cbb --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/build_metadata.py @@ -0,0 +1,219 @@ +import os +import shutil +import sys +import time +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict + + +def update_metadata(path, opt): + if not os.path.exists(path): + return None + timestamp = str(int(time.time())) + os.makedirs(os.path.join(path, 'merged_records'), exist_ok=True) + os.makedirs(os.path.join(path, 'new_records'), exist_ok=True) + if opt.from_merged_records: + df_files = [f for f in os.listdir(os.path.join(path, 'merged_records')) if f.endswith('.csv')] + df_files = [f for f in df_files if int(f.split('_')[0]) >= opt.record_start] + else: + df_files = [f for f in os.listdir(os.path.join(path, 'new_records')) if f.startswith('part_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(path, 'new_records', f))) + except Exception as e: + print(f"Failed to read {f}: {e}") + if len(df_parts) > 0: + if os.path.exists(os.path.join(path, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(path, 'metadata.csv')) + else: + columns = df_parts[0].columns + metadata = pd.DataFrame(columns=columns) + metadata.set_index('sha256', inplace=True) + for df_part in df_parts: + if 'sha256' in df_part.columns: + df_part.set_index('sha256', inplace=True) + metadata = df_part.combine_first(metadata) + metadata.to_csv(os.path.join(path, 'metadata.csv')) + for f in df_files: + shutil.move(os.path.join(path, 'new_records', f), os.path.join(path, 'merged_records', f'{timestamp}_{f}')) + return metadata + else: + if os.path.exists(os.path.join(path, 'metadata.csv')): + return pd.read_csv(os.path.join(path, 'metadata.csv')) + return None + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--download_root', type=str, default=None, + help='Directory to save the downloaded files') + parser.add_argument('--thumbnail_root', type=str, default=None, + help='Directory to save the thumbnail files') + parser.add_argument('--render_cond_root', type=str, default=None, + help='Directory to save the render condition files') + parser.add_argument('--mesh_dump_root', type=str, default=None, + help='Directory to save the mesh files') + parser.add_argument('--pbr_dump_root', type=str, default=None, + help='Directory to save the pbr files') + parser.add_argument('--dual_grid_root', type=str, default=None, + help='Directory to save the dual grid files') + parser.add_argument('--pbr_voxel_root', type=str, default=None, + help='Directory to save the pbr voxel files') + parser.add_argument('--ss_latent_root', type=str, default=None, + help='Directory to save the sparse structure latent files') + parser.add_argument('--shape_latent_root', type=str, default=None, + help='Directory to save the shape latent files') + parser.add_argument('--pbr_latent_root', type=str, default=None, + help='Directory to save the pbr latent files') + parser.add_argument('--field', type=str, default='all', + help='Fields to process, separated by commas') + parser.add_argument('--from_file', action='store_true', + help='Build metadata from file instead of from records of processings.' + + 'Useful when some processing fail to generate records but file already exists.') + parser.add_argument('--from_merged_records', action='store_true', + help='Build metadata from merged records') + parser.add_argument('--record_start', type=int) + parser.add_argument('--rebuild', action='store_true', + help='Rebuild metadata from scratch, ignore existing metadata.') + dataset_utils.add_args(parser) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.download_root = opt.download_root or opt.root + opt.thumbnail_root = opt.thumbnail_root or opt.root + opt.render_cond_root = opt.render_cond_root or opt.root + opt.mesh_dump_root = opt.mesh_dump_root or opt.root + opt.pbr_dump_root = opt.pbr_dump_root or opt.root + opt.dual_grid_root = opt.dual_grid_root or opt.root + opt.pbr_voxel_root = opt.pbr_voxel_root or opt.root + opt.ss_latent_root = opt.ss_latent_root or opt.root + opt.shape_latent_root = opt.shape_latent_root or opt.root + opt.pbr_latent_root = opt.pbr_latent_root or opt.root + + os.makedirs(opt.root, exist_ok=True) + + opt.field = opt.field.split(',') + + # get file list + if os.path.exists(os.path.join(opt.root, 'metadata.csv')): + print('Loading previous metadata...') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')) + else: + metadata = dataset_utils.get_metadata(**opt) + metadata.to_csv(os.path.join(opt.root, 'metadata.csv'), index=False) + + # merge downloaded + downloaded_metadata = update_metadata(os.path.join(opt.download_root, 'raw'), opt) + + # merge thumbnails + thumbnail_metadata = update_metadata(os.path.join(opt.thumbnail_root, 'thumbnails'), opt) + + # merge aesthetic scores + aesthetic_score_metadata = update_metadata(os.path.join(opt.root, 'aesthetic_scores'), opt) + + # merge render conditions + render_cond_metadata = update_metadata(os.path.join(opt.render_cond_root, 'renders_cond'), opt) + + # merge mesh dumped + mesh_dumped_metadata = update_metadata(os.path.join(opt.mesh_dump_root, 'mesh_dumps'), opt) + + # merge pbr dumped + pbr_dumped_metadata = update_metadata(os.path.join(opt.pbr_dump_root, 'pbr_dumps'), opt) + + # merge asset stats + asset_stats_metadata = update_metadata(os.path.join(opt.root, 'asset_stats'), opt) + + # merge dual grid + dual_grid_resolutions = [] + for dir in os.listdir(opt.dual_grid_root): + if os.path.isdir(os.path.join(opt.dual_grid_root, dir)) and dir.startswith('dual_grid_'): + dual_grid_resolutions.append(int(dir.split('_')[-1])) + dual_grid_metadata = {} + for res in dual_grid_resolutions: + dual_grid_metadata[res] = update_metadata(os.path.join(opt.dual_grid_root, f'dual_grid_{res}'), opt) + + # merge pbr voxelized + pbr_voxel_resolutions = [] + for dir in os.listdir(opt.pbr_voxel_root): + if os.path.isdir(os.path.join(opt.pbr_voxel_root, dir)) and dir.startswith('pbr_voxels_'): + pbr_voxel_resolutions.append(int(dir.split('_')[-1])) + pbr_voxel_metadata = {} + for res in pbr_voxel_resolutions: + pbr_voxel_metadata[res] = update_metadata(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{res}'), opt) + + # merge ss latents + ss_latent_models = [] + if os.path.exists(os.path.join(opt.ss_latent_root, 'ss_latents')): + ss_latent_models = os.listdir(os.path.join(opt.ss_latent_root, 'ss_latents')) + ss_latent_metadata = {} + for model in ss_latent_models: + ss_latent_metadata[model] = update_metadata(os.path.join(opt.ss_latent_root, f'ss_latents/{model}'), opt) + + # merge shape latents + shape_latent_models = [] + if os.path.exists(os.path.join(opt.shape_latent_root, 'shape_latents')): + shape_latent_models = os.listdir(os.path.join(opt.shape_latent_root, 'shape_latents')) + shape_latent_metadata = {} + for model in shape_latent_models: + shape_latent_metadata[model] = update_metadata(os.path.join(opt.shape_latent_root, f'shape_latents/{model}'), opt) + + # merge pbr latents + pbr_latent_models = [] + if os.path.exists(os.path.join(opt.pbr_latent_root, 'pbr_latents')): + pbr_latent_models = os.listdir(os.path.join(opt.pbr_latent_root, 'pbr_latents')) + pbr_latent_metadata = {} + for model in pbr_latent_models: + pbr_latent_metadata[model] = update_metadata(os.path.join(opt.pbr_latent_root, f'pbr_latents/{model}'), opt) + + # statistics + num_downloaded = downloaded_metadata['local_path'].count() if downloaded_metadata is not None else 0 + with open(os.path.join(opt.root, 'statistics.txt'), 'w') as f: + f.write('Statistics:\n') + f.write(f' - Number of assets: {len(metadata)}\n') + f.write(f' - Number of assets downloaded: {num_downloaded}\n') + if thumbnail_metadata is not None: + f.write(f' - Number of assets with thumbnails: {thumbnail_metadata["thumbnailed"].sum()}\n') + if aesthetic_score_metadata is not None: + f.write(f' - Number of assets with aesthetic scores: {aesthetic_score_metadata["aesthetic_score"].count()}\n') + if render_cond_metadata is not None: + f.write(f' - Number of assets with render conditions: {render_cond_metadata["cond_rendered"].count()}\n') + if mesh_dumped_metadata is not None: + f.write(f' - Number of assets with mesh dumped: {mesh_dumped_metadata["mesh_dumped"].sum()}\n') + if pbr_dumped_metadata is not None: + f.write(f' - Number of assets with PBR dumped: {pbr_dumped_metadata["pbr_dumped"].sum()}\n') + if asset_stats_metadata is not None: + f.write(f' - Number of assets with asset stats: {len(asset_stats_metadata)}\n') + if len(dual_grid_resolutions) != 0: + f.write(f' - Number of assets with dual grid:\n') + for res in dual_grid_resolutions: + if dual_grid_metadata[res] is not None: + f.write(f' - {res}: {dual_grid_metadata[res]["dual_grid_converted"].sum()}\n') + if len(pbr_voxel_resolutions) != 0: + f.write(f' - Number of assets with PBR voxelization:\n') + for res in pbr_voxel_resolutions: + if pbr_voxel_metadata[res] is not None: + f.write(f' - {res}: {pbr_voxel_metadata[res]["pbr_voxelized"].sum()}\n') + if len(ss_latent_models) != 0: + f.write(f' - Number of assets with sparse structure latents:\n') + for model in ss_latent_models: + if ss_latent_metadata[model] is not None: + f.write(f' - {model}: {ss_latent_metadata[model]["ss_latent_encoded"].sum()}\n') + if len(shape_latent_models) != 0: + f.write(f' - Number of assets with shape latents:\n') + for model in shape_latent_models: + if shape_latent_metadata[model] is not None: + f.write(f' - {model}: {shape_latent_metadata[model]["shape_latent_encoded"].sum()}\n') + if len(pbr_latent_models) != 0: + f.write(f' - Number of assets with PBR latents:\n') + for model in pbr_latent_models: + if pbr_latent_metadata[model] is not None: + f.write(f' - {model}: {pbr_latent_metadata[model]["pbr_latent_encoded"].sum()}\n') + + with open(os.path.join(opt.root, 'statistics.txt'), 'r') as f: + print(f.read()) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/download.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/download.py new file mode 100644 index 0000000000000000000000000000000000000000..32acd698f7f92ac133e4041b59ed7a21a06f9284 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/download.py @@ -0,0 +1,64 @@ +import os +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--download_root', type=str, default=None, + help='Directory to download the objects') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--check_only', action='store_true', + help='Only check if the objects are already downloaded') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.download_root = opt.download_root or opt.root + + os.makedirs(opt.root, exist_ok=True) + os.makedirs(opt.download_root, exist_ok=True) + os.makedirs(os.path.join(opt.download_root, 'raw', 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.download_root, 'raw', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.download_root, 'raw', 'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'local_path' in metadata.columns: + metadata = metadata[metadata['local_path'].isna()] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + + print(f'Processing {len(metadata)} objects...') + + # process objects + downloaded = dataset_utils.download(metadata, **opt) + downloaded.to_csv(os.path.join(opt.download_root, 'raw', 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dual_grid.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dual_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a3621a9ea93a24a4658daa0e2430ac922d9363 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dual_grid.py @@ -0,0 +1,170 @@ +import os +import sys +import importlib +import argparse +import pandas as pd +import numpy as np +import torch +import pickle +import o_voxel +from easydict import EasyDict as edict +from functools import partial + + +def _dual_grid_mesh(file, metadatum, mesh_dump_root, root): + sha256 = metadatum['sha256'] + try: + pack = {'sha256': sha256} + data = None + for res in opt.resolution: + need_process = False + + # check if already processed + if os.path.exists(os.path.join(root, f'dual_grid_{res}', f'{sha256}.vxz')): + try: + info = o_voxel.io.read_vxz_info(os.path.join(root, f'dual_grid_{res}', f'{sha256}.vxz')) + pack[f'dual_grid_converted_{res}'] = True + pack[f'dual_grid_size_{res}'] = info['num_voxel'] + except Exception as e: + print(f'Error reading {sha256}.vxz: {e}') + need_process = True + else: + need_process = True + + # process mesh + if need_process: + if data is None: + with open(os.path.join(mesh_dump_root, 'mesh_dumps', f'{sha256}.pickle'), 'rb') as f: + dump = pickle.load(f) + start = 0 + vertices = [] + faces = [] + for obj in dump['objects']: + if obj['vertices'].size == 0 or obj['faces'].size == 0: + continue + vertices.append(obj['vertices']) + faces.append(obj['faces'] + start) + start += len(obj['vertices']) + vertices = torch.from_numpy(np.concatenate(vertices, axis=0)).float() + faces = torch.from_numpy(np.concatenate(faces, axis=0)).long() + vertices_min = vertices.min(dim=0)[0] + vertices_max = vertices.max(dim=0)[0] + center = (vertices_min + vertices_max) / 2 + scale = 0.99999 / (vertices_max - vertices_min).max() + vertices = (vertices - center) * scale + assert torch.all(vertices >= -0.5) and torch.all(vertices <= 0.5), 'vertices out of range' + data = {'vertices': vertices, 'faces': faces} + + voxel_indices, dual_vertices, intersected = o_voxel.convert.mesh_to_flexible_dual_grid( + **data, + grid_size=res, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], + face_weight=1.0, + boundary_weight=0.2, + regularization_weight=1e-2, + timing=False, + ) + dual_vertices = dual_vertices * res - voxel_indices + assert torch.all(dual_vertices >= -1e-3) and torch.all(dual_vertices <= 1+1e-3), 'dual_vertices out of range' + dual_vertices = torch.clamp(dual_vertices, 0, 1) + dual_vertices = (dual_vertices * 255).type(torch.uint8) + intersected = (intersected[:, 0:1] + 2 * intersected[:, 1:2] + 4 * intersected[:, 2:3]).type(torch.uint8) + + o_voxel.io.write_vxz( + os.path.join(root, f'dual_grid_{res}', f'{sha256}.vxz'), + voxel_indices, + {'vertices': dual_vertices, 'intersected': intersected}, + ) + + pack[f'dual_grid_converted_{res}'] = True + pack[f'dual_grid_size_{res}'] = len(dual_vertices) + + return pack + except Exception as e: + print(f'Error processing {sha256}: {e}') + return {'sha256': sha256, 'error': str(e)} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--mesh_dump_root', type=str, default=None, + help='Directory to load mesh dumps') + parser.add_argument('--dual_grid_root', type=str, default=None, + help='Directory to save dual grids') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--resolution', type=str, default=256) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=0) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.resolution = [int(x) for x in opt.resolution.split(',')] + opt.mesh_dump_root = opt.mesh_dump_root or opt.root + opt.dual_grid_root = opt.dual_grid_root or opt.root + + for res in opt.resolution: + os.makedirs(os.path.join(opt.dual_grid_root, f'dual_grid_{res}', 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'metadata.csv')).set_index('sha256')) + for res in opt.resolution: + if os.path.exists(os.path.join(opt.dual_grid_root, f'dual_grid_{res}', 'metadata.csv')): + dual_grid_metadata = pd.read_csv(os.path.join(opt.dual_grid_root, f'dual_grid_{res}', 'metadata.csv')).set_index('sha256') + dual_grid_metadata = dual_grid_metadata.rename(columns={'dual_grid_converted': f'dual_grid_converted_{res}', 'dual_grid_size': f'dual_grid_size_{res}'}) + metadata = metadata.combine_first(dual_grid_metadata) + metadata = metadata.reset_index() + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['mesh_dumped'] == True] + mask = np.zeros(len(metadata), dtype=bool) + for res in opt.resolution: + if f'dual_grid_converted_{res}' in metadata.columns: + mask |= metadata[f'dual_grid_converted_{res}'] != True + else: + mask[:] = True + break + metadata = metadata[mask] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_dual_grid_mesh, root=opt.dual_grid_root, mesh_dump_root=opt.mesh_dump_root) + dual_grids = dataset_utils.foreach_instance(metadata, None, func, max_workers=opt.max_workers, no_file=True, desc='Dual griding') + if 'error' in dual_grids.columns: + errors = dual_grids[dual_grids[f'error'].notna()] + with open('errors.txt', 'w') as f: + f.write('\n'.join(errors['sha256'].tolist())) + for res in opt.resolution: + if f'dual_grid_converted_{res}' in dual_grids.columns: + dual_grid_metadata = dual_grids[dual_grids[f'dual_grid_converted_{res}'] == True] + if len(dual_grid_metadata) > 0: + dual_grid_metadata = dual_grid_metadata[['sha256', f'dual_grid_converted_{res}', f'dual_grid_size_{res}']] + dual_grid_metadata = dual_grid_metadata.rename(columns={f'dual_grid_converted_{res}': 'dual_grid_converted', f'dual_grid_size_{res}': 'dual_grid_size'}) + dual_grid_metadata.to_csv(os.path.join(opt.dual_grid_root, f'dual_grid_{res}', 'new_records', f'part_{opt.rank}.csv'), index=False) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dump_mesh.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dump_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..c3200bfe0b350efb42e03387afd08078f31ee460 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dump_mesh.py @@ -0,0 +1,127 @@ +import os +import shutil +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +from subprocess import DEVNULL, call +import numpy as np +import tempfile + + +BLENDER_LINK = 'https://ftp.halifax.rwth-aachen.de/blender/release/Blender4.5/blender-4.5.1-linux-x64.tar.xz' +BLENDER_INSTALLATION_PATH = '/tmp' +BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-4.5.1-linux-x64/blender' + +def _install_blender(): + if not os.path.exists(BLENDER_PATH): + os.system('sudo apt-get update') + os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6 libxfixes3 libgl1') + os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}') + os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-4.5.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}') + + +def _dump_mesh(file_path, metadatum, root): + sha256 = metadatum['sha256'] + with tempfile.TemporaryDirectory() as tmp_dir: + temp_path = os.path.join(tmp_dir, f'{sha256}.pickle') + output_path = os.path.join(root, 'mesh_dumps', f'{sha256}.pickle') + args = [ + BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'dump_mesh.py'), + '--', + '--object', os.path.expanduser(file_path), + '--output_path', os.path.expanduser(temp_path) + ] + if file_path.endswith('.blend'): + args.insert(1, file_path) + + call(args, stdout=DEVNULL, stderr=DEVNULL) + + if os.path.exists(temp_path): + shutil.move(temp_path, output_path) + return {'sha256': sha256, 'mesh_dumped': True} + else: + if os.path.exists(temp_path + '_error.txt'): + with open(temp_path + '_error.txt', 'r') as f: + error_msg = f.read() + raise ValueError(f'Failed to dump mesh. File {file_path}. Error message: {error_msg}') + else: + raise ValueError(f'Failed to dump mesh. File {file_path}.') + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--download_root', type=str, default=None, + help='Directory to save the downloaded files') + parser.add_argument('--mesh_dump_root', type=str, default=None, + help='Directory to save the mesh dumps') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=0) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.download_root = opt.download_root or opt.root + opt.mesh_dump_root = opt.mesh_dump_root or opt.root + + os.makedirs(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'new_records'), exist_ok=True) + + # install blender + print('Checking blender...', flush=True) + _install_blender() + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.download_root, 'raw', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.download_root, 'raw', 'metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + metadata = metadata[metadata['local_path'].notna()] + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'mesh_dumped' in metadata.columns: + metadata = metadata[metadata['mesh_dumped'] != True] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256_list = os.listdir(os.path.join(opt.mesh_dump_root, 'mesh_dumps')) + sha256_list = [os.path.splitext(f)[0] for f in sha256_list if f.endswith('.pickle')] + for sha256 in sha256_list: + records.append({'sha256': sha256, 'mesh_dumped': True}) + print(f'Found {len(sha256_list)} dumped mesh') + metadata = metadata[~metadata['sha256'].isin(sha256_list)] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_dump_mesh, root=opt.mesh_dump_root) + mesh_dumped = dataset_utils.foreach_instance(metadata, opt.download_root, func, max_workers=opt.max_workers, desc='Dumping mesh') + mesh_dumped = pd.concat([mesh_dumped, pd.DataFrame.from_records(records)]) + mesh_dumped.to_csv(os.path.join(opt.mesh_dump_root, 'mesh_dumps', 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dump_pbr.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dump_pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..aee6084e28b5a8d3e9391fc7e360046ca6163e5c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/dump_pbr.py @@ -0,0 +1,128 @@ +import os +import shutil +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +from subprocess import DEVNULL, call +import numpy as np +import tempfile + + +BLENDER_LINK = 'https://ftp.halifax.rwth-aachen.de/blender/release/Blender4.5/blender-4.5.1-linux-x64.tar.xz' +BLENDER_INSTALLATION_PATH = '/tmp' +BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-4.5.1-linux-x64/blender' + +def _install_blender(): + if not os.path.exists(BLENDER_PATH): + os.system('sudo apt-get update') + os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6 libxfixes3 libgl1') + os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}') + os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-4.5.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}') + os.system(f'{BLENDER_PATH} -b --python {os.path.join(os.path.dirname(__file__), "blender_script", "install_pillow.py")}') + + +def _dump_pbr(file_path, metadatum, root): + sha256 = metadatum['sha256'] + with tempfile.TemporaryDirectory() as tmp_dir: + temp_path = os.path.join(tmp_dir, f'{sha256}.pickle') + output_path = os.path.join(root, 'pbr_dumps', f'{sha256}.pickle') + args = [ + BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'dump_pbr.py'), + '--', + '--object', os.path.expanduser(file_path), + '--output_path', os.path.expanduser(temp_path) + ] + if file_path.endswith('.blend'): + args.insert(1, file_path) + + call(args, stdout=DEVNULL, stderr=DEVNULL) + + if os.path.exists(temp_path): + shutil.move(temp_path, output_path) + return {'sha256': sha256, 'pbr_dumped': True} + else: + if os.path.exists(temp_path + '_error.txt'): + with open(temp_path + '_error.txt', 'r') as f: + error_msg = f.read() + raise ValueError(f'Failed to dump PBR. File {file_path}. Error message: {error_msg}') + else: + raise ValueError(f'Failed to dump PBR. File {file_path}.') + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--download_root', type=str, default=None, + help='Directory to save the downloaded files') + parser.add_argument('--pbr_dump_root', type=str, default=None, + help='Directory to save the mesh dumps') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=0) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.download_root = opt.download_root or opt.root + opt.pbr_dump_root = opt.pbr_dump_root or opt.root + + os.makedirs(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'new_records'), exist_ok=True) + + # install blender + print('Checking blender...', flush=True) + _install_blender() + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.download_root, 'raw', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.download_root, 'raw', 'metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + metadata = metadata[metadata['local_path'].notna()] + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'pbr_dumped' in metadata.columns: + metadata = metadata[metadata['pbr_dumped'] != True] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256_list = os.listdir(os.path.join(opt.pbr_dump_root, 'pbr_dumps')) + sha256_list = [os.path.splitext(f)[0] for f in sha256_list if f.endswith('.pickle')] + for sha256 in sha256_list: + records.append({'sha256': sha256, 'pbr_dumped': True}) + print(f'Found {len(sha256_list)} dumped PBRs') + metadata = metadata[~metadata['sha256'].isin(sha256_list)] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_dump_pbr, root=opt.pbr_dump_root) + pbr_dumped = dataset_utils.foreach_instance(metadata, opt.download_root, func, max_workers=opt.max_workers, desc='Dumping PBR') + pbr_dumped = pd.concat([pbr_dumped, pd.DataFrame.from_records(records)]) + pbr_dumped.to_csv(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_pbr_latent.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_pbr_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..b2469f7c886376df59221595161795074ca96cc5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_pbr_latent.py @@ -0,0 +1,181 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import json +import argparse +import torch +import numpy as np +import pandas as pd +import o_voxel +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis2.models as models +import trellis2.modules.sparse as sp + +torch.set_grad_enabled(False) + +def is_valid_sparse_tensor(tensor): + return torch.isfinite(tensor.feats).all() and torch.isfinite(tensor.coords).all() + +def clear_cuda_error(): + torch.cuda.synchronize() + torch.cuda.empty_cache() + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--pbr_voxel_root', type=str, default=None, + help='Directory to save the pbr voxel files') + parser.add_argument('--pbr_latent_root', type=str, default=None, + help='Directory to save the pbr latent files') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--resolution', type=int, default=1024, + help='Sparse voxel resolution') + parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS.2-4B/ckpts/tex_enc_next_dc_f16c32_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, + help='Root directory of models') + parser.add_argument('--enc_model', type=str, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, + help='Checkpoint to load') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + opt.pbr_voxel_root = opt.pbr_voxel_root or opt.root + opt.pbr_latent_root = opt.pbr_latent_root or opt.root + + if opt.enc_model is None: + latent_name = f'{opt.enc_pretrained.split("/")[-1]}_{opt.resolution}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.enc_model.split("/")[-1]}_{opt.ckpt}_{opt.resolution}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name, 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{opt.resolution}', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{opt.resolution}','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name, 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name,'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['pbr_voxelized'] == True] + if 'pbr_latent_encoded' in metadata.columns: + metadata = metadata[metadata['pbr_latent_encoded'] != True] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Filtering existing objects") as pbar: + def check_sha256(sha256): + if os.path.exists(os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name, f'{sha256}.npz')): + coords = np.load(os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name, f'{sha256}.npz'))['coords'] + records.append({'sha256': sha256, 'pbr_latent_encoded': True, 'pbr_latent_tokens': coords.shape[0]}) + pbar.update() + executor.map(check_sha256, metadata['sha256'].values) + executor.shutdown(wait=True) + existing_sha256 = set(r['sha256'] for r in records) + print(f'Found {len(existing_sha256)} processed objects') + metadata = metadata[~metadata['sha256'].isin(existing_sha256)] + + print(f'Processing {len(metadata)} objects...') + + sha256s = list(metadata['sha256'].values) + load_queue = Queue(maxsize=32) + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + + def loader(sha256): + try: + attrs = ['base_color', 'metallic', 'roughness', 'alpha'] + coords, attr = o_voxel.io.read_vxz( + os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{opt.resolution}', f'{sha256}.vxz'), + num_threads=4 + ) + feats = torch.concat([attr[k] for k in attrs], dim=-1) / 255.0 * 2 - 1 + x = sp.SparseTensor( + feats.float(), + torch.cat([torch.zeros_like(coords[:, 0:1]), coords], dim=-1), + ) + load_queue.put((sha256, x)) + except Exception as e: + print(f"[Loader Error] {sha256}: {e}") + load_queue.put((sha256, None)) + + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, 'pbr_latent_encoded': True, 'pbr_latent_tokens': pack['coords'].shape[0]}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + try: + sha256, voxels = load_queue.get() + if voxels is None: + print(f"[Skip] {sha256}: Failed to load input") + continue + + num_voxels = voxels.feats.shape[0] + + # NaN/Inf + if not (is_valid_sparse_tensor(voxels)): + print(f"[Skip] {sha256}: NaN/Inf in input") + continue + + z = encoder(voxels.cuda()) + torch.cuda.synchronize() + + if not torch.isfinite(z.feats).all(): + print(f"[Skip] {sha256}: Non-finite latent in z.feats") + clear_cuda_error() + continue + + pack = { + 'feats': z.feats.cpu().numpy().astype(np.float32), + 'coords': z.coords[:, 1:].cpu().numpy().astype(np.uint8), + } + saver_executor.submit(saver, sha256, pack) + + except Exception as e: + print(f"[Error] {sha256} ({num_voxels} voxels): {e}") + clear_cuda_error() + continue + + saver_executor.shutdown(wait=True) + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.pbr_latent_root, 'pbr_latents', latent_name, 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_shape_latent.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_shape_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..7a39bb3c0a6db8c93ada8f3c850adcfa4c712555 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_shape_latent.py @@ -0,0 +1,184 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import json +import argparse +import torch +import numpy as np +import pandas as pd +import o_voxel +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis2.models as models +import trellis2.modules.sparse as sp + +torch.set_grad_enabled(False) + +def is_valid_sparse_tensor(tensor): + return torch.isfinite(tensor.feats).all() and torch.isfinite(tensor.coords).all() + +def clear_cuda_error(): + torch.cuda.synchronize() + torch.cuda.empty_cache() + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--dual_grid_root', type=str, default=None, + help='Directory to save the dual grids') + parser.add_argument('--shape_latent_root', type=str, default=None, + help='Directory to save the shape latent files') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--resolution', type=int, default=1024, + help='Sparse voxel resolution') + parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS.2-4B/ckpts/shape_enc_next_dc_f16c32_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, + help='Root directory of models') + parser.add_argument('--enc_model', type=str, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, + help='Checkpoint to load') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + opt.dual_grid_root = opt.dual_grid_root or opt.root + opt.shape_latent_root = opt.shape_latent_root or opt.root + + if opt.enc_model is None: + latent_name = f'{opt.enc_pretrained.split("/")[-1]}_{opt.resolution}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.enc_model.split("/")[-1]}_{opt.ckpt}_{opt.resolution}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.shape_latent_root, 'shape_latents', latent_name, 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.dual_grid_root, f'dual_grid_{opt.resolution}', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.dual_grid_root, f'dual_grid_{opt.resolution}','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.shape_latent_root, 'shape_latents', latent_name, 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.shape_latent_root, 'shape_latents', latent_name,'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['dual_grid_converted'] == True] + if 'shape_latent_encoded' in metadata.columns: + metadata = metadata[metadata['shape_latent_encoded'] != True] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Filtering existing objects") as pbar: + def check_sha256(sha256): + if os.path.exists(os.path.join(opt.shape_latent_root, 'shape_latents', latent_name, f'{sha256}.npz')): + coords = np.load(os.path.join(opt.shape_latent_root, 'shape_latents', latent_name, f'{sha256}.npz'))['coords'] + records.append({'sha256': sha256, 'shape_latent_encoded': True, 'shape_latent_tokens': coords.shape[0]}) + pbar.update() + executor.map(check_sha256, metadata['sha256'].values) + executor.shutdown(wait=True) + existing_sha256 = set(r['sha256'] for r in records) + print(f'Found {len(existing_sha256)} processed objects') + metadata = metadata[~metadata['sha256'].isin(existing_sha256)] + + print(f'Processing {len(metadata)} objects...') + + sha256s = list(metadata['sha256'].values) + load_queue = Queue(maxsize=32) + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + + def loader(sha256): + try: + coords, attr = o_voxel.io.read_vxz( + os.path.join(opt.dual_grid_root, f'dual_grid_{opt.resolution}', f'{sha256}.vxz'), + num_threads=4 + ) + vertices = sp.SparseTensor( + (attr['vertices'] / 255.0).float(), + torch.cat([torch.zeros_like(coords[:, 0:1]), coords], dim=-1), + ) + intersected = vertices.replace(torch.cat([ + attr['intersected'] % 2, + attr['intersected'] // 2 % 2, + attr['intersected'] // 4 % 2, + ], dim=-1).bool()) + load_queue.put((sha256, vertices, intersected)) + except Exception as e: + print(f"[Loader Error] {sha256}: {e}") + load_queue.put((sha256, None, None)) + + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.shape_latent_root, 'shape_latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, 'shape_latent_encoded': True, 'shape_latent_tokens': pack['coords'].shape[0]}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + try: + sha256, vertices, intersected = load_queue.get() + if vertices is None or intersected is None: + print(f"[Skip] {sha256}: Failed to load input") + continue + + num_voxels = vertices.feats.shape[0] + + # NaN/Inf + if not (is_valid_sparse_tensor(vertices) and is_valid_sparse_tensor(intersected)): + print(f"[Skip] {sha256}: NaN/Inf in input") + continue + + z = encoder(vertices.cuda(), intersected.cuda()) + torch.cuda.synchronize() + + if not torch.isfinite(z.feats).all(): + print(f"[Skip] {sha256}: Non-finite latent in z.feats") + clear_cuda_error() + continue + + pack = { + 'feats': z.feats.cpu().numpy().astype(np.float32), + 'coords': z.coords[:, 1:].cpu().numpy().astype(np.uint8), + } + saver_executor.submit(saver, sha256, pack) + + except Exception as e: + print(f"[Error] {sha256} ({num_voxels} voxels): {e}") + clear_cuda_error() + continue + + saver_executor.shutdown(wait=True) + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.shape_latent_root, 'shape_latents', latent_name, 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_ss_latent.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_ss_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..90f7fd96ff93bd6f16f29c5c4b0fe827644f03fe --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/encode_ss_latent.py @@ -0,0 +1,163 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import json +import argparse +import torch +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis2.models as models + +torch.set_grad_enabled(False) + +def is_valid_sparse_tensor(tensor): + return torch.isfinite(tensor.feats).all() and torch.isfinite(tensor.coords).all() + +def clear_cuda_error(): + torch.cuda.synchronize() + torch.cuda.empty_cache() + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--shape_latent_root', type=str, default=None, + help='Directory to save the shape latent files') + parser.add_argument('--ss_latent_root', type=str, default=None, + help='Directory to save the shape latent files') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--resolution', type=int, default=64, + help='Sparse voxel resolution') + parser.add_argument('--shape_latent_name', type=str, default=None, + help='Name of the shape latent files') + parser.add_argument('--enc_pretrained', type=str, default='microsoft/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, + help='Root directory of models') + parser.add_argument('--enc_model', type=str, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, + help='Checkpoint to load') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + opt.shape_latent_root = opt.shape_latent_root or opt.root + opt.ss_latent_root = opt.ss_latent_root or opt.root + + if opt.enc_model is None: + latent_name = f'{opt.enc_pretrained.split("/")[-1]}_{opt.resolution}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.enc_model.split("/")[-1]}_{opt.ckpt}_{opt.resolution}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.ss_latent_root, 'ss_latents', latent_name, 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.shape_latent_root, 'shape_latents', opt.shape_latent_name, 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.shape_latent_root, 'shape_latents', opt.shape_latent_name,'metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.ss_latent_root,'ss_latents', latent_name, 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.ss_latent_root,'ss_latents', latent_name,'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['shape_latent_encoded'] == True] + if 'ss_latent_encoded' in metadata.columns: + metadata = metadata[metadata['ss_latent_encoded'] != True] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256_list = os.listdir(os.path.join(opt.ss_latent_root, 'ss_latents')) + sha256_list = [os.path.splitext(f)[0] for f in sha256_list if f.endswith('.npz')] + for sha256 in sha256_list: + records.append({'sha256': sha256, 'ss_latent_encoded': True}) + print(f'Found {len(sha256_list)} processed objects') + metadata = metadata[~metadata['sha256'].isin(sha256_list)] + + print(f'Processing {len(metadata)} objects...') + + sha256s = list(metadata['sha256'].values) + load_queue = Queue(maxsize=32) + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + + def loader(sha256): + try: + coords = np.load(os.path.join(opt.shape_latent_root, 'shape_latents', opt.shape_latent_name, f'{sha256}.npz'))['coords'] + assert np.all(coords < opt.resolution), f"{sha256}: Invalid coords" + coords = torch.from_numpy(coords).long() + ss = torch.zeros(1, opt.resolution, opt.resolution, opt.resolution, dtype=torch.long) + ss[:, coords[:, 0], coords[:, 1], coords[:, 2]] = 1 + load_queue.put((sha256, ss)) + except Exception as e: + print(f"[Loader Error] {sha256}: {e}") + load_queue.put((sha256, None)) + + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.ss_latent_root, 'ss_latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, 'ss_latent_encoded': True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + try: + sha256, ss = load_queue.get() + if ss is None: + print(f"[Skip] {sha256}: Failed to load input") + continue + + ss = ss.cuda()[None].float() + z = encoder(ss, sample_posterior=False) + torch.cuda.synchronize() + + if not torch.isfinite(z).all(): + print(f"[Skip] {sha256}: Non-finite latent") + clear_cuda_error() + continue + + pack = { + 'z': z[0].cpu().numpy(), + } + saver_executor.submit(saver, sha256, pack) + + except Exception as e: + print(f"[Error] {sha256}: {e}") + clear_cuda_error() + continue + + saver_executor.shutdown(wait=True) + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.ss_latent_root, 'ss_latents', latent_name, 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/render_cond.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/render_cond.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a0dc2b4c8b4f777668578f62b38cb4fe340ecf --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/render_cond.py @@ -0,0 +1,146 @@ +import os +import json +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +from subprocess import DEVNULL, call +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import numpy as np +from utils import sphere_hammersley_sequence + + +BLENDER_LINK = 'https://download.blender.org/release/Blender3.0/blender-3.0.1-linux-x64.tar.xz' +BLENDER_INSTALLATION_PATH = '/tmp' +BLENDER_PATH = f'{BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64/blender' + +def _install_blender(): + if not os.path.exists(BLENDER_PATH): + os.system('sudo apt-get update') + os.system('sudo apt-get install -y libxrender1 libxi6 libxkbcommon-x11-0 libsm6 libxfixes3 libgl1') + os.system(f'wget {BLENDER_LINK} -P {BLENDER_INSTALLATION_PATH}') + os.system(f'tar -xvf {BLENDER_INSTALLATION_PATH}/blender-3.0.1-linux-x64.tar.xz -C {BLENDER_INSTALLATION_PATH}') + + +def _render_cond(file_path, metadatum, root, num_cond_views): + sha256 = metadatum['sha256'] + # Build conditional view camera + yaws = [] + pitchs = [] + offset = (np.random.rand(), np.random.rand()) + for i in range(num_cond_views): + y, p = sphere_hammersley_sequence(i, num_cond_views, offset) + yaws.append(y) + pitchs.append(p) + fov_min, fov_max = 10, 70 + radius_min = np.sqrt(3) / 2 / np.sin(fov_max / 360 * np.pi) + radius_max = np.sqrt(3) / 2 / np.sin(fov_min / 360 * np.pi) + k_min = 1 / radius_max**2 + k_max = 1 / radius_min**2 + ks = np.random.uniform(k_min, k_max, (1000000,)) + radius = [1 / np.sqrt(k) for k in ks] + fov = [2 * np.arcsin(np.sqrt(3) / 2 / r) for r in radius] + cond_views = [{'yaw': y, 'pitch': p, 'radius': r, 'fov': f} for y, p, r, f in zip(yaws, pitchs, radius, fov)] + + args = [ + BLENDER_PATH, '-b', '-P', os.path.join(os.path.dirname(__file__), 'blender_script', 'render_cond.py'), + '--', + '--object', os.path.expanduser(file_path), + '--cond_views', json.dumps(cond_views), + '--cond_resolution', '1024', + '--cond_output_folder', os.path.join(root, 'renders_cond', sha256), + '--engine', 'CYCLES', + ] + if file_path.endswith('.blend'): + args.insert(1, file_path) + + call(args, stdout=DEVNULL, stderr=DEVNULL) + + if os.path.exists(os.path.join(root, 'renders_cond', sha256, 'transforms.json')): + return {'sha256': sha256, 'cond_rendered': True} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--download_root', type=str, default=None, + help='Directory to save the downloaded files') + parser.add_argument('--render_cond_root', type=str, default=None, + help='Directory to save the mesh dumps') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--num_cond_views', type=int, default=16, + help='Number of conditional views to render') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=8) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.download_root = opt.download_root or opt.root + opt.render_cond_root = opt.render_cond_root or opt.root + + os.makedirs(os.path.join(opt.render_cond_root, 'renders_cond', 'new_records'), exist_ok=True) + + # install blender + print('Checking blender...', flush=True) + _install_blender() + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.download_root, 'raw', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.download_root, 'raw', 'metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.render_cond_root, 'renders_cond', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.render_cond_root, 'renders_cond', 'metadata.csv')).set_index('sha256')) + metadata = metadata.reset_index() + if opt.instances is None: + metadata = metadata[metadata['local_path'].notna()] + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'cond_rendered' in metadata.columns: + metadata = metadata[(metadata['cond_rendered'] != True)] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Filtering existing objects") as pbar: + def check_sha256(sha256): + if os.path.exists(os.path.join(opt.render_cond_root, 'renders_cond', sha256, 'transforms.json')): + records.append({'sha256': sha256, 'cond_rendered': True}) + pbar.update() + executor.map(check_sha256, metadata['sha256'].values) + executor.shutdown(wait=True) + existing_sha256 = set(r['sha256'] for r in records) + metadata = metadata[~metadata['sha256'].isin(existing_sha256)] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_render_cond, root=opt.render_cond_root, num_cond_views=opt.num_cond_views) + cond_rendered = dataset_utils.foreach_instance(metadata, opt.render_cond_root, func, max_workers=opt.max_workers, desc='Rendering objects') + cond_rendered = pd.concat([cond_rendered, pd.DataFrame.from_records(records)]) + cond_rendered.to_csv(os.path.join(opt.render_cond_root, 'renders_cond', 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/setup.sh b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..3cb14278024d2d6df62448028e086d2bb910efaa --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/setup.sh @@ -0,0 +1 @@ +pip install pillow imageio imageio-ffmpeg tqdm easydict opencv-python-headless pandas open3d objaverse huggingface_hub[cli] open_clip_torch diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee3f3e0661aaa0e03562f22a928b34e3958e848 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/utils.py @@ -0,0 +1,440 @@ +from typing import * +import hashlib +import numpy as np +import cv2 + + +def get_file_hash(file: str) -> str: + sha256 = hashlib.sha256() + # Read the file from the path + with open(file, "rb") as f: + # Update the hash with the file content + for byte_block in iter(lambda: f.read(4096), b""): + sha256.update(byte_block) + return sha256.hexdigest() + +# ===============LOW DISCREPANCY SEQUENCES================ + +PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] + +def radical_inverse(base, n): + val = 0 + inv_base = 1.0 / base + inv_base_n = inv_base + while n > 0: + digit = n % base + val += digit * inv_base_n + n //= base + inv_base_n *= inv_base + return val + +def halton_sequence(dim, n): + return [radical_inverse(PRIMES[dim], n) for dim in range(dim)] + +def hammersley_sequence(dim, n, num_samples): + return [n / num_samples] + halton_sequence(dim - 1, n) + +def sphere_hammersley_sequence(n, num_samples, offset=(0, 0)): + u, v = hammersley_sequence(2, n, num_samples) + u += offset[0] / num_samples + v += offset[1] + u = 2 * u if u < 0.25 else 2 / 3 * u + 1 / 3 + theta = np.arccos(1 - 2 * u) - np.pi / 2 + phi = v * 2 * np.pi + return [phi, theta] + +# ==============PLY IO=============== +import struct +import re +import torch + +def read_ply(filename): + """ + Read a PLY file and return vertices, triangle faces, and quad faces. + + Args: + filename (str): The file path to read from. + + Returns: + vertices (torch.Tensor): Tensor of shape [N, 3] containing vertex positions. + tris (torch.Tensor): Tensor of shape [M, 3] containing triangle face indices (empty if none). + quads (torch.Tensor): Tensor of shape [K, 4] containing quad face indices (empty if none). + """ + with open(filename, 'rb') as f: + # Read the header until 'end_header' is encountered + header_bytes = b"" + while True: + line = f.readline() + if not line: + raise ValueError("PLY header not found") + header_bytes += line + if b"end_header" in line: + break + header = header_bytes.decode('utf-8') + + # Determine if the file is in ASCII or binary format + is_ascii = "ascii" in header + + # Extract the number of vertices and faces from the header using regex + vertex_match = re.search(r'element vertex (\d+)', header) + if vertex_match: + num_vertices = int(vertex_match.group(1)) + else: + raise ValueError("Vertex count not found in header") + + face_match = re.search(r'element face (\d+)', header) + if face_match: + num_faces = int(face_match.group(1)) + else: + raise ValueError("Face count not found in header") + + vertices = [] + tris = [] + quads = [] + + if is_ascii: + # For ASCII format, read each line of vertex data (each line contains 3 floats) + for _ in range(num_vertices): + line = f.readline().decode('utf-8').strip() + if not line: + continue + parts = line.split() + vertices.append([float(parts[0]), float(parts[1]), float(parts[2])]) + + # Read face data, where the first number indicates the number of vertices for the face + for _ in range(num_faces): + line = f.readline().decode('utf-8').strip() + if not line: + continue + parts = line.split() + count = int(parts[0]) + indices = list(map(int, parts[1:])) + if count == 3: + tris.append(indices) + elif count == 4: + quads.append(indices) + else: + # Skip faces with other numbers of vertices (can be extended as needed) + pass + else: + # For binary format: read directly from the binary stream + # Each vertex consists of 3 floats (12 bytes per vertex) + for _ in range(num_vertices): + data = f.read(12) + if len(data) < 12: + raise ValueError("Insufficient vertex data") + v = struct.unpack(' 0 else torch.empty((0, 3), dtype=torch.int32) + quads = torch.tensor(quads, dtype=torch.int32) if len(quads) > 0 else torch.empty((0, 4), dtype=torch.int32) + + return vertices, tris, quads + + +def write_ply(filename, vertices, tris, quads, ascii=False): + """ + Write a mesh to a PLY file, with the option to save in ASCII or binary format. + + Args: + filename (str): The filename to write to. + vertices (torch.Tensor): [N, 3] The vertex positions. + tris (torch.Tensor): [M, 3] The triangle indices. + quads (torch.Tensor): [K, 4] The quad indices. + ascii (bool): If True, write in ASCII format. If False, write in binary format. + """ + # Convert torch tensors to numpy arrays + vertices = vertices.numpy() + tris = tris.numpy() + quads = quads.numpy() + + # Prepare the header + num_vertices = len(vertices) + num_faces = len(tris) + len(quads) + + # Vertex properties + vertex_header = "property float x\nproperty float y\nproperty float z" + + # Face properties (the number of vertices per face is variable) + face_header = "property list uchar int vertex_index" + + # Start writing the PLY header + header = f"ply\n" + header += f"format {'ascii 1.0' if ascii else 'binary_little_endian 1.0'}\n" + header += f"element vertex {num_vertices}\n" + header += vertex_header + "\n" + header += f"element face {num_faces}\n" + header += face_header + "\n" + header += "end_header\n" + + # Open the file for writing + with open(filename, 'wb' if not ascii else 'w') as f: + # Write the header + f.write(header if ascii else header.encode('utf-8')) + + # Write the vertex data + if ascii: + for v in vertices: + f.write(f"{v[0]} {v[1]} {v[2]}\n") + else: + for v in vertices: + f.write(struct.pack('= num_images, 'nrow * ncol must be greater than or equal to the number of images' + + if images[0].ndim == 2: + grid = np.zeros((nrow * images[0].shape[0], ncol * images[0].shape[1]), dtype=images[0].dtype) + else: + grid = np.zeros((nrow * images[0].shape[0], ncol * images[0].shape[1], images[0].shape[2]), dtype=images[0].dtype) + for i, img in enumerate(images): + row = i // ncol + col = i % ncol + grid[row * img.shape[0]:(row + 1) * img.shape[0], col * img.shape[1]:(col + 1) * img.shape[1]] = img + return grid + + +def notes_on_image(img, notes=None): + img = np.pad(img, ((0, 32), (0, 0), (0, 0)), 'constant', constant_values=0) + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + if notes is not None: + img = cv2.putText(img, notes, (0, img.shape[0] - 4), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + return img + + + +def text_image(text, resolution=(512, 512), max_size=0.5, h_align="left", v_align="center"): + """ + Draw text on an image of the given resolution. The text is automatically wrapped + and scaled so that it fits completely within the image while preserving any explicit + line breaks and original spacing. Horizontal and vertical alignment can be controlled + via flags. + + Parameters: + text (str): The input text. Newline characters and spacing are preserved. + resolution (tuple): The image resolution as (width, height). + max_size (float): The maximum font size. + h_align (str): Horizontal alignment. Options: "left", "center", "right". + v_align (str): Vertical alignment. Options: "top", "center", "bottom". + + Returns: + numpy.ndarray: The resulting image (BGR format) with the text drawn. + """ + width, height = resolution + # Create a white background image + img = np.full((height, width, 3), 255, dtype=np.uint8) + + # Set margins and compute available drawing area + margin = 10 + avail_width = width - 2 * margin + avail_height = height - 2 * margin + + # Choose OpenCV font and text thickness + font = cv2.FONT_HERSHEY_SIMPLEX + thickness = 1 + # Ratio for additional spacing between lines (relative to the height of "A") + line_spacing_ratio = 0.5 + + def wrap_line(line, max_width, font, thickness, scale): + """ + Wrap a single line of text into multiple lines such that each line's + width (measured at the given scale) does not exceed max_width. + This function preserves the original spacing by splitting the line into tokens + (words and whitespace) using a regular expression. + + Parameters: + line (str): The input text line. + max_width (int): Maximum allowed width in pixels. + font (int): OpenCV font identifier. + thickness (int): Text thickness. + scale (float): The current font scale. + + Returns: + List[str]: A list of wrapped lines. + """ + # Split the line into tokens (words and whitespace), preserving spacing + tokens = re.split(r'(\s+)', line) + if not tokens: + return [''] + + wrapped_lines = [] + current_line = "" + for token in tokens: + candidate = current_line + token + candidate_width = cv2.getTextSize(candidate, font, scale, thickness)[0][0] + if candidate_width <= max_width: + current_line = candidate + else: + # If current_line is empty, the token itself is too wide; + # break the token character by character. + if current_line == "": + sub_token = "" + for char in token: + candidate_char = sub_token + char + if cv2.getTextSize(candidate_char, font, scale, thickness)[0][0] <= max_width: + sub_token = candidate_char + else: + if sub_token: + wrapped_lines.append(sub_token) + sub_token = char + current_line = sub_token + else: + wrapped_lines.append(current_line) + current_line = token + if current_line: + wrapped_lines.append(current_line) + return wrapped_lines + + def compute_text_block(scale): + """ + Wrap the entire text (splitting at explicit newline characters) using the + provided scale, and then compute the overall width and height of the text block. + + Returns: + wrapped_lines (List[str]): The list of wrapped lines. + block_width (int): Maximum width among the wrapped lines. + block_height (int): Total height of the text block including spacing. + sizes (List[tuple]): A list of (width, height) for each wrapped line. + spacing (int): The spacing between lines (computed from the scaled "A" height). + """ + # Split text by explicit newlines + input_lines = text.splitlines() if text else [''] + wrapped_lines = [] + for line in input_lines: + wrapped = wrap_line(line, avail_width, font, thickness, scale) + wrapped_lines.extend(wrapped) + + sizes = [] + for line in wrapped_lines: + (text_size, _) = cv2.getTextSize(line, font, scale, thickness) + sizes.append(text_size) # (width, height) + + block_width = max((w for w, h in sizes), default=0) + # Use the height of "A" (at the current scale) to compute line spacing + base_height = cv2.getTextSize("A", font, scale, thickness)[0][1] + spacing = int(line_spacing_ratio * base_height) + block_height = sum(h for w, h in sizes) + spacing * (len(sizes) - 1) if sizes else 0 + + return wrapped_lines, block_width, block_height, sizes, spacing + + # Use binary search to find the maximum scale that allows the text block to fit + lo = 0.001 + hi = max_size + eps = 0.001 # convergence threshold + best_scale = lo + best_result = None + + while hi - lo > eps: + mid = (lo + hi) / 2 + wrapped_lines, block_width, block_height, sizes, spacing = compute_text_block(mid) + # Ensure that both width and height constraints are met + if block_width <= avail_width and block_height <= avail_height: + best_scale = mid + best_result = (wrapped_lines, block_width, block_height, sizes, spacing) + lo = mid # try a larger scale + else: + hi = mid # reduce the scale + + if best_result is None: + best_scale = 0.5 + best_result = compute_text_block(best_scale) + + wrapped_lines, block_width, block_height, sizes, spacing = best_result + + # Compute starting y-coordinate based on vertical alignment flag + if v_align == "top": + y_top = margin + elif v_align == "center": + y_top = margin + (avail_height - block_height) // 2 + elif v_align == "bottom": + y_top = margin + (avail_height - block_height) + else: + y_top = margin + (avail_height - block_height) // 2 # default to center if invalid flag + + # For cv2.putText, the y coordinate represents the text baseline; + # so for the first line add its height. + y = y_top + (sizes[0][1] if sizes else 0) + + # Draw each line with horizontal alignment based on the flag + for i, line in enumerate(wrapped_lines): + line_width, line_height = sizes[i] + if h_align == "left": + x = margin + elif h_align == "center": + x = margin + (avail_width - line_width) // 2 + elif h_align == "right": + x = margin + (avail_width - line_width) + else: + x = margin # default to left if invalid flag + + cv2.putText(img, line, (x, y), font, best_scale, (0, 0, 0), thickness, cv2.LINE_AA) + y += line_height + spacing + + return img + + +def save_image_with_notes(img, path, notes=None): + """ + Save an image with notes. + """ + if isinstance(img, torch.Tensor): + img = img.cpu().numpy().transpose(1, 2, 0) + if img.dtype == np.float32 or img.dtype == np.float64: + img = np.clip(img * 255, 0, 255).astype(np.uint8) + img = notes_on_image(img, notes) + cv2.imwrite(path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/voxelize_pbr.py b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/voxelize_pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..23b75e269a6074d5bdab10e5a404995b4dc01742 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/data_toolkit/voxelize_pbr.py @@ -0,0 +1,167 @@ +import os +import copy +import sys +import importlib +import argparse +import pandas as pd +import pickle +import numpy as np +import torch +from easydict import EasyDict as edict +from functools import partial +import o_voxel + + +def _pbr_voxelize(file, metadatum, pbr_dump_root, root): + sha256 = metadatum['sha256'] + try: + pack = {'sha256': sha256} + dump = None + for res in opt.resolution: + need_process = False + + # check if already processed + if os.path.exists(os.path.join(root, f'pbr_voxels_{res}', f'{sha256}.vxz')): + try: + info = o_voxel.io.read_vxz_info(os.path.join(root, f'pbr_voxels_{res}', f'{sha256}.vxz')) + pack[f'pbr_voxelized_{res}'] = True + pack[f'num_pbr_voxels_{res}'] = info['num_voxel'] + except Exception as e: + print(f'Error reading {sha256}.vxz: {e}') + need_process = True + else: + need_process = True + + # process if necessary + if need_process: + if dump == None: + with open(os.path.join(pbr_dump_root, 'pbr_dumps', f'{sha256}.pickle'), 'rb') as f: + dump = pickle.load(f) + # Fix dump alpha map + for mat in dump['materials']: + if mat['alphaTexture'] is not None and mat['alphaMode'] == 'OPAQUE': + mat['alphaMode'] = 'BLEND' + dump['materials'].append({ + "baseColorFactor": [0.8, 0.8, 0.8], + "alphaFactor": 1.0, + "metallicFactor": 0.0, + "roughnessFactor": 0.5, + "alphaMode": "OPAQUE", + "alphaCutoff": 0.5, + "baseColorTexture": None, + "alphaTexture": None, + "metallicTexture": None, + "roughnessTexture": None, + }) # append default material + dump['objects'] = [ + obj for obj in dump['objects'] + if obj['vertices'].size != 0 and obj['faces'].size != 0 + ] + vertices = torch.from_numpy(np.concatenate([obj['vertices'] for obj in dump['objects']], axis=0)).float() + vertices_min = vertices.min(dim=0)[0] + vertices_max = vertices.max(dim=0)[0] + center = (vertices_min + vertices_max) / 2 + scale = 0.99999 / (vertices_max - vertices_min).max() + for obj in dump['objects']: + obj['vertices'] = (torch.from_numpy(obj['vertices']).float() - center) * scale + obj['vertices'] = obj['vertices'].numpy() + obj['mat_ids'][obj['mat_ids'] == -1] = len(dump['materials']) - 1 + assert np.all(obj['mat_ids'] >= 0), 'invalid mat_ids' + assert np.all(obj['vertices'] >= -0.5) and np.all(obj['vertices'] <= 0.5), 'vertices out of range' + + coord, attr = o_voxel.convert.blender_dump_to_volumetric_attr(dump, grid_size=res, aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + mip_level_offset=0, verbose=False, timing=False) + del attr['normal'] + del attr['emissive'] + o_voxel.io.write_vxz(os.path.join(root, f'pbr_voxels_{res}', f'{sha256}.vxz'), coord, attr) + pack[f'pbr_voxelized_{res}'] = True + pack[f'num_pbr_voxels_{res}'] = len(coord) + + return pack + except Exception as e: + print(f'Error voxelizing {sha256}: {e}') + return {'sha256': sha256, 'error': str(e)} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--root', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--pbr_dump_root', type=str, default=None, + help='Directory to load mesh dumps') + parser.add_argument('--pbr_voxel_root', type=str, default=None, + help='Directory to save voxelized pbr attributes') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--resolution', type=str, default=1024) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=0) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + opt.resolution = sorted([int(x) for x in opt.resolution.split(',')], reverse=True) + opt.pbr_dump_root = opt.pbr_dump_root or opt.root + opt.pbr_voxel_root = opt.pbr_voxel_root or opt.root + + for res in opt.resolution: + os.makedirs(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{res}', 'new_records'), exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.root, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.root, 'metadata.csv')).set_index('sha256') + if os.path.exists(os.path.join(opt.root, 'aesthetic_scores', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.root, 'aesthetic_scores','metadata.csv')).set_index('sha256')) + if os.path.exists(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'metadata.csv')): + metadata = metadata.combine_first(pd.read_csv(os.path.join(opt.pbr_dump_root, 'pbr_dumps', 'metadata.csv')).set_index('sha256')) + for res in opt.resolution: + if os.path.exists(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{res}', 'metadata.csv')): + pbr_voxel_metadata = pd.read_csv(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{res}','metadata.csv')).set_index('sha256') + pbr_voxel_metadata = pbr_voxel_metadata.rename(columns={'pbr_voxelized': f'pbr_voxelized_{res}', 'num_pbr_voxels': f'num_pbr_voxels_{res}'}) + metadata = metadata.combine_first(pbr_voxel_metadata) + metadata = metadata.reset_index() + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['pbr_dumped'] == True] + mask = np.zeros(len(metadata), dtype=bool) + for res in opt.resolution: + if f'pbr_voxelized_{res}' in metadata.columns: + mask |= metadata[f'pbr_voxelized_{res}'] != True + else: + mask[:] = True + break + metadata = metadata[mask] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_pbr_voxelize, pbr_dump_root=opt.pbr_dump_root, root=opt.pbr_voxel_root) + pbr_voxelized = dataset_utils.foreach_instance(metadata, None, func, max_workers=opt.max_workers, no_file=True, desc='Voxelizing') + if 'error' in pbr_voxelized.columns: + errors = pbr_voxelized[pbr_voxelized['error'].notna()] + with open('errors.txt', 'w') as f: + f.write('\n'.join(errors['sha256'].tolist())) + for res in opt.resolution: + if f'pbr_voxelized_{res}' in pbr_voxelized.columns: + pbr_voxel_metadata = pbr_voxelized[pbr_voxelized[f'pbr_voxelized_{res}'] == True] + if len(pbr_voxel_metadata) > 0: + pbr_voxel_metadata = pbr_voxel_metadata[['sha256', f'pbr_voxelized_{res}', f'num_pbr_voxels_{res}']] + pbr_voxel_metadata = pbr_voxel_metadata.rename(columns={f'pbr_voxelized_{res}': 'pbr_voxelized', f'num_pbr_voxels_{res}': 'num_pbr_voxels'}) + pbr_voxel_metadata.to_csv(os.path.join(opt.pbr_voxel_root, f'pbr_voxels_{res}', 'new_records', f'part_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/example.py b/OVOW/engine/oneposeviagen/TRELLIS2/example.py new file mode 100644 index 0000000000000000000000000000000000000000..475a3b17eef04ab527385f2c8df922dc302fd84e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/example.py @@ -0,0 +1,48 @@ +import os +os.environ['OPENCV_IO_ENABLE_OPENEXR'] = '1' +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" # Can save GPU memory +import cv2 +import imageio +from PIL import Image +import torch +from trellis2.pipelines import Trellis2ImageTo3DPipeline +from trellis2.utils import render_utils +from trellis2.renderers import EnvMap +import o_voxel + +# 1. Setup Environment Map +envmap = EnvMap(torch.tensor( + cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB), + dtype=torch.float32, device='cuda' +)) + +# 2. Load Pipeline +pipeline = Trellis2ImageTo3DPipeline.from_pretrained("microsoft/TRELLIS.2-4B") +pipeline.cuda() + +# 3. Load Image & Run +image = Image.open("assets/example_image/T.png") +mesh = pipeline.run(image)[0] +mesh.simplify(16777216) # nvdiffrast limit + +# 4. Render Video +video = render_utils.make_pbr_vis_frames(render_utils.render_video(mesh, envmap=envmap)) +imageio.mimsave("sample.mp4", video, fps=15) + +# 5. Export to GLB +glb = o_voxel.postprocess.to_glb( + vertices = mesh.vertices, + faces = mesh.faces, + attr_volume = mesh.attrs, + coords = mesh.coords, + attr_layout = mesh.layout, + voxel_size = mesh.voxel_size, + aabb = [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + decimation_target = 1000000, + texture_size = 4096, + remesh = True, + remesh_band = 1, + remesh_project = 0, + verbose = True +) +glb.export("sample.glb", extension_webp=True) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/example_texturing.py b/OVOW/engine/oneposeviagen/TRELLIS2/example_texturing.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb5ffcde46103d6c940f45b18dd396fa2a920f0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/example_texturing.py @@ -0,0 +1,17 @@ +import os +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" # Can save GPU memory +import trimesh +from PIL import Image +from trellis2.pipelines import Trellis2TexturingPipeline + +# 1. Load Pipeline +pipeline = Trellis2TexturingPipeline.from_pretrained("microsoft/TRELLIS.2-4B", config_file="texturing_pipeline.json") +pipeline.cuda() + +# 2. Load Mesh, image & Run +mesh = trimesh.load("assets/example_texturing/the_forgotten_knight.ply") +image = Image.open("assets/example_texturing/image.webp") +output = pipeline.run(mesh, image) + +# 3. Render Mesh +output.export("textured.glb", extension_webp=True) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/README.md b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0dba0bf9e3ff5ac02a9c780338fce1a0d05ecb1b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/README.md @@ -0,0 +1,174 @@ +# O-Voxel: A Native 3D Representation + +**O-Voxel** is a sparse, voxel-based native 3D representation designed for high-quality 3D generation and reconstruction. Unlike traditional methods that rely on fields (e.g., Occupancy fields, SDFs), O-Voxel utilizes a **Flexible Dual Grid** formulation to robustly represent surfaces with arbitrary topology (including non-manifold and open surfaces) and **volumetric surface properties** such as Physically-Based Rendering (PBR) material attributes. + +This library provides an efficient implementation for the instant bidirectional conversion between Meshes and O-Voxels, along with tools for sparse voxel compression, serialization, and rendering. + +![Overview](assets/overview.webp) + +## Key Features + +- **🧱 Flexible Dual Grid**: A geometry representation that solves a enhanced QEF (Quadratic Error Function) to accurately capture sharp features and open boundaries without requiring watertight meshes. +- **🎨 Volumetric PBR Attributes**: Native support for physically-based rendering properties (Base Color, Metallic, Roughness, Opacity) aligned with the sparse voxel grid. +- **⚡ Instant Bidirectional Conversion**: Rapid `Mesh <-> O-Voxel` conversion without expensive SDF evaluation, flood-filling, or iterative optimization. +- **💾 Efficient Compression**: Supports custom `.vxz` format for compact storage of sparse voxel structures using Z-order/Hilbert curve encoding. +- **🛠️ Production Ready**: Tools to export converted assets directly to `.glb` with UV unwrapping and texture baking. + +## Installation + +```bash +git clone -b main https://github.com/microsoft/TRELLIS.2.git --recursive +pip install TRELLIS.2/o_voxel --no-build-isolation +``` + +## Quick Start + +> See also the [examples](examples) directory for more detailed usage. + +### 1. Convert Mesh to O-Voxel [[link]](examples/mesh2ovox.py) +Convert a standard 3D mesh (with textures) into the O-Voxel representation. + +```python +asset = trimesh.load("path/to/mesh.glb") + +# 1. Geometry Voxelization (Flexible Dual Grid) +# Returns: occupied indices, dual vertices (QEF solution), and edge intersected +mesh = asset.to_mesh() +vertices = torch.from_numpy(mesh.vertices).float() +faces = torch.from_numpy(mesh.faces).long() +voxel_indices, dual_vertices, intersected = o_voxel.convert.mesh_to_flexible_dual_grid( + vertices, faces, + grid_size=RES, # Resolution + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], # Axis-aligned bounding box + face_weight=1.0, # Face term weight in QEF + boundary_weight=0.2, # Boundary term weight in QEF + regularization_weight=1e-2, # Regularization term weight in QEF + timing=True +) +## sort to ensure align between geometry and material voxelization +vid = o_voxel.serialize.encode_seq(voxel_indices) +mapping = torch.argsort(vid) +voxel_indices = voxel_indices[mapping] +dual_vertices = dual_vertices[mapping] +intersected = intersected[mapping] + +# 2. Material Voxelization (Volumetric Attributes) +# Returns: dict containing 'base_color', 'metallic', 'roughness', etc. +voxel_indices_mat, attributes = o_voxel.convert.textured_mesh_to_volumetric_attr( + asset, + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], + timing=True +) +## sort to ensure align between geometry and material voxelization +vid_mat = o_voxel.serialize.encode_seq(voxel_indices_mat) +mapping_mat = torch.argsort(vid_mat) +attributes = {k: v[mapping_mat] for k, v in attributes.items()} + +# Save to compressed .vxz format +## packing +dual_vertices = dual_vertices * RES - voxel_indices +dual_vertices = (torch.clamp(dual_vertices, 0, 1) * 255).type(torch.uint8) +intersected = (intersected[:, 0:1] + 2 * intersected[:, 1:2] + 4 * intersected[:, 2:3]).type(torch.uint8) +attributes['dual_vertices'] = dual_vertices +attributes['intersected'] = intersected +o_voxel.io.write("ovoxel_helmet.vxz", voxel_indices, attributes) +``` + +### 2. Recover Mesh from O-Voxel [[link]](examples/ovox2mesh.py) +Reconstruct the surface mesh from the sparse voxel data. + +```python +# Load data +coords, data = o_voxel.io.read("path/to/ovoxel.vxz") +dual_vertices = data['dual_vertices'] +intersected = data['intersected'] +base_color = data['base_color'] +## ... other attributes omitted for brevity + +# Depack +dual_vertices = dual_vertices / 255 +intersected = torch.cat([ + intersected % 2, + intersected // 2 % 2, + intersected // 4 % 2, +], dim=-1).bool() + +# Extract Mesh +# O-Voxel connects dual vertices to form quads, optionally splitting them +# based on geometric features. +rec_verts, rec_faces = o_voxel.convert.flexible_dual_grid_to_mesh( + coords.cuda(), + dual_vertices.cuda(), + intersected.cuda(), + split_weight=None, # Auto-split based on min angle if None + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], +) +``` + +### 3. Export to GLB [[link]](examples/ovox2glb.py) +For visualization in standard 3D viewers, you can clean, UV-unwrap, and bake the volumetric attributes into textures. + +```python +# Assuming you have the reconstructed verts/faces and volume attributes +mesh = o_voxel.postprocess.to_glb( + vertices=rec_verts, + faces=rec_faces, + attr_volume=attr_tensor, # Concatenated attributes + coords=coords, + attr_layout={'base_color': slice(0,3), 'metallic': slice(3,4), ...}, + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], + decimation_target=100000, + texture_size=2048, + verbose=True, +) +mesh.export("rec_helmet.glb") +``` + +### 4. Voxel Rendering [[link]](examples/render_ovox.py) +Render the voxel representation directly. + +```python +# Load data +coords, data = o_voxel.io.read("ovoxel_helmet.vxz") +position = (coords / RES - 0.5).cuda() +base_color = (data['base_color'] / 255).cuda() + +# Render +renderer = o_voxel.rasterize.VoxelRenderer( + rendering_options={"resolution": 512, "ssaa": 2} +) +output = renderer.render( + position=position, # Voxel centers + attrs=base_color, # Color/Opacity etc. + voxel_size=1.0/RES, + extrinsics=extr, + intrinsics=intr +) +# output.attr contains the rendered image (C, H, W) +``` + +## API Overview + +### `o_voxel.convert` +Core algorithms for the conversion between meshes and O-Voxels. +* `mesh_to_flexible_dual_grid`: Determines the active sparse voxels and solves the QEF to determine dual vertex positions within voxels based on mesh-voxel grid intersections. +* `flexible_dual_grid_to_mesh`: Reconnects dual vertices to form a surface. +* `textured_mesh_to_volumetric_attr`: Samples texture maps into voxel space. + +### `o_voxel.io` +Handles sparse voxel file I/O operations. +* **Formats**: `.npz` (NumPy), `.ply` (Point Cloud), `.vxz` (Custom compressed, recommended). +* **Functions**: `read()`, `write()`. + +### `o_voxel.serialize` +Utilities for spatial hashing and ordering. +* `encode_seq` / `decode_seq`: Converts 3D coordinates to/from Morton codes (Z-order) or Hilbert curves for efficient storage and processing. + +### `o_voxel.rasterize` +* `VoxelRenderer`: A lightweight renderer for sparse voxel visualization during training. + +### `o_voxel.postprocess` +* `to_glb`: A comprehensive pipeline for mesh cleaning, remeshing, UV unwrapping, and texture baking. diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/assets/overview.webp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/assets/overview.webp new file mode 100644 index 0000000000000000000000000000000000000000..5317e1364e4f0d497369cca7d00d4698bc339903 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/assets/overview.webp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba51a74520803e36ec5be8e1aab1c71fea8a8df78a0502f0736e338ff4e97f93 +size 391770 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/mesh2ovox.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/mesh2ovox.py new file mode 100644 index 0000000000000000000000000000000000000000..54d0c9b9d94941bd3d6854002264d636f64a1338 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/mesh2ovox.py @@ -0,0 +1,57 @@ +import torch +import o_voxel +import utils + +RES = 512 + +asset = utils.get_helmet() + +# 0. Normalize asset to unit cube +aabb = asset.bounding_box.bounds +center = (aabb[0] + aabb[1]) / 2 +scale = 0.99999 / (aabb[1] - aabb[0]).max() # To avoid numerical issues +asset.apply_translation(-center) +asset.apply_scale(scale) + +# 1. Geometry Voxelization (Flexible Dual Grid) +# Returns: occupied indices, dual vertices (QEF solution), and edge intersected +mesh = asset.to_mesh() +vertices = torch.from_numpy(mesh.vertices).float() +faces = torch.from_numpy(mesh.faces).long() +voxel_indices, dual_vertices, intersected = o_voxel.convert.mesh_to_flexible_dual_grid( + vertices, faces, + grid_size=RES, # Resolution + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], # Axis-aligned bounding box + face_weight=1.0, # Face term weight in QEF + boundary_weight=0.2, # Boundary term weight in QEF + regularization_weight=1e-2, # Regularization term weight in QEF + timing=True +) +## sort to ensure align between geometry and material voxelization +vid = o_voxel.serialize.encode_seq(voxel_indices) +mapping = torch.argsort(vid) +voxel_indices = voxel_indices[mapping] +dual_vertices = dual_vertices[mapping] +intersected = intersected[mapping] + +# 2. Material Voxelization (Volumetric Attributes) +# Returns: dict containing 'base_color', 'metallic', 'roughness', etc. +voxel_indices_mat, attributes = o_voxel.convert.textured_mesh_to_volumetric_attr( + asset, + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], + timing=True +) +## sort to ensure align between geometry and material voxelization +vid_mat = o_voxel.serialize.encode_seq(voxel_indices_mat) +mapping_mat = torch.argsort(vid_mat) +attributes = {k: v[mapping_mat] for k, v in attributes.items()} + +# Save to compressed .vxz format +## packing +dual_vertices = dual_vertices * RES - voxel_indices +dual_vertices = (torch.clamp(dual_vertices, 0, 1) * 255).type(torch.uint8) +intersected = (intersected[:, 0:1] + 2 * intersected[:, 1:2] + 4 * intersected[:, 2:3]).type(torch.uint8) +attributes['dual_vertices'] = dual_vertices +attributes['intersected'] = intersected +o_voxel.io.write("ovoxel_helmet.vxz", voxel_indices, attributes) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/ovox2glb.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/ovox2glb.py new file mode 100644 index 0000000000000000000000000000000000000000..230631084997d686e9c66468d3314e8c142571a3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/ovox2glb.py @@ -0,0 +1,52 @@ +import torch +import o_voxel + +RES = 512 + +# Load data +coords, data = o_voxel.io.read("ovoxel_helmet.vxz") +dual_vertices = data['dual_vertices'] +intersected = data['intersected'] +base_color = data['base_color'] +metallic = data['metallic'] +roughness = data['roughness'] +alpha = data['alpha'] + +# Depack +dual_vertices = dual_vertices / 255 +intersected = torch.cat([ + intersected % 2, + intersected // 2 % 2, + intersected // 4 % 2, +], dim=-1).bool() + +# Extract Mesh +# O-Voxel connects dual vertices to form quads, optionally splitting them +# based on geometric features. +rec_verts, rec_faces = o_voxel.convert.flexible_dual_grid_to_mesh( + coords.cuda(), + dual_vertices.cuda(), + intersected.cuda(), + split_weight=None, # Auto-split based on min angle if None + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], +) + +# Post-process +attr_volume = torch.cat([base_color.cuda(), metallic.cuda(), roughness.cuda(), alpha.cuda()], dim=-1) / 255 +attr_layout = {'base_color': slice(0,3), 'metallic': slice(3,4), 'roughness': slice(4,5), 'alpha': slice(5,6)} +mesh = o_voxel.postprocess.to_glb( + vertices=rec_verts, + faces=rec_faces, + attr_volume=attr_volume, + coords=coords.cuda(), + attr_layout=attr_layout, + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], + decimation_target=100000, + texture_size=2048, + verbose=True, +) + +# Save as glb +mesh.export("rec_helmet.glb") diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/ovox2mesh.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/ovox2mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5a6be5a91c6af9b8152051a1badcbd7fb73074 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/ovox2mesh.py @@ -0,0 +1,45 @@ +import torch +import o_voxel +import trimesh +import trimesh.visual + +RES = 512 + +# Load data +coords, data = o_voxel.io.read("ovoxel_helmet.vxz") +dual_vertices = data['dual_vertices'] +intersected = data['intersected'] +base_color = data['base_color'] +metallic = data['metallic'] +roughness = data['roughness'] +alpha = data['alpha'] + +# Depack +dual_vertices = dual_vertices / 255 +intersected = torch.cat([ + intersected % 2, + intersected // 2 % 2, + intersected // 4 % 2, +], dim=-1).bool() + +# Extract Mesh +# O-Voxel connects dual vertices to form quads, optionally splitting them +# based on geometric features. +rec_verts, rec_faces = o_voxel.convert.flexible_dual_grid_to_mesh( + coords.cuda(), + dual_vertices.cuda(), + intersected.cuda(), + split_weight=None, # Auto-split based on min angle if None + grid_size=RES, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], +) + +# Save as ply +visual = trimesh.visual.ColorVisuals( + vertex_colors=base_color, +) +mesh = trimesh.Trimesh( + vertices=rec_verts.cpu(), faces=rec_faces.cpu(), visual=visual, + process=False +) +mesh.export("rec_helmet.ply") diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/render_ovox.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/render_ovox.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a27c09c7fda6183dca42099e78b375f29f2515 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/render_ovox.py @@ -0,0 +1,39 @@ +import torch +import numpy as np +import imageio +import o_voxel +import utils3d + +RES = 512 + +# Load data +coords, data = o_voxel.io.read("ovoxel_helmet.vxz") +position = (coords / RES - 0.5).cuda() +base_color = (data['base_color'] / 255).cuda() + +# Setup camera +extr = utils3d.extrinsics_look_at( + eye=torch.tensor([1.2, 0.5, 1.2]), + look_at=torch.tensor([0.0, 0.0, 0.0]), + up=torch.tensor([0.0, 1.0, 0.0]) +).cuda() +intr = utils3d.intrinsics_from_fov_xy( + fov_x=torch.deg2rad(torch.tensor(45.0)), + fov_y=torch.deg2rad(torch.tensor(45.0)), +).cuda() + +# Render +renderer = o_voxel.rasterize.VoxelRenderer( + rendering_options={"resolution": 512, "ssaa": 2} +) +output = renderer.render( + position=position, # Voxel centers + attrs=base_color, # Color/Opacity etc. + voxel_size=1.0/RES, + extrinsics=extr, + intrinsics=intr +) +image = np.clip( + output.attr.permute(1, 2, 0).cpu().numpy() * 255, 0, 255 +).astype(np.uint8) +imageio.imwrite("ovoxel_helmet_visualization.png", image) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a8a6a26271d6fd37d53b039d5e8bedb8548280 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/examples/utils.py @@ -0,0 +1,27 @@ +import os +import requests +import tarfile +import trimesh + +HELMET_URL = "https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/refs/heads/main/2.0/DamagedHelmet/glTF-Binary/DamagedHelmet.glb" +CACHE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "cache") + + +def download_file(url, path): + print(f"Downloading from {url} ...") + resp = requests.get(url, stream=True) + resp.raise_for_status() + + with open(path, "wb") as f: + for chunk in resp.iter_content(chunk_size=8192): + f.write(chunk) + + print(f"Saved to {path}") + + +def get_helmet() -> trimesh.Trimesh: + HELMET_PATH = os.path.join(CACHE_DIR, "helmet.glb") + if not os.path.exists(HELMET_PATH): + os.makedirs(CACHE_DIR, exist_ok=True) + download_file(HELMET_URL, HELMET_PATH) + return trimesh.load(HELMET_PATH) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/_C.cpython-311-x86_64-linux-gnu.so b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/_C.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..65c5e6cffdc01c2828c635da8d8c217cb1ea767d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/_C.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7a8b5a0fdd4bd08dbb3fba7db54bedeff854ea100e6d68d4f1046e1bdcb375c +size 716112 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..263b753ebc61659e08715a9c329c1449a28769f9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/__init__.py @@ -0,0 +1,7 @@ +from . import ( + convert, + io, + postprocess, + rasterize, + serialize +) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7b6d8c01e90897af20dbe751527f1854e81ecc1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/__init__.py @@ -0,0 +1,2 @@ +from .flexible_dual_grid import * +from .volumetic_attr import * \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/flexible_dual_grid.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/flexible_dual_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf1397e58e42b9d66b2230f5b3d55fee708514d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/flexible_dual_grid.py @@ -0,0 +1,283 @@ +from typing import * +import numpy as np +import torch +from .. import _C + +__all__ = [ + "mesh_to_flexible_dual_grid", + "flexible_dual_grid_to_mesh", +] + + +def _init_hashmap(grid_size, capacity, device): + VOL = (grid_size[0] * grid_size[1] * grid_size[2]).item() + + # If the number of elements in the tensor is less than 2^32, use uint32 as the hashmap type, otherwise use uint64. + if VOL < 2**32: + hashmap_keys = torch.full((capacity,), torch.iinfo(torch.uint32).max, dtype=torch.uint32, device=device) + elif VOL < 2**64: + hashmap_keys = torch.full((capacity,), torch.iinfo(torch.uint64).max, dtype=torch.uint64, device=device) + else: + raise ValueError(f"The spatial size is too large to fit in a hashmap. Get volumn {VOL} > 2^64.") + + hashmap_vals = torch.empty((capacity,), dtype=torch.uint32, device=device) + + return hashmap_keys, hashmap_vals + + +@torch.no_grad() +def mesh_to_flexible_dual_grid( + vertices: torch.Tensor, + faces: torch.Tensor, + voxel_size: Union[float, list, tuple, np.ndarray, torch.Tensor] = None, + grid_size: Union[int, list, tuple, np.ndarray, torch.Tensor] = None, + aabb: Union[list, tuple, np.ndarray, torch.Tensor] = None, + face_weight: float = 1.0, + boundary_weight: float = 1.0, + regularization_weight: float = 0.1, + timing: bool = False, +) -> Union[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Voxelize a mesh into a sparse voxel grid. + + Args: + vertices (torch.Tensor): The vertices of the mesh. + faces (torch.Tensor): The faces of the mesh. + voxel_size (float, list, tuple, np.ndarray, torch.Tensor): The size of each voxel. + grid_size (int, list, tuple, np.ndarray, torch.Tensor): The size of the grid. + NOTE: One of voxel_size and grid_size must be provided. + aabb (list, tuple, np.ndarray, torch.Tensor): The axis-aligned bounding box of the mesh. + If not provided, it will be computed automatically. + face_weight (float): The weight of the face term in the QEF when solving the dual vertices. + boundary_weight (float): The weight of the boundary term in the QEF when solving the dual vertices. + regularization_weight (float): The weight of the regularization term in the QEF when solving the dual vertices. + timing (bool): Whether to time the voxelization process. + + Returns: + torch.Tensor: The indices of the voxels that are occupied by the mesh. + The shape of the tensor is (N, 3), where N is the number of occupied voxels. + torch.Tensor: The dual vertices of the mesh. + torch.Tensor: The intersected flag of each voxel. + """ + + # Load mesh + vertices = vertices.float() + faces = faces.int() + + # Voxelize settings + assert voxel_size is not None or grid_size is not None, "Either voxel_size or grid_size must be provided" + + if voxel_size is not None: + if isinstance(voxel_size, float): + voxel_size = [voxel_size, voxel_size, voxel_size] + if isinstance(voxel_size, (list, tuple)): + voxel_size = np.array(voxel_size) + if isinstance(voxel_size, np.ndarray): + voxel_size = torch.tensor(voxel_size, dtype=torch.float32) + assert isinstance(voxel_size, torch.Tensor), f"voxel_size must be a float, list, tuple, np.ndarray, or torch.Tensor, but got {type(voxel_size)}" + assert voxel_size.dim() == 1, f"voxel_size must be a 1D tensor, but got {voxel_size.shape}" + assert voxel_size.size(0) == 3, f"voxel_size must have 3 elements, but got {voxel_size.size(0)}" + + if grid_size is not None: + if isinstance(grid_size, int): + grid_size = [grid_size, grid_size, grid_size] + if isinstance(grid_size, (list, tuple)): + grid_size = np.array(grid_size) + if isinstance(grid_size, np.ndarray): + grid_size = torch.tensor(grid_size, dtype=torch.int32) + assert isinstance(grid_size, torch.Tensor), f"grid_size must be an int, list, tuple, np.ndarray, or torch.Tensor, but got {type(grid_size)}" + assert grid_size.dim() == 1, f"grid_size must be a 1D tensor, but got {grid_size.shape}" + assert grid_size.size(0) == 3, f"grid_size must have 3 elements, but got {grid_size.size(0)}" + + if aabb is not None: + if isinstance(aabb, (list, tuple)): + aabb = np.array(aabb) + if isinstance(aabb, np.ndarray): + aabb = torch.tensor(aabb, dtype=torch.float32) + assert isinstance(aabb, torch.Tensor), f"aabb must be a list, tuple, np.ndarray, or torch.Tensor, but got {type(aabb)}" + assert aabb.dim() == 2, f"aabb must be a 2D tensor, but got {aabb.shape}" + assert aabb.size(0) == 2, f"aabb must have 2 rows, but got {aabb.size(0)}" + assert aabb.size(1) == 3, f"aabb must have 3 columns, but got {aabb.size(1)}" + + # Auto adjust aabb + if aabb is None: + min_xyz = vertices.min(dim=0).values + max_xyz = vertices.max(dim=0).values + + if voxel_size is not None: + padding = torch.ceil((max_xyz - min_xyz) / voxel_size) * voxel_size - (max_xyz - min_xyz) + min_xyz -= padding * 0.5 + max_xyz += padding * 0.5 + if grid_size is not None: + padding = (max_xyz - min_xyz) / (grid_size - 1) + min_xyz -= padding * 0.5 + max_xyz += padding * 0.5 + + aabb = torch.stack([min_xyz, max_xyz], dim=0).float().cuda() + + # Fill voxel size or grid size + if voxel_size is None: + voxel_size = (aabb[1] - aabb[0]) / grid_size + if grid_size is None: + grid_size = ((aabb[1] - aabb[0]) / voxel_size).round().int() + + # subdivide mesh + vertices = vertices - aabb[0].reshape(1, 3) + grid_range = torch.stack([torch.zeros_like(grid_size), grid_size], dim=0).int() + + ret = _C.mesh_to_flexible_dual_grid_cpu( + vertices, + faces, + voxel_size, + grid_range, + face_weight, + boundary_weight, + regularization_weight, + timing, + ) + + return ret + + +def flexible_dual_grid_to_mesh( + coords: torch.Tensor, + dual_vertices: torch.Tensor, + intersected_flag: torch.Tensor, + split_weight: Union[torch.Tensor, None], + aabb: Union[list, tuple, np.ndarray, torch.Tensor], + voxel_size: Union[float, list, tuple, np.ndarray, torch.Tensor] = None, + grid_size: Union[int, list, tuple, np.ndarray, torch.Tensor] = None, + train: bool = False, +): + """ + Extract mesh from sparse voxel structures using flexible dual grid. + + Args: + coords (torch.Tensor): The coordinates of the voxels. + dual_vertices (torch.Tensor): The dual vertices. + intersected_flag (torch.Tensor): The intersected flag. + split_weight (torch.Tensor): The split weight of each dual quad. If None, the algorithm + will split based on minimum angle. + aabb (list, tuple, np.ndarray, torch.Tensor): The axis-aligned bounding box of the mesh. + voxel_size (float, list, tuple, np.ndarray, torch.Tensor): The size of each voxel. + grid_size (int, list, tuple, np.ndarray, torch.Tensor): The size of the grid. + NOTE: One of voxel_size and grid_size must be provided. + train (bool): Whether to use training mode. + + Returns: + vertices (torch.Tensor): The vertices of the mesh. + faces (torch.Tensor): The faces of the mesh. + """ + # Static variables + if not hasattr(flexible_dual_grid_to_mesh, "edge_neighbor_voxel_offset"): + flexible_dual_grid_to_mesh.edge_neighbor_voxel_offset = torch.tensor([ + [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]], # x-axis + [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]], # y-axis + [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], # z-axis + ], dtype=torch.int, device=coords.device).unsqueeze(0) + if not hasattr(flexible_dual_grid_to_mesh, "quad_split_1"): + flexible_dual_grid_to_mesh.quad_split_1 = torch.tensor([0, 1, 2, 0, 2, 3], dtype=torch.long, device=coords.device, requires_grad=False) + if not hasattr(flexible_dual_grid_to_mesh, "quad_split_2"): + flexible_dual_grid_to_mesh.quad_split_2 = torch.tensor([0, 1, 3, 3, 1, 2], dtype=torch.long, device=coords.device, requires_grad=False) + if not hasattr(flexible_dual_grid_to_mesh, "quad_split_train"): + flexible_dual_grid_to_mesh.quad_split_train = torch.tensor([0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4], dtype=torch.long, device=coords.device, requires_grad=False) + + # AABB + if isinstance(aabb, (list, tuple)): + aabb = np.array(aabb) + if isinstance(aabb, np.ndarray): + aabb = torch.tensor(aabb, dtype=torch.float32, device=coords.device) + assert isinstance(aabb, torch.Tensor), f"aabb must be a list, tuple, np.ndarray, or torch.Tensor, but got {type(aabb)}" + assert aabb.dim() == 2, f"aabb must be a 2D tensor, but got {aabb.shape}" + assert aabb.size(0) == 2, f"aabb must have 2 rows, but got {aabb.size(0)}" + assert aabb.size(1) == 3, f"aabb must have 3 columns, but got {aabb.size(1)}" + + # Voxel size + if voxel_size is not None: + if isinstance(voxel_size, float): + voxel_size = [voxel_size, voxel_size, voxel_size] + if isinstance(voxel_size, (list, tuple)): + voxel_size = np.array(voxel_size) + if isinstance(voxel_size, np.ndarray): + voxel_size = torch.tensor(voxel_size, dtype=torch.float32, device=coords.device) + grid_size = ((aabb[1] - aabb[0]) / voxel_size).round().int() + else: + assert grid_size is not None, "Either voxel_size or grid_size must be provided" + if isinstance(grid_size, int): + grid_size = [grid_size, grid_size, grid_size] + if isinstance(grid_size, (list, tuple)): + grid_size = np.array(grid_size) + if isinstance(grid_size, np.ndarray): + grid_size = torch.tensor(grid_size, dtype=torch.int32, device=coords.device) + voxel_size = (aabb[1] - aabb[0]) / grid_size + assert isinstance(voxel_size, torch.Tensor), f"voxel_size must be a float, list, tuple, np.ndarray, or torch.Tensor, but got {type(voxel_size)}" + assert voxel_size.dim() == 1, f"voxel_size must be a 1D tensor, but got {voxel_size.shape}" + assert voxel_size.size(0) == 3, f"voxel_size must have 3 elements, but got {voxel_size.size(0)}" + assert isinstance(grid_size, torch.Tensor), f"grid_size must be an int, list, tuple, np.ndarray, or torch.Tensor, but got {type(grid_size)}" + assert grid_size.dim() == 1, f"grid_size must be a 1D tensor, but got {grid_size.shape}" + assert grid_size.size(0) == 3, f"grid_size must have 3 elements, but got {grid_size.size(0)}" + + # Extract mesh + N = dual_vertices.shape[0] + mesh_vertices = (coords.float() + dual_vertices) / (2 * N) - 0.5 + + # Store active voxels into hashmap + hashmap = _init_hashmap(grid_size, 2 * N, device=coords.device) + _C.hashmap_insert_3d_idx_as_val_cuda(*hashmap, torch.cat([torch.zeros_like(coords[:, :1]), coords], dim=-1), *grid_size.tolist()) + + # Find connected voxels + edge_neighbor_voxel = coords.reshape(N, 1, 1, 3) + flexible_dual_grid_to_mesh.edge_neighbor_voxel_offset # (N, 3, 4, 3) + connected_voxel = edge_neighbor_voxel[intersected_flag] # (M, 4, 3) + M = connected_voxel.shape[0] + connected_voxel_hash_key = torch.cat([ + torch.zeros((M * 4, 1), dtype=torch.int, device=coords.device), + connected_voxel.reshape(-1, 3) + ], dim=1) + connected_voxel_indices = _C.hashmap_lookup_3d_cuda(*hashmap, connected_voxel_hash_key, *grid_size.tolist()).reshape(M, 4).int() + connected_voxel_valid = (connected_voxel_indices != 0xffffffff).all(dim=1) + quad_indices = connected_voxel_indices[connected_voxel_valid].int() # (L, 4) + L = quad_indices.shape[0] + + # Construct triangles + if not train: + mesh_vertices = (coords.float() + dual_vertices) * voxel_size + aabb[0].reshape(1, 3) + if split_weight is None: + # if split 1 + atempt_triangles_0 = quad_indices[:, flexible_dual_grid_to_mesh.quad_split_1] + normals0 = torch.cross(mesh_vertices[atempt_triangles_0[:, 1]] - mesh_vertices[atempt_triangles_0[:, 0]], mesh_vertices[atempt_triangles_0[:, 2]] - mesh_vertices[atempt_triangles_0[:, 0]]) + normals1 = torch.cross(mesh_vertices[atempt_triangles_0[:, 2]] - mesh_vertices[atempt_triangles_0[:, 1]], mesh_vertices[atempt_triangles_0[:, 3]] - mesh_vertices[atempt_triangles_0[:, 1]]) + align0 = (normals0 * normals1).sum(dim=1, keepdim=True).abs() + # if split 2 + atempt_triangles_1 = quad_indices[:, flexible_dual_grid_to_mesh.quad_split_2] + normals0 = torch.cross(mesh_vertices[atempt_triangles_1[:, 1]] - mesh_vertices[atempt_triangles_1[:, 0]], mesh_vertices[atempt_triangles_1[:, 2]] - mesh_vertices[atempt_triangles_1[:, 0]]) + normals1 = torch.cross(mesh_vertices[atempt_triangles_1[:, 2]] - mesh_vertices[atempt_triangles_1[:, 1]], mesh_vertices[atempt_triangles_1[:, 3]] - mesh_vertices[atempt_triangles_1[:, 1]]) + align1 = (normals0 * normals1).sum(dim=1, keepdim=True).abs() + # select split + mesh_triangles = torch.where(align0 > align1, atempt_triangles_0, atempt_triangles_1).reshape(-1, 3) + else: + split_weight_ws = split_weight[quad_indices] + split_weight_ws_02 = split_weight_ws[:, 0] * split_weight_ws[:, 2] + split_weight_ws_13 = split_weight_ws[:, 1] * split_weight_ws[:, 3] + mesh_triangles = torch.where( + split_weight_ws_02 > split_weight_ws_13, + quad_indices[:, flexible_dual_grid_to_mesh.quad_split_1], + quad_indices[:, flexible_dual_grid_to_mesh.quad_split_2] + ).reshape(-1, 3) + else: + assert split_weight is not None, "split_weight must be provided in training mode" + mesh_vertices = (coords.float() + dual_vertices) * voxel_size + aabb[0].reshape(1, 3) + quad_vs = mesh_vertices[quad_indices] + mean_v02 = (quad_vs[:, 0] + quad_vs[:, 2]) / 2 + mean_v13 = (quad_vs[:, 1] + quad_vs[:, 3]) / 2 + split_weight_ws = split_weight[quad_indices] + split_weight_ws_02 = split_weight_ws[:, 0] * split_weight_ws[:, 2] + split_weight_ws_13 = split_weight_ws[:, 1] * split_weight_ws[:, 3] + mid_vertices = ( + split_weight_ws_02 * mean_v02 + + split_weight_ws_13 * mean_v13 + ) / (split_weight_ws_02 + split_weight_ws_13) + mesh_vertices = torch.cat([mesh_vertices, mid_vertices], dim=0) + quad_indices = torch.cat([quad_indices, torch.arange(N, N + L, device='cuda').unsqueeze(1)], dim=1) + mesh_triangles = quad_indices[:, flexible_dual_grid_to_mesh.quad_split_train].reshape(-1, 3) + + return mesh_vertices, mesh_triangles diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/volumetic_attr.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/volumetic_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..77c71c1f6ba0176d0286b7906c67279097395511 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/convert/volumetic_attr.py @@ -0,0 +1,583 @@ +from typing import * +import io +from PIL import Image +import torch +import numpy as np +from tqdm import tqdm +import trimesh +import trimesh.visual + +from .. import _C + +__all__ = [ + "textured_mesh_to_volumetric_attr", + "blender_dump_to_volumetric_attr" +] + + +ALPHA_MODE_ENUM = { + "OPAQUE": 0, + "MASK": 1, + "BLEND": 2, +} + + +def is_power_of_two(n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 + + +def nearest_power_of_two(n: int) -> int: + if n < 1: + raise ValueError("n must be >= 1") + if is_power_of_two(n): + return n + lower = 2 ** (n.bit_length() - 1) + upper = 2 ** n.bit_length() + if n - lower < upper - n: + return lower + else: + return upper + + +def textured_mesh_to_volumetric_attr( + mesh: Union[trimesh.Scene, trimesh.Trimesh, str], + voxel_size: Union[float, list, tuple, np.ndarray, torch.Tensor] = None, + grid_size: Union[int, list, tuple, np.ndarray, torch.Tensor] = None, + aabb: Union[list, tuple, np.ndarray, torch.Tensor] = None, + mip_level_offset: float = 0.0, + verbose: bool = False, + timing: bool = False, +) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """ + Voxelize a mesh into a sparse voxel grid with PBR properties. + + Args: + mesh (trimesh.Scene, trimesh.Trimesh, str): The input mesh. + If a string is provided, it will be loaded as a mesh using trimesh.load(). + voxel_size (float, list, tuple, np.ndarray, torch.Tensor): The size of each voxel. + grid_size (int, list, tuple, np.ndarray, torch.Tensor): The size of the grid. + NOTE: One of voxel_size and grid_size must be provided. + aabb (list, tuple, np.ndarray, torch.Tensor): The axis-aligned bounding box of the mesh. + If not provided, it will be computed automatically. + tile_size (int): The size of the tiles used for each individual voxelization. + mip_level_offset (float): The mip level offset for texture mip level selection. + verbose (bool): Whether to print the settings. + timing (bool): Whether to print the timing information. + + Returns: + torch.Tensor: The indices of the voxels that are occupied by the mesh. + Dict[str, torch.Tensor]: A dictionary containing the following keys: + - "base_color": The base color of the occupied voxels. + - "metallic": The metallic value of the occupied voxels. + - "roughness": The roughness value of the occupied voxels. + - "emissive": The emissive value of the occupied voxels. + - "alpha": The alpha value of the occupied voxels. + - "normal": The normal of the occupied voxels. + """ + + # Load mesh + if isinstance(mesh, str): + mesh = trimesh.load(mesh) + if isinstance(mesh, trimesh.Scene): + groups = mesh.dump() + if isinstance(mesh, trimesh.Trimesh): + groups = [mesh] + scene = trimesh.Scene(groups) + + # Voxelize settings + assert voxel_size is not None or grid_size is not None, "Either voxel_size or grid_size must be provided" + + if voxel_size is not None: + if isinstance(voxel_size, float): + voxel_size = [voxel_size, voxel_size, voxel_size] + if isinstance(voxel_size, (list, tuple)): + voxel_size = np.array(voxel_size) + if isinstance(voxel_size, np.ndarray): + voxel_size = torch.tensor(voxel_size, dtype=torch.float32) + assert isinstance(voxel_size, torch.Tensor), f"voxel_size must be a float, list, tuple, np.ndarray, or torch.Tensor, but got {type(voxel_size)}" + assert voxel_size.dim() == 1, f"voxel_size must be a 1D tensor, but got {voxel_size.shape}" + assert voxel_size.size(0) == 3, f"voxel_size must have 3 elements, but got {voxel_size.size(0)}" + + if grid_size is not None: + if isinstance(grid_size, int): + grid_size = [grid_size, grid_size, grid_size] + if isinstance(grid_size, (list, tuple)): + grid_size = np.array(grid_size) + if isinstance(grid_size, np.ndarray): + grid_size = torch.tensor(grid_size, dtype=torch.int32) + assert isinstance(grid_size, torch.Tensor), f"grid_size must be an int, list, tuple, np.ndarray, or torch.Tensor, but got {type(grid_size)}" + assert grid_size.dim() == 1, f"grid_size must be a 1D tensor, but got {grid_size.shape}" + assert grid_size.size(0) == 3, f"grid_size must have 3 elements, but got {grid_size.size(0)}" + + if aabb is not None: + if isinstance(aabb, (list, tuple)): + aabb = np.array(aabb) + if isinstance(aabb, np.ndarray): + aabb = torch.tensor(aabb, dtype=torch.float32) + assert isinstance(aabb, torch.Tensor), f"aabb must be a list, tuple, np.ndarray, or torch.Tensor, but got {type(aabb)}" + assert aabb.dim() == 2, f"aabb must be a 2D tensor, but got {aabb.shape}" + assert aabb.size(0) == 2, f"aabb must have 2 rows, but got {aabb.size(0)}" + assert aabb.size(1) == 3, f"aabb must have 3 columns, but got {aabb.size(1)}" + + # Auto adjust aabb + if aabb is None: + aabb = scene.bounds + min_xyz = aabb[0] + max_xyz = aabb[1] + + if voxel_size is not None: + padding = torch.ceil((max_xyz - min_xyz) / voxel_size) * voxel_size - (max_xyz - min_xyz) + min_xyz -= padding * 0.5 + max_xyz += padding * 0.5 + if grid_size is not None: + padding = (max_xyz - min_xyz) / (grid_size - 1) + min_xyz -= padding * 0.5 + max_xyz += padding * 0.5 + + aabb = torch.stack([min_xyz, max_xyz], dim=0).float() + + # Fill voxel size or grid size + if voxel_size is None: + voxel_size = (aabb[1] - aabb[0]) / grid_size + if grid_size is None: + grid_size = ((aabb[1] - aabb[0]) / voxel_size).round().int() + + grid_range = torch.stack([torch.zeros_like(grid_size), grid_size], dim=0).int() + + # Print settings + if verbose: + print(f"Voxelize settings:") + print(f" Voxel size: {voxel_size}") + print(f" Grid size: {grid_size}") + print(f" AABB: {aabb}") + + # Load Scene + scene_buffers = { + 'triangles': [], + 'normals': [], + 'uvs': [], + 'material_ids': [], + 'base_color_factor': [], + 'base_color_texture': [], + 'metallic_factor': [], + 'metallic_texture': [], + 'roughness_factor': [], + 'roughness_texture': [], + 'emissive_factor': [], + 'emissive_texture': [], + 'alpha_mode': [], + 'alpha_cutoff': [], + 'alpha_factor': [], + 'alpha_texture': [], + 'normal_texture': [], + } + for sid, (name, g) in tqdm(enumerate(scene.geometry.items()), total=len(scene.geometry), desc="Loading Scene", disable=not verbose): + if verbose: + print(f"Geometry: {name}") + print(f" Visual: {g.visual}") + print(f" Triangles: {g.triangles.shape[0]}") + print(f" Vertices: {g.vertices.shape[0]}") + print(f" Normals: {g.vertex_normals.shape[0]}") + if g.visual.material.baseColorFactor is not None: + print(f" Base color factor: {g.visual.material.baseColorFactor}") + if g.visual.material.baseColorTexture is not None: + print(f" Base color texture: {g.visual.material.baseColorTexture.size} {g.visual.material.baseColorTexture.mode}") + if g.visual.material.metallicFactor is not None: + print(f" Metallic factor: {g.visual.material.metallicFactor}") + if g.visual.material.roughnessFactor is not None: + print(f" Roughness factor: {g.visual.material.roughnessFactor}") + if g.visual.material.metallicRoughnessTexture is not None: + print(f" Metallic roughness texture: {g.visual.material.metallicRoughnessTexture.size} {g.visual.material.metallicRoughnessTexture.mode}") + if g.visual.material.emissiveFactor is not None: + print(f" Emissive factor: {g.visual.material.emissiveFactor}") + if g.visual.material.emissiveTexture is not None: + print(f" Emissive texture: {g.visual.material.emissiveTexture.size} {g.visual.material.emissiveTexture.mode}") + if g.visual.material.alphaMode is not None: + print(f" Alpha mode: {g.visual.material.alphaMode}") + if g.visual.material.alphaCutoff is not None: + print(f" Alpha cutoff: {g.visual.material.alphaCutoff}") + if g.visual.material.normalTexture is not None: + print(f" Normal texture: {g.visual.material.normalTexture.size} {g.visual.material.normalTexture.mode}") + + assert isinstance(g, trimesh.Trimesh), f"Only trimesh.Trimesh is supported, but got {type(g)}" + assert isinstance(g.visual, trimesh.visual.TextureVisuals), f"Only trimesh.visual.TextureVisuals is supported, but got {type(g.visual)}" + assert isinstance(g.visual.material, trimesh.visual.material.PBRMaterial), f"Only trimesh.visual.material.PBRMaterial is supported, but got {type(g.visual.material)}" + triangles = torch.tensor(g.triangles, dtype=torch.float32) - aabb[0].reshape(1, 1, 3) # [N, 3, 3] + normals = torch.tensor(g.vertex_normals[g.faces], dtype=torch.float32) # [N, 3, 3] + uvs = torch.tensor(g.visual.uv[g.faces], dtype=torch.float32) if g.visual.uv is not None \ + else torch.zeros(g.triangles.shape[0], 3, 2, dtype=torch.float32) # [N, 3, 2] + baseColorFactor = torch.tensor(g.visual.material.baseColorFactor / 255, dtype=torch.float32) if g.visual.material.baseColorFactor is not None \ + else torch.ones(3, dtype=torch.float32) # [3] + baseColorTexture = torch.tensor(np.array(g.visual.material.baseColorTexture.convert('RGBA'))[..., :3], dtype=torch.uint8) if g.visual.material.baseColorTexture is not None \ + else torch.tensor([]) # [H, W, 3] + metallicFactor = g.visual.material.metallicFactor if g.visual.material.metallicFactor is not None else 1.0 + metallicTexture = torch.tensor(np.array(g.visual.material.metallicRoughnessTexture.convert('RGB'))[..., 2], dtype=torch.uint8) if g.visual.material.metallicRoughnessTexture is not None \ + else torch.tensor([]) # [H, W] + roughnessFactor = g.visual.material.roughnessFactor if g.visual.material.roughnessFactor is not None else 1.0 + roughnessTexture = torch.tensor(np.array(g.visual.material.metallicRoughnessTexture.convert('RGB'))[..., 1], dtype=torch.uint8) if g.visual.material.metallicRoughnessTexture is not None \ + else torch.tensor([]) # [H, W] + emissiveFactor = torch.tensor(g.visual.material.emissiveFactor, dtype=torch.float32) if g.visual.material.emissiveFactor is not None \ + else torch.zeros(3, dtype=torch.float32) # [3] + emissiveTexture = torch.tensor(np.array(g.visual.material.emissiveTexture.convert('RGB'))[..., :3], dtype=torch.uint8) if g.visual.material.emissiveTexture is not None \ + else torch.tensor([]) # [H, W, 3] + alphaMode = ALPHA_MODE_ENUM[g.visual.material.alphaMode] if g.visual.material.alphaMode in ALPHA_MODE_ENUM else 0 + alphaCutoff = g.visual.material.alphaCutoff if g.visual.material.alphaCutoff is not None else 0.5 + alphaFactor = g.visual.material.baseColorFactor[3] / 255 if g.visual.material.baseColorFactor is not None else 1.0 + alphaTexture = torch.tensor(np.array(g.visual.material.baseColorTexture.convert('RGBA'))[..., 3], dtype=torch.uint8) if g.visual.material.baseColorTexture is not None and alphaMode != 0 \ + else torch.tensor([]) # [H, W] + normalTexture = torch.tensor(np.array(g.visual.material.normalTexture.convert('RGB'))[..., :3], dtype=torch.uint8) if g.visual.material.normalTexture is not None \ + else torch.tensor([]) # [H, W, 3] + + scene_buffers['triangles'].append(triangles) + scene_buffers['normals'].append(normals) + scene_buffers['uvs'].append(uvs) + scene_buffers['material_ids'].append(torch.full((triangles.shape[0],), sid, dtype=torch.int32)) + scene_buffers['base_color_factor'].append(baseColorFactor) + scene_buffers['base_color_texture'].append(baseColorTexture) + scene_buffers['metallic_factor'].append(metallicFactor) + scene_buffers['metallic_texture'].append(metallicTexture) + scene_buffers['roughness_factor'].append(roughnessFactor) + scene_buffers['roughness_texture'].append(roughnessTexture) + scene_buffers['emissive_factor'].append(emissiveFactor) + scene_buffers['emissive_texture'].append(emissiveTexture) + scene_buffers['alpha_mode'].append(alphaMode) + scene_buffers['alpha_cutoff'].append(alphaCutoff) + scene_buffers['alpha_factor'].append(alphaFactor) + scene_buffers['alpha_texture'].append(alphaTexture) + scene_buffers['normal_texture'].append(normalTexture) + + scene_buffers['triangles'] = torch.cat(scene_buffers['triangles'], dim=0) # [N, 3, 3] + scene_buffers['normals'] = torch.cat(scene_buffers['normals'], dim=0) # [N, 3, 3] + scene_buffers['uvs'] = torch.cat(scene_buffers['uvs'], dim=0) # [N, 3, 2] + scene_buffers['material_ids'] = torch.cat(scene_buffers['material_ids'], dim=0) # [N] + + # Voxelize + out_tuple = _C.textured_mesh_to_volumetric_attr_cpu( + voxel_size, + grid_range, + scene_buffers["triangles"], + scene_buffers["normals"], + scene_buffers["uvs"], + scene_buffers["material_ids"], + scene_buffers["base_color_factor"], + scene_buffers["base_color_texture"], + [1] * len(scene_buffers["base_color_texture"]), + [0] * len(scene_buffers["base_color_texture"]), + scene_buffers["metallic_factor"], + scene_buffers["metallic_texture"], + [1] * len(scene_buffers["metallic_texture"]), + [0] * len(scene_buffers["metallic_texture"]), + scene_buffers["roughness_factor"], + scene_buffers["roughness_texture"], + [1] * len(scene_buffers["roughness_texture"]), + [0] * len(scene_buffers["roughness_texture"]), + scene_buffers["emissive_factor"], + scene_buffers["emissive_texture"], + [1] * len(scene_buffers["emissive_texture"]), + [0] * len(scene_buffers["emissive_texture"]), + scene_buffers["alpha_mode"], + scene_buffers["alpha_cutoff"], + scene_buffers["alpha_factor"], + scene_buffers["alpha_texture"], + [1] * len(scene_buffers["alpha_texture"]), + [0] * len(scene_buffers["alpha_texture"]), + scene_buffers["normal_texture"], + [1] * len(scene_buffers["normal_texture"]), + [0] * len(scene_buffers["normal_texture"]), + mip_level_offset, + timing, + ) + + # Post process + coord = out_tuple[0] + attr = { + "base_color": torch.clamp(out_tuple[1] * 255, 0, 255).byte().reshape(-1, 3), + "metallic": torch.clamp(out_tuple[2] * 255, 0, 255).byte().reshape(-1, 1), + "roughness": torch.clamp(out_tuple[3] * 255, 0, 255).byte().reshape(-1, 1), + "emissive": torch.clamp(out_tuple[4] * 255, 0, 255).byte().reshape(-1, 3), + "alpha": torch.clamp(out_tuple[5] * 255, 0, 255).byte().reshape(-1, 1), + "normal": torch.clamp((out_tuple[6] * 0.5 + 0.5) * 255, 0, 255).byte().reshape(-1, 3), + } + + return coord, attr + + +def blender_dump_to_volumetric_attr( + dump: Dict[str, Any], + voxel_size: Union[float, list, tuple, np.ndarray, torch.Tensor] = None, + grid_size: Union[int, list, tuple, np.ndarray, torch.Tensor] = None, + aabb: Union[list, tuple, np.ndarray, torch.Tensor] = None, + mip_level_offset: float = 0.0, + verbose: bool = False, + timing: bool = False, +) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """ + Voxelize a mesh into a sparse voxel grid with PBR properties. + + Args: + dump (Dict[str, Any]): Dumped data from a blender scene. + voxel_size (float, list, tuple, np.ndarray, torch.Tensor): The size of each voxel. + grid_size (int, list, tuple, np.ndarray, torch.Tensor): The size of the grid. + NOTE: One of voxel_size and grid_size must be provided. + aabb (list, tuple, np.ndarray, torch.Tensor): The axis-aligned bounding box of the mesh. + If not provided, it will be computed automatically. + mip_level_offset (float): The mip level offset for texture mip level selection. + verbose (bool): Whether to print the settings. + timing (bool): Whether to print the timing information. + + Returns: + torch.Tensor: The indices of the voxels that are occupied by the mesh. + Dict[str, torch.Tensor]: A dictionary containing the following keys: + - "base_color": The base color of the occupied voxels. + - "metallic": The metallic value of the occupied voxels. + - "roughness": The roughness value of the occupied voxels. + - "emissive": The emissive value of the occupied voxels. + - "alpha": The alpha value of the occupied voxels. + - "normal": The normal of the occupied voxels. + """ + # Voxelize settings + assert voxel_size is not None or grid_size is not None, "Either voxel_size or grid_size must be provided" + + if voxel_size is not None: + if isinstance(voxel_size, float): + voxel_size = [voxel_size, voxel_size, voxel_size] + if isinstance(voxel_size, (list, tuple)): + voxel_size = np.array(voxel_size) + if isinstance(voxel_size, np.ndarray): + voxel_size = torch.tensor(voxel_size, dtype=torch.float32) + assert isinstance(voxel_size, torch.Tensor), f"voxel_size must be a float, list, tuple, np.ndarray, or torch.Tensor, but got {type(voxel_size)}" + assert voxel_size.dim() == 1, f"voxel_size must be a 1D tensor, but got {voxel_size.shape}" + assert voxel_size.size(0) == 3, f"voxel_size must have 3 elements, but got {voxel_size.size(0)}" + + if grid_size is not None: + if isinstance(grid_size, int): + grid_size = [grid_size, grid_size, grid_size] + if isinstance(grid_size, (list, tuple)): + grid_size = np.array(grid_size) + if isinstance(grid_size, np.ndarray): + grid_size = torch.tensor(grid_size, dtype=torch.int32) + assert isinstance(grid_size, torch.Tensor), f"grid_size must be an int, list, tuple, np.ndarray, or torch.Tensor, but got {type(grid_size)}" + assert grid_size.dim() == 1, f"grid_size must be a 1D tensor, but got {grid_size.shape}" + assert grid_size.size(0) == 3, f"grid_size must have 3 elements, but got {grid_size.size(0)}" + + if aabb is not None: + if isinstance(aabb, (list, tuple)): + aabb = np.array(aabb) + if isinstance(aabb, np.ndarray): + aabb = torch.tensor(aabb, dtype=torch.float32) + assert isinstance(aabb, torch.Tensor), f"aabb must be a list, tuple, np.ndarray, or torch.Tensor, but got {type(aabb)}" + assert aabb.dim() == 2, f"aabb must be a 2D tensor, but got {aabb.shape}" + assert aabb.size(0) == 2, f"aabb must have 2 rows, but got {aabb.size(0)}" + assert aabb.size(1) == 3, f"aabb must have 3 columns, but got {aabb.size(1)}" + + # Auto adjust aabb + if aabb is None: + min_xyz = np.min([ + object['vertices'].min(axis=0) + for object in dump['objects'] + ], axis=0) + max_xyz = np.max([ + object['vertices'].max(axis=0) + for object in dump['objects'] + ], axis=0) + + if voxel_size is not None: + padding = torch.ceil((max_xyz - min_xyz) / voxel_size) * voxel_size - (max_xyz - min_xyz) + min_xyz -= padding * 0.5 + max_xyz += padding * 0.5 + if grid_size is not None: + padding = (max_xyz - min_xyz) / (grid_size - 1) + min_xyz -= padding * 0.5 + max_xyz += padding * 0.5 + + aabb = torch.stack([min_xyz, max_xyz], dim=0).float() + + # Fill voxel size or grid size + if voxel_size is None: + voxel_size = (aabb[1] - aabb[0]) / grid_size + if grid_size is None: + grid_size = ((aabb[1] - aabb[0]) / voxel_size).round().int() + + grid_range = torch.stack([torch.zeros_like(grid_size), grid_size], dim=0).int() + + # Print settings + if verbose: + print(f"Voxelize settings:") + print(f" Voxel size: {voxel_size}") + print(f" Grid size: {grid_size}") + print(f" AABB: {aabb}") + + # Load Scene + scene_buffers = { + 'triangles': [], + 'normals': [], + 'uvs': [], + 'material_ids': [], + 'base_color_factor': [], + 'base_color_texture': [], + 'base_color_texture_filter': [], + 'base_color_texture_wrap': [], + 'metallic_factor': [], + 'metallic_texture': [], + 'metallic_texture_filter': [], + 'metallic_texture_wrap': [], + 'roughness_factor': [], + 'roughness_texture': [], + 'roughness_texture_filter': [], + 'roughness_texture_wrap': [], + 'alpha_mode': [], + 'alpha_cutoff': [], + 'alpha_factor': [], + 'alpha_texture': [], + 'alpha_texture_filter': [], + 'alpha_texture_wrap': [], + } + + def load_texture(pack): + png_bytes = pack['image'] + image = Image.open(io.BytesIO(png_bytes)) + if image.width != image.height or not is_power_of_two(image.width): + size = nearest_power_of_two(max(image.width, image.height)) + image = image.resize((size, size), Image.LANCZOS) + texture = torch.tensor(np.array(image), dtype=torch.uint8) + filter_mode = { + 'Linear': 1, + 'Closest': 0, + 'Cubic': 1, + 'Smart': 1, + }[pack['interpolation']] + wrap_mode = { + 'REPEAT': 0, + 'EXTEND': 1, + 'CLIP': 1, + 'MIRROR': 2, + }[pack['extension']] + return texture, filter_mode, wrap_mode + + for material in dump['materials']: + baseColorFactor = torch.tensor(material['baseColorFactor'][:3], dtype=torch.float32) + if material['baseColorTexture'] is not None: + baseColorTexture, baseColorTextureFilter, baseColorTextureWrap = \ + load_texture(material['baseColorTexture']) + assert baseColorTexture.shape[2] == 3, f"Base color texture must have 3 channels, but got {baseColorTexture.shape[2]}" + else: + baseColorTexture = torch.tensor([]) + baseColorTextureFilter = 0 + baseColorTextureWrap = 0 + scene_buffers['base_color_factor'].append(baseColorFactor) + scene_buffers['base_color_texture'].append(baseColorTexture) + scene_buffers['base_color_texture_filter'].append(baseColorTextureFilter) + scene_buffers['base_color_texture_wrap'].append(baseColorTextureWrap) + + metallicFactor = material['metallicFactor'] + if material['metallicTexture'] is not None: + metallicTexture, metallicTextureFilter, metallicTextureWrap = \ + load_texture(material['metallicTexture']) + assert metallicTexture.dim() == 2, f"Metallic roughness texture must have 2 dimensions, but got {metallicTexture.dim()}" + else: + metallicTexture = torch.tensor([]) + metallicTextureFilter = 0 + metallicTextureWrap = 0 + scene_buffers['metallic_factor'].append(metallicFactor) + scene_buffers['metallic_texture'].append(metallicTexture) + scene_buffers['metallic_texture_filter'].append(metallicTextureFilter) + scene_buffers['metallic_texture_wrap'].append(metallicTextureWrap) + + roughnessFactor = material['roughnessFactor'] + if material['roughnessTexture'] is not None: + roughnessTexture, roughnessTextureFilter, roughnessTextureWrap = \ + load_texture(material['roughnessTexture']) + assert roughnessTexture.dim() == 2, f"Metallic roughness texture must have 2 dimensions, but got {roughnessTexture.dim()}" + else: + roughnessTexture = torch.tensor([]) + roughnessTextureFilter = 0 + roughnessTextureWrap = 0 + scene_buffers['roughness_factor'].append(roughnessFactor) + scene_buffers['roughness_texture'].append(roughnessTexture) + scene_buffers['roughness_texture_filter'].append(roughnessTextureFilter) + scene_buffers['roughness_texture_wrap'].append(roughnessTextureWrap) + + alphaMode = ALPHA_MODE_ENUM[material['alphaMode']] + alphaCutoff = material['alphaCutoff'] + alphaFactor = material['alphaFactor'] + if material['alphaTexture'] is not None: + alphaTexture, alphaTextureFilter, alphaTextureWrap = \ + load_texture(material['alphaTexture']) + assert alphaTexture.dim() == 2, f"Alpha texture must have 2 dimensions, but got {alphaTexture.dim()}" + else: + alphaTexture = torch.tensor([]) + alphaTextureFilter = 0 + alphaTextureWrap = 0 + scene_buffers['alpha_mode'].append(alphaMode) + scene_buffers['alpha_cutoff'].append(alphaCutoff) + scene_buffers['alpha_factor'].append(alphaFactor) + scene_buffers['alpha_texture'].append(alphaTexture) + scene_buffers['alpha_texture_filter'].append(alphaTextureFilter) + scene_buffers['alpha_texture_wrap'].append(alphaTextureWrap) + + for object in dump['objects']: + triangles = torch.tensor(object['vertices'][object['faces']], dtype=torch.float32).reshape(-1, 3, 3) - aabb[0].reshape(1, 1, 3) + normails = torch.tensor(object['normals'], dtype=torch.float32) + uvs = torch.tensor(object['uvs'], dtype=torch.float32) if object['uvs'] is not None else torch.zeros(triangles.shape[0], 3, 2, dtype=torch.float32) + material_id = torch.tensor(object['mat_ids'], dtype=torch.int32) + scene_buffers['triangles'].append(triangles) + scene_buffers['normals'].append(normails) + scene_buffers['uvs'].append(uvs) + scene_buffers['material_ids'].append(material_id) + + scene_buffers['triangles'] = torch.cat(scene_buffers['triangles'], dim=0) # [N, 3, 3] + scene_buffers['normals'] = torch.cat(scene_buffers['normals'], dim=0) # [N, 3, 3] + scene_buffers['uvs'] = torch.cat(scene_buffers['uvs'], dim=0) # [N, 3, 2] + scene_buffers['material_ids'] = torch.cat(scene_buffers['material_ids'], dim=0) # [N] + + scene_buffers['uvs'][:, :, 1] = 1 - scene_buffers['uvs'][:, :, 1] # Flip v coordinate + + # Voxelize + out_tuple = _C.textured_mesh_to_volumetric_attr_cpu( + voxel_size, + grid_range, + scene_buffers["triangles"], + scene_buffers["normals"], + scene_buffers["uvs"], + scene_buffers["material_ids"], + scene_buffers["base_color_factor"], + scene_buffers["base_color_texture"], + scene_buffers["base_color_texture_filter"], + scene_buffers["base_color_texture_wrap"], + scene_buffers["metallic_factor"], + scene_buffers["metallic_texture"], + scene_buffers["metallic_texture_filter"], + scene_buffers["metallic_texture_wrap"], + scene_buffers["roughness_factor"], + scene_buffers["roughness_texture"], + scene_buffers["roughness_texture_filter"], + scene_buffers["roughness_texture_wrap"], + [torch.zeros(3, dtype=torch.float32) for _ in range(len(scene_buffers["base_color_texture"]))], + [torch.tensor([]) for _ in range(len(scene_buffers["base_color_texture"]))], + [0] * len(scene_buffers["base_color_texture"]), + [0] * len(scene_buffers["base_color_texture"]), + scene_buffers["alpha_mode"], + scene_buffers["alpha_cutoff"], + scene_buffers["alpha_factor"], + scene_buffers["alpha_texture"], + scene_buffers["alpha_texture_filter"], + scene_buffers["alpha_texture_wrap"], + [torch.tensor([]) for _ in range(len(scene_buffers["base_color_texture"]))], + [0] * len(scene_buffers["base_color_texture"]), + [0] * len(scene_buffers["base_color_texture"]), + mip_level_offset, + timing, + ) + + # Post process + coord = out_tuple[0] + attr = { + "base_color": torch.clamp(out_tuple[1] * 255, 0, 255).byte().reshape(-1, 3), + "metallic": torch.clamp(out_tuple[2] * 255, 0, 255).byte().reshape(-1, 1), + "roughness": torch.clamp(out_tuple[3] * 255, 0, 255).byte().reshape(-1, 1), + "emissive": torch.clamp(out_tuple[4] * 255, 0, 255).byte().reshape(-1, 3), + "alpha": torch.clamp(out_tuple[5] * 255, 0, 255).byte().reshape(-1, 1), + "normal": torch.clamp((out_tuple[6] * 0.5 + 0.5) * 255, 0, 255).byte().reshape(-1, 3), + } + + return coord, attr \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f29541bbbf8ef8275a31b45f7b0144d366ba1250 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/__init__.py @@ -0,0 +1,45 @@ +from typing import Dict, Union +import torch +from .ply import * +from .npz import * +from .vxz import * + + +def read(file_path: str) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """ + Read a file containing voxels. + + Args: + file_path: Path to the file. + + Returns: + torch.Tensor: the coordinates of the voxels. + Dict[str, torch.Tensor]: the attributes of the voxels. + """ + if file_path.endswith('.npz'): + return read_npz(file_path) + elif file_path.endswith('.ply'): + return read_ply(file_path) + elif file_path.endswith('.vxz'): + return read_vxz(file_path) + else: + raise ValueError(f"Unsupported file type {file_path}") + + +def write(file_path: str, coord: torch.Tensor, attr: Dict[str, torch.Tensor], **kwargs): + """ + Write a file containing voxels. + + Args: + file_path: Path to the file. + coord: the coordinates of the voxels. + attr: the attributes of the voxels. + """ + if file_path.endswith('.npz'): + write_npz(file_path, coord, attr, **kwargs) + elif file_path.endswith('.ply'): + write_ply(file_path, coord, attr, **kwargs) + elif file_path.endswith('.vxz'): + write_vxz(file_path, coord, attr, **kwargs) + else: + raise ValueError(f"Unsupported file type {file_path}") diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/npz.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/npz.py new file mode 100644 index 0000000000000000000000000000000000000000..900904555061aca9fbc8f941c70112d0a663a804 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/npz.py @@ -0,0 +1,43 @@ +from typing import * +import torch +import numpy as np + + +__all__ = [ + "read_npz", + "write_npz", +] + + +def read_npz(file) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """ + Read a NPZ file containing voxels. + + Args: + file_path: Path or file object from which to read the NPZ file. + + Returns: + torch.Tensor: the coordinates of the voxels. + Dict[str, torch.Tensor]: the attributes of the voxels. + """ + data = np.load(file) + coord = torch.from_numpy(data['coord']).int() + attr = {k: torch.from_numpy(v) for k, v in data.items() if k!= 'coord'} + return coord, attr + + +def write_npz(file, coord: torch.Tensor, attr: Dict[str, torch.Tensor], compress=True): + """ + Write a NPZ file containing voxels. + + Args: + file_path: Path or file object to which to write the NPZ file. + coord: the coordinates of the voxels. + attr: the attributes of the voxels. + """ + data = {'coord': coord.cpu().numpy().astype(np.uint16)} + data.update({k: v.cpu().numpy() for k, v in attr.items()}) + if compress: + np.savez_compressed(file, **data) + else: + np.savez(file, **data) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/ply.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/ply.py new file mode 100644 index 0000000000000000000000000000000000000000..c8e7fb82db86760eeb3e524e3f2cce93f9533414 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/ply.py @@ -0,0 +1,72 @@ +from typing import * +import io +import torch +import numpy as np +import plyfile + + +__all__ = [ + "read_ply", + "write_ply", +] + + +DTYPE_MAP = { + torch.uint8: 'u1', + torch.uint16: 'u2', + torch.uint32: 'u4', + torch.int8: 'i1', + torch.int16: 'i2', + torch.int32: 'i4', + torch.float32: 'f4', + torch.float64: 'f8' +} + + +def read_ply(file) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """ + Read a PLY file containing voxels. + + Args: + file: Path or file-like object of the PLY file. + + Returns: + torch.Tensor: the coordinates of the voxels. + Dict[str, torch.Tensor]: the attributes of the voxels. + """ + plydata = plyfile.PlyData.read(file) + xyz = np.stack([plydata.elements[0][k] for k in ['x', 'y', 'z']], axis=1) + coord = np.round(xyz).astype(int) + coord = torch.from_numpy(coord) + + attr_keys = [k for k in plydata.elements[0].data.dtype.names if k not in ['x', 'y', 'z']] + attr_names = ['_'.join(k.split('_')[:-1]) for k in attr_keys] + attr_chs = [sum([1 for k in attr_keys if k.startswith(f'{name}_')]) for name in attr_names] + + attr = {} + for i, name in enumerate(attr_names): + attr[name] = np.stack([plydata.elements[0][f'{name}_{j}'] for j in range(attr_chs[i])], axis=1) + attr = {k: torch.from_numpy(v) for k, v in attr.items()} + + return coord, attr + + +def write_ply(file, coord: torch.Tensor, attr: Dict[str, torch.Tensor]): + """ + Write a PLY file containing voxels. + + Args: + file: Path or file-like object of the PLY file. + coord: the coordinates of the voxels. + attr: the attributes of the voxels. + """ + dtypes = [('x', 'f4'), ('y', 'f4'), ('z', 'f4')] + for k, v in attr.items(): + for j in range(v.shape[-1]): + assert v.dtype in DTYPE_MAP, f"Unsupported data type {v.dtype} for attribute {k}" + dtypes.append((f'{k}_{j}', DTYPE_MAP[v.dtype])) + data = np.empty(len(coord), dtype=dtypes) + all_chs = np.concatenate([coord.cpu().numpy().astype(np.float32)] + [v.cpu().numpy() for v in attr.values()], axis=1) + data[:] = list(map(tuple, all_chs)) + plyfile.PlyData([plyfile.PlyElement.describe(data, 'vertex')]).write(file) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/vxz.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/vxz.py new file mode 100644 index 0000000000000000000000000000000000000000..bc34cda8eeee8633ddb107f79edbcdb4947aa430 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/io/vxz.py @@ -0,0 +1,365 @@ +from typing import * +import os +import json +import struct +import torch +import numpy as np +import zlib +import lzma +import zstandard +from concurrent.futures import ThreadPoolExecutor +from ..serialize import encode_seq, decode_seq +from .. import _C + + +__all__ = [ + "read_vxz", + "read_vxz_info", + "write_vxz", +] + + +""" +VXZ format + +Header: +- file type (3 bytes) - 'VXZ' +- version (1 byte) - 0 +- binary start offset (4 bytes) +- structure (json) - +{ + "num_voxel": int, + "chunk_size": int, + "filter": str, + "compression": str, + "compression_level": int, + "raw_size": int, + "compressed_size": int, + "compress_ratio": float, + "attr_interleave": str, + "attr": [ + {"name": str, "chs": int}, + ... + ] + "chunks": [ + { + "ptr": [offset, length], # offset from global binary start + "svo": [offset, length], # offset from this chunk start + "attr": [offset, length], # offset from this chunk start + }, + ... + ] +} +- binary data +""" + +DEFAULT_COMPRESION_LEVEL = { + 'none': 0, + 'deflate': 9, + 'lzma': 9, + 'zstd': 22, +} + + +def _compress(data: bytes, algo: Literal['none', 'deflate', 'lzma', 'zstd'], level: int) -> bytes: + if algo == 'none': + return data + if level is None: + level = DEFAULT_COMPRESION_LEVEL[algo] + if algo == 'deflate': + compresser = zlib.compressobj(level, wbits=-15) + return compresser.compress(data) + compresser.flush() + if algo == 'lzma': + compresser = lzma.LZMACompressor(format=lzma.FORMAT_RAW, filters=[{'id': lzma.FILTER_LZMA2, 'preset': level}]) + return compresser.compress(data) + compresser.flush() + if algo == 'zstd': + compresser = zstandard.ZstdCompressor(level=level, write_checksum=False, write_content_size=True, threads=-1) + return compresser.compress(data) + raise ValueError(f"Invalid compression algorithm: {algo}") + + +def _decompress(data: bytes, algo: Literal['none', 'deflate', 'lzma', 'zstd'], level: int) -> bytes: + if algo == 'none': + return data + if level is None: + level = DEFAULT_COMPRESION_LEVEL[algo] + if algo == 'deflate': + decompresser = zlib.decompressobj(wbits=-15) + return decompresser.decompress(data) + decompresser.flush() + if algo == 'lzma': + decompresser = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=[{'id': lzma.FILTER_LZMA2, 'preset': level}]) + return decompresser.decompress(data) + if algo == 'zstd': + decompresser = zstandard.ZstdDecompressor(format=zstandard.FORMAT_ZSTD1) + return decompresser.decompress(data) + raise ValueError(f"Invalid compression algorithm: {algo}") + + +def read_vxz_info(file) -> Dict: + """ + Read the header of a VXZ file without decompressing the binary data. + + Args: + file_path: Path or file-like object to the VXZ file. + + Returns: + Dict: the header of the VXZ file. + """ + if isinstance(file, str): + with open(file, 'rb') as f: + file_data = f.read() + else: + file_data = file.read() + + assert file_data[:3] == b'VXZ', "Invalid file type" + version = file_data[3] + assert version == 0, "Invalid file version" + + bin_start = struct.unpack('>I', file_data[4:8])[0] + structure_data = json.loads(file_data[8:bin_start].decode()) + return structure_data + + +def read_vxz(file, num_threads: int = -1) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """ + Read a VXZ file containing voxels. + + Args: + file_path: Path or file-like object to the VXZ file. + num_threads: the number of threads to use for reading the file. + + Returns: + torch.Tensor: the coordinates of the voxels. + Dict[str, torch.Tensor]: the attributes of the voxels. + """ + if isinstance(file, str): + with open(file, 'rb') as f: + file_data = f.read() + else: + file_data = file.read() + + num_threads = num_threads if num_threads > 0 else os.cpu_count() + + # Parse header + assert file_data[:3] == b'VXZ', "Invalid file type" + version = file_data[3] + assert version == 0, "Invalid file version" + + bin_start = struct.unpack('>I', file_data[4:8])[0] + structure_data = json.loads(file_data[8:bin_start].decode()) + bin_data = file_data[bin_start:] + + # Decode chunks + chunk_size = structure_data['chunk_size'] + chunk_depth = np.log2(chunk_size) + assert chunk_depth.is_integer(), f"Chunk size must be a power of 2, got {chunk_size}" + chunk_depth = int(chunk_depth) + + def worker(chunk_info): + decompressed = {} + chunk_data = bin_data[chunk_info['ptr'][0]:chunk_info['ptr'][0]+chunk_info['ptr'][1]] + for k, v in chunk_info.items(): + if k in ['ptr', 'idx']: + continue + decompressed[k] = np.frombuffer(_decompress(chunk_data[v[0]:v[0]+v[1]], structure_data['compression'], structure_data['compression_level']), dtype=np.uint8) + svo = torch.tensor(np.frombuffer(decompressed['svo'], dtype=np.uint8)) + morton_code = _C.decode_sparse_voxel_octree_cpu(svo, chunk_depth) + coord = decode_seq(morton_code.int()).cpu() + + # deinterleave attributes + if structure_data['attr_interleave'] == 'none': + all_attr = [] + for k, chs in structure_data['attr']: + for i in range(chs): + all_attr.append(torch.tensor(decompressed[f'{k}_{i}'])) + all_attr = torch.stack(all_attr, dim=1) + elif structure_data['attr_interleave'] == 'as_is': + all_attr = [] + for k, chs in structure_data['attr']: + all_attr.append(torch.tensor(decompressed[k].reshape(-1, chs))) + all_attr = torch.cat(all_attr, dim=1) + elif structure_data['attr_interleave'] == 'all': + all_chs = sum(chs for k, chs in structure_data['attr']) + all_attr = decompressed['attr'].reshape(-1, all_chs) + + # unfilter + if structure_data['filter'] == 'none': + pass + elif structure_data['filter'] == 'parent': + all_attr = _C.decode_sparse_voxel_octree_attr_parent_cpu(svo, chunk_depth, all_attr) + elif structure_data['filter'] == 'neighbor': + all_attr = _C.decode_sparse_voxel_octree_attr_neighbor_cpu(coord, chunk_size, all_attr) + + # final + attr = {} + ch = 0 + for k, chs in structure_data['attr']: + attr[k] = all_attr[:, ch:ch+chs] + ch += chs + return { + 'coord': coord, + 'attr': attr, + } + + if num_threads == 1: + chunks = [worker(info) for info in structure_data['chunks']] + else: + with ThreadPoolExecutor(max_workers=num_threads) as executor: + chunks = list(executor.map(worker, structure_data['chunks'])) + + # Combine chunks + coord = [] + attr = {k: [] for k, _ in structure_data['attr']} + for info, chunk in zip(structure_data['chunks'], chunks): + coord.append(chunk['coord'] + torch.tensor([[info['idx'][0] * chunk_size, info['idx'][1] * chunk_size, info['idx'][2] * chunk_size]]).int()) + for k, v in chunk['attr'].items(): + attr[k].append(v) + coord = torch.cat(coord, dim=0) + for k, v in attr.items(): + attr[k] = torch.cat(v, dim=0) + return coord, attr + + +def write_vxz( + file, + coord: torch.Tensor, + attr: Dict[str, torch.Tensor], + chunk_size: int = 256, + filter: Literal['none', 'parent', 'neighbor'] = 'none', + compression: Literal['none', 'deflate', 'lzma', 'zstd'] = 'lzma', + compression_level: Optional[int] = None, + attr_interleave: Literal['none', 'as_is', 'all'] = 'as_is', + num_threads: int = -1, +): + """ + Write a VXZ file containing voxels. + + Args: + file: Path or file-like object to the VXZ file. + coord: the coordinates of the voxels. + attr: the attributes of the voxels. + chunk_size: the size of each chunk. + filter: the filter to apply to the voxels. + compression: the compression algorithm to use. + compression_level: the level of compression. + attr_interleave: how to interleave the attributes. + num_threads: the number of threads to use for compression. + """ + # Check + for k, v in attr.items(): + assert coord.shape[0] == v.shape[0], f"Number of coordinates and attributes do not match for key {k}" + assert v.dtype == torch.uint8, f"Attributes must be uint8, got {v.dtype} for key {k}" + assert attr_interleave in ['none', 'as_is', 'all'], f"Invalid attr_interleave value: {attr_interleave}" + + compression_level = compression_level or DEFAULT_COMPRESION_LEVEL[compression] + num_threads = num_threads if num_threads > 0 else os.cpu_count() + + file_info = { + 'num_voxel': coord.shape[0], + 'chunk_size': chunk_size, + 'filter': filter, + 'compression': compression, + 'compression_level': compression_level, + 'raw_size': sum([coord.numel() * 4] + [v.numel() for v in attr.values()]), + 'compressed_size': 0, + 'compress_ratio': 0.0, + 'attr_interleave': attr_interleave, + 'attr': [[k, v.shape[1]] for k, v in attr.items()], + 'chunks': [], + } + bin_data = b'' + + # Split into chunks + chunk_depth = np.log2(chunk_size) + assert chunk_depth.is_integer(), f"Chunk size must be a power of 2, got {chunk_size}" + chunk_depth = int(chunk_depth) + + chunk_coord = coord // chunk_size + coord = coord % chunk_size + unique_chunk_coord, inverse = torch.unique(chunk_coord, dim=0, return_inverse=True) + + chunks = [] + for idx, chunk_xyz in enumerate(unique_chunk_coord.tolist()): + chunk_mask = (inverse == idx) + chunks.append({ + 'idx': chunk_xyz, + 'coord': coord[chunk_mask], + 'attr': {k: v[chunk_mask] for k, v in attr.items()}, + }) + + # Compress each chunk + with ThreadPoolExecutor(max_workers=num_threads) as executor: + def worker(chunk): + ## compress to binary + coord = chunk['coord'] + morton_code = encode_seq(coord) + sorted_idx = morton_code.argsort().cpu() + coord = coord.cpu()[sorted_idx] + morton_code = morton_code.cpu()[sorted_idx] + attr = torch.cat([v.cpu()[sorted_idx] for v in chunk['attr'].values()], dim=1) + svo = _C.encode_sparse_voxel_octree_cpu(morton_code, chunk_depth) + svo_bytes = _compress(svo.numpy().tobytes(), compression, compression_level) + + # filter + if filter == 'none': + attr = attr.numpy() + elif filter == 'parent': + attr = _C.encode_sparse_voxel_octree_attr_parent_cpu(svo, chunk_depth, attr).numpy() + elif filter == 'neighbor': + attr = _C.encode_sparse_voxel_octree_attr_neighbor_cpu(coord, chunk_size, attr).numpy() + + # interleave attributes + attr_bytes = {} + if attr_interleave == 'none': + ch = 0 + for k, chs in file_info['attr']: + for i in range(chs): + attr_bytes[f'{k}_{i}'] = _compress(attr[:, ch].tobytes(), compression, compression_level) + ch += 1 + elif attr_interleave == 'as_is': + ch = 0 + for k, chs in file_info['attr']: + attr_bytes[k] = _compress(attr[:, ch:ch+chs].tobytes(), compression, compression_level) + ch += chs + elif attr_interleave == 'all': + attr_bytes['attr'] = _compress(attr.tobytes(), compression, compression_level) + + ## buffer for each chunk + chunk_info = {'idx': chunk['idx']} + bin_data = b'' + + ### svo + chunk_info['svo'] = [len(bin_data), len(svo_bytes)] + bin_data += svo_bytes + + ### attr + for k, v in attr_bytes.items(): + chunk_info[k] = [len(bin_data), len(v)] + bin_data += v + + return chunk_info, bin_data + + chunks = list(executor.map(worker, chunks)) + + for chunk_info, chunk_data in chunks: + chunk_info['ptr'] = [len(bin_data), len(chunk_data)] + bin_data += chunk_data + file_info['chunks'].append(chunk_info) + + file_info['compressed_size'] = len(bin_data) + file_info['compress_ratio'] = file_info['raw_size'] / file_info['compressed_size'] + + # File parts + structure_data = json.dumps(file_info).encode() + header = b'VXZ\x00' + struct.pack('>I', len(structure_data) + 8) + + # Write to file + if isinstance(file, str): + with open(file, 'wb') as f: + f.write(header) + f.write(structure_data) + f.write(bin_data) + else: + file.write(header) + file.write(structure_data) + file.write(bin_data) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/postprocess.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce82271bab56dc757b3cd45ceea4f88d1bea551 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/postprocess.py @@ -0,0 +1,331 @@ +from typing import * +from tqdm import tqdm +import numpy as np +import torch +import cv2 +from PIL import Image +import trimesh +import trimesh.visual +from flex_gemm.ops.grid_sample import grid_sample_3d +import nvdiffrast.torch as dr +import cumesh + + +def to_glb( + vertices: torch.Tensor, + faces: torch.Tensor, + attr_volume: torch.Tensor, + coords: torch.Tensor, + attr_layout: Dict[str, slice], + aabb: Union[list, tuple, np.ndarray, torch.Tensor], + voxel_size: Union[float, list, tuple, np.ndarray, torch.Tensor] = None, + grid_size: Union[int, list, tuple, np.ndarray, torch.Tensor] = None, + decimation_target: int = 1000000, + texture_size: int = 2048, + remesh: bool = False, + remesh_band: float = 1, + remesh_project: float = 0.9, + mesh_cluster_threshold_cone_half_angle_rad=np.radians(90.0), + mesh_cluster_refine_iterations=0, + mesh_cluster_global_iterations=1, + mesh_cluster_smooth_strength=1, + verbose: bool = False, + use_tqdm: bool = False, +): + """ + Convert an extracted mesh to a GLB file. + Performs cleaning, optional remeshing, UV unwrapping, and texture baking from a volume. + + Args: + vertices: (N, 3) tensor of vertex positions + faces: (M, 3) tensor of vertex indices + attr_volume: (L, C) features of a sprase tensor for attribute interpolation + coords: (L, 3) tensor of coordinates for each voxel + attr_layout: dictionary of slice objects for each attribute + aabb: (2, 3) tensor of minimum and maximum coordinates of the volume + voxel_size: (3,) tensor of size of each voxel + grid_size: (3,) tensor of number of voxels in each dimension + decimation_target: target number of vertices for mesh simplification + texture_size: size of the texture for baking + remesh: whether to perform remeshing + remesh_band: size of the remeshing band + remesh_project: projection factor for remeshing + mesh_cluster_threshold_cone_half_angle_rad: threshold for cone-based clustering in uv unwrapping + mesh_cluster_refine_iterations: number of iterations for refining clusters in uv unwrapping + mesh_cluster_global_iterations: number of global iterations for clustering in uv unwrapping + mesh_cluster_smooth_strength: strength of smoothing for clustering in uv unwrapping + verbose: whether to print verbose messages + use_tqdm: whether to use tqdm to display progress bar + """ + # --- Input Normalization (AABB, Voxel Size, Grid Size) --- + if isinstance(aabb, (list, tuple)): + aabb = np.array(aabb) + if isinstance(aabb, np.ndarray): + aabb = torch.tensor(aabb, dtype=torch.float32, device=coords.device) + assert isinstance(aabb, torch.Tensor), f"aabb must be a list, tuple, np.ndarray, or torch.Tensor, but got {type(aabb)}" + assert aabb.dim() == 2, f"aabb must be a 2D tensor, but got {aabb.shape}" + assert aabb.size(0) == 2, f"aabb must have 2 rows, but got {aabb.size(0)}" + assert aabb.size(1) == 3, f"aabb must have 3 columns, but got {aabb.size(1)}" + + # Calculate grid dimensions based on AABB and voxel size + if voxel_size is not None: + if isinstance(voxel_size, float): + voxel_size = [voxel_size, voxel_size, voxel_size] + if isinstance(voxel_size, (list, tuple)): + voxel_size = np.array(voxel_size) + if isinstance(voxel_size, np.ndarray): + voxel_size = torch.tensor(voxel_size, dtype=torch.float32, device=coords.device) + grid_size = ((aabb[1] - aabb[0]) / voxel_size).round().int() + else: + assert grid_size is not None, "Either voxel_size or grid_size must be provided" + if isinstance(grid_size, int): + grid_size = [grid_size, grid_size, grid_size] + if isinstance(grid_size, (list, tuple)): + grid_size = np.array(grid_size) + if isinstance(grid_size, np.ndarray): + grid_size = torch.tensor(grid_size, dtype=torch.int32, device=coords.device) + voxel_size = (aabb[1] - aabb[0]) / grid_size + + # Assertions for dimensions + assert isinstance(voxel_size, torch.Tensor) + assert voxel_size.dim() == 1 and voxel_size.size(0) == 3 + assert isinstance(grid_size, torch.Tensor) + assert grid_size.dim() == 1 and grid_size.size(0) == 3 + + if use_tqdm: + pbar = tqdm(total=6, desc="Extracting GLB") + if verbose: + print(f"Original mesh: {vertices.shape[0]} vertices, {faces.shape[0]} faces") + + # Move data to GPU + vertices = vertices.cuda() + faces = faces.cuda() + + # Initialize CUDA mesh handler + mesh = cumesh.CuMesh() + mesh.init(vertices, faces) + + # --- Initial Mesh Cleaning --- + # Fills holes as much as we can before processing + mesh.fill_holes(max_hole_perimeter=3e-2) + if verbose: + print(f"After filling holes: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + vertices, faces = mesh.read() + if use_tqdm: + pbar.update(1) + + # Build BVH for the current mesh to guide remeshing + if use_tqdm: + pbar.set_description("Building BVH") + if verbose: + print(f"Building BVH for current mesh...", end='', flush=True) + bvh = cumesh.cuBVH(vertices, faces) + if use_tqdm: + pbar.update(1) + if verbose: + print("Done") + + if use_tqdm: + pbar.set_description("Cleaning mesh") + if verbose: + print("Cleaning mesh...") + + # --- Branch 1: Standard Pipeline (Simplification & Cleaning) --- + if not remesh: + # Step 1: Aggressive simplification (3x target) + mesh.simplify(decimation_target * 3, verbose=verbose) + if verbose: + print(f"After inital simplification: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + + # Step 2: Clean up topology (duplicates, non-manifolds, isolated parts) + mesh.remove_duplicate_faces() + mesh.repair_non_manifold_edges() + mesh.remove_small_connected_components(1e-5) + mesh.fill_holes(max_hole_perimeter=3e-2) + if verbose: + print(f"After initial cleanup: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + + # Step 3: Final simplification to target count + mesh.simplify(decimation_target, verbose=verbose) + if verbose: + print(f"After final simplification: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + + # Step 4: Final Cleanup loop + mesh.remove_duplicate_faces() + mesh.repair_non_manifold_edges() + mesh.remove_small_connected_components(1e-5) + mesh.fill_holes(max_hole_perimeter=3e-2) + if verbose: + print(f"After final cleanup: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + + # Step 5: Unify face orientations + mesh.unify_face_orientations() + + # --- Branch 2: Remeshing Pipeline --- + else: + center = aabb.mean(dim=0) + scale = (aabb[1] - aabb[0]).max().item() + resolution = grid_size.max().item() + + # Perform Dual Contouring remeshing (rebuilds topology) + mesh.init(*cumesh.remeshing.remesh_narrow_band_dc( + vertices, faces, + center = center, + scale = (resolution + 3 * remesh_band) / resolution * scale, + resolution = resolution, + band = remesh_band, + project_back = remesh_project, # Snaps vertices back to original surface + verbose = verbose, + bvh = bvh, + )) + if verbose: + print(f"After remeshing: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + + # Simplify and clean the remeshed result (similar logic to above) + mesh.simplify(decimation_target, verbose=verbose) + if verbose: + print(f"After simplifying: {mesh.num_vertices} vertices, {mesh.num_faces} faces") + + if use_tqdm: + pbar.update(1) + if verbose: + print("Done") + + + # --- UV Parameterization --- + if use_tqdm: + pbar.set_description("Parameterizing new mesh") + if verbose: + print("Parameterizing new mesh...") + + out_vertices, out_faces, out_uvs, out_vmaps = mesh.uv_unwrap( + compute_charts_kwargs={ + "threshold_cone_half_angle_rad": mesh_cluster_threshold_cone_half_angle_rad, + "refine_iterations": mesh_cluster_refine_iterations, + "global_iterations": mesh_cluster_global_iterations, + "smooth_strength": mesh_cluster_smooth_strength, + }, + return_vmaps=True, + verbose=verbose, + ) + out_vertices = out_vertices.cuda() + out_faces = out_faces.cuda() + out_uvs = out_uvs.cuda() + out_vmaps = out_vmaps.cuda() + mesh.compute_vertex_normals() + out_normals = mesh.read_vertex_normals()[out_vmaps] + + if use_tqdm: + pbar.update(1) + if verbose: + print("Done") + + # --- Texture Baking (Attribute Sampling) --- + if use_tqdm: + pbar.set_description("Sampling attributes") + if verbose: + print("Sampling attributes...", end='', flush=True) + + # Setup differentiable rasterizer context + ctx = dr.RasterizeCudaContext() + # Prepare UV coordinates for rasterization (rendering in UV space) + uvs_rast = torch.cat([out_uvs * 2 - 1, torch.zeros_like(out_uvs[:, :1]), torch.ones_like(out_uvs[:, :1])], dim=-1).unsqueeze(0) + rast = torch.zeros((1, texture_size, texture_size, 4), device='cuda', dtype=torch.float32) + + # Rasterize in chunks to save memory + for i in range(0, out_faces.shape[0], 100000): + rast_chunk, _ = dr.rasterize( + ctx, uvs_rast, out_faces[i:i+100000], + resolution=[texture_size, texture_size], + ) + mask_chunk = rast_chunk[..., 3:4] > 0 + rast_chunk[..., 3:4] += i # Store face ID in alpha channel + rast = torch.where(mask_chunk, rast_chunk, rast) + + # Mask of valid pixels in texture + mask = rast[0, ..., 3] > 0 + + # Interpolate 3D positions in UV space (finding 3D coord for every texel) + pos = dr.interpolate(out_vertices.unsqueeze(0), rast, out_faces)[0][0] + valid_pos = pos[mask] + + # Map these positions back to the *original* high-res mesh to get accurate attributes + # This corrects geometric errors introduced by simplification/remeshing + _, face_id, uvw = bvh.unsigned_distance(valid_pos, return_uvw=True) + orig_tri_verts = vertices[faces[face_id.long()]] # (N_new, 3, 3) + valid_pos = (orig_tri_verts * uvw.unsqueeze(-1)).sum(dim=1) + + # Trilinear sampling from the attribute volume (Color, Material props) + attrs = torch.zeros(texture_size, texture_size, attr_volume.shape[1], device='cuda') + attrs[mask] = grid_sample_3d( + attr_volume, + torch.cat([torch.zeros_like(coords[:, :1]), coords], dim=-1), + shape=torch.Size([1, attr_volume.shape[1], *grid_size.tolist()]), + grid=((valid_pos - aabb[0]) / voxel_size).reshape(1, -1, 3), + mode='trilinear', + ) + if use_tqdm: + pbar.update(1) + if verbose: + print("Done") + + # --- Texture Post-Processing & Material Construction --- + if use_tqdm: + pbar.set_description("Finalizing mesh") + if verbose: + print("Finalizing mesh...", end='', flush=True) + + mask = mask.cpu().numpy() + + # Extract channels based on layout (BaseColor, Metallic, Roughness, Alpha) + base_color = np.clip(attrs[..., attr_layout['base_color']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + metallic = np.clip(attrs[..., attr_layout['metallic']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + roughness = np.clip(attrs[..., attr_layout['roughness']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + alpha = np.clip(attrs[..., attr_layout['alpha']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + alpha_mode = 'OPAQUE' + + # Inpainting: fill gaps (dilation) to prevent black seams at UV boundaries + mask_inv = (~mask).astype(np.uint8) + base_color = cv2.inpaint(base_color, mask_inv, 3, cv2.INPAINT_TELEA) + metallic = cv2.inpaint(metallic, mask_inv, 1, cv2.INPAINT_TELEA)[..., None] + roughness = cv2.inpaint(roughness, mask_inv, 1, cv2.INPAINT_TELEA)[..., None] + alpha = cv2.inpaint(alpha, mask_inv, 1, cv2.INPAINT_TELEA)[..., None] + + # Create PBR material + # Standard PBR packs Metallic and Roughness into Blue and Green channels + material = trimesh.visual.material.PBRMaterial( + baseColorTexture=Image.fromarray(np.concatenate([base_color, alpha], axis=-1)), + baseColorFactor=np.array([255, 255, 255, 255], dtype=np.uint8), + metallicRoughnessTexture=Image.fromarray(np.concatenate([np.zeros_like(metallic), roughness, metallic], axis=-1)), + metallicFactor=1.0, + roughnessFactor=1.0, + alphaMode=alpha_mode, + doubleSided=True if not remesh else False, + ) + + # --- Coordinate System Conversion & Final Object --- + vertices_np = out_vertices.cpu().numpy() + faces_np = out_faces.cpu().numpy() + uvs_np = out_uvs.cpu().numpy() + normals_np = out_normals.cpu().numpy() + + # Swap Y and Z axes, invert Y (common conversion for GLB compatibility) + vertices_np[:, 1], vertices_np[:, 2] = vertices_np[:, 2], -vertices_np[:, 1] + normals_np[:, 1], normals_np[:, 2] = normals_np[:, 2], -normals_np[:, 1] + uvs_np[:, 1] = 1 - uvs_np[:, 1] # Flip UV V-coordinate + + textured_mesh = trimesh.Trimesh( + vertices=vertices_np, + faces=faces_np, + vertex_normals=normals_np, + process=False, + visual=trimesh.visual.TextureVisuals(uv=uvs_np, material=material) + ) + + if use_tqdm: + pbar.update(1) + pbar.close() + if verbose: + print("Done") + + return textured_mesh \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/rasterize.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/rasterize.py new file mode 100644 index 0000000000000000000000000000000000000000..c27134add4ba1935e03308d82a06ee5e77faa5c3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/rasterize.py @@ -0,0 +1,111 @@ +import torch +import torch.nn.functional as F +from easydict import EasyDict as edict +from . import _C + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = far / (far - near) + ret[2, 3] = near * far / (near - far) + ret[3, 2] = 1. + return ret + + +class VoxelRenderer: + """ + Renderer for the Voxel representation. + + Args: + rendering_options (dict): Rendering options. + """ + + def __init__(self, rendering_options={}) -> None: + self.rendering_options = edict({ + "resolution": None, + "near": 0.1, + "far": 10.0, + "ssaa": 1, + }) + self.rendering_options.update(rendering_options) + + def render( + self, + position: torch.Tensor, + attrs: torch.Tensor, + voxel_size: float, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + ) -> edict: + """ + Render the octree. + + Args: + position (torch.Tensor): (N, 3) xyz positions + attrs (torch.Tensor): (N, C) attributes + voxel_size (float): voxel size + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + + Returns: + edict containing: + attr (torch.Tensor): (C, H, W) rendered color + depth (torch.Tensor): (H, W) rendered depth + alpha (torch.Tensor): (H, W) rendered alpha + """ + resolution = self.rendering_options["resolution"] + near = self.rendering_options["near"] + far = self.rendering_options["far"] + ssaa = self.rendering_options["ssaa"] + + view = extrinsics + perspective = intrinsics_to_projection(intrinsics, near, far) + camera = torch.inverse(view)[:3, 3] + focalx = intrinsics[0, 0] + focaly = intrinsics[1, 1] + args = ( + position, + attrs, + voxel_size, + view.T.contiguous(), + (perspective @ view).T.contiguous(), + camera, + 0.5 / focalx, + 0.5 / focaly, + resolution * ssaa, + resolution * ssaa, + ) + color, depth, alpha = _C.rasterize_voxels_cuda(*args) + + if ssaa > 1: + color = F.interpolate(color[None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + depth = F.interpolate(depth[None, None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + alpha = F.interpolate(alpha[None, None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + + ret = edict({ + 'attr': color, + 'depth': depth, + 'alpha': alpha, + }) + return ret + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/serialize.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..452b5dc89e082cacabb7b12ed3bd443233e0bf80 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/serialize.py @@ -0,0 +1,68 @@ +from typing import * +import torch +from . import _C + + +@torch.no_grad() +def encode_seq(coords: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor: + """ + Encodes 3D coordinates into a 30-bit code. + + Args: + coords: a tensor of shape [N, 3] containing the 3D coordinates. + permute: the permutation of the coordinates. + mode: the encoding mode to use. + """ + assert coords.shape[-1] == 3 and coords.ndim == 2, "Input coordinates must be of shape [N, 3]" + x = coords[:, permute[0]].int() + y = coords[:, permute[1]].int() + z = coords[:, permute[2]].int() + if mode == 'z_order': + if coords.device.type == 'cpu': + return _C.z_order_encode_cpu(x, y, z) + elif coords.device.type == 'cuda': + return _C.z_order_encode_cuda(x, y, z) + else: + raise ValueError(f"Unsupported device type: {coords.device.type}") + elif mode == 'hilbert': + if coords.device.type == 'cpu': + return _C.hilbert_encode_cpu(x, y, z) + elif coords.device.type == 'cuda': + return _C.hilbert_encode_cuda(x, y, z) + else: + raise ValueError(f"Unsupported device type: {coords.device.type}") + else: + raise ValueError(f"Unknown encoding mode: {mode}") + + +@torch.no_grad() +def decode_seq(code: torch.Tensor, permute: List[int] = [0, 1, 2], mode: Literal['z_order', 'hilbert'] = 'z_order') -> torch.Tensor: + """ + Decodes a 30-bit code into 3D coordinates. + + Args: + code: a tensor of shape [N] containing the 30-bit code. + permute: the permutation of the coordinates. + mode: the decoding mode to use. + """ + assert code.ndim == 1, "Input code must be of shape [N]" + if mode == 'z_order': + if code.device.type == 'cpu': + coords = _C.z_order_decode_cpu(code) + elif code.device.type == 'cuda': + coords = _C.z_order_decode_cuda(code) + else: + raise ValueError(f"Unsupported device type: {code.device.type}") + elif mode == 'hilbert': + if code.device.type == 'cpu': + coords = _C.hilbert_decode_cpu(code) + elif code.device.type == 'cuda': + coords = _C.hilbert_decode_cuda(code) + else: + raise ValueError(f"Unsupported device type: {code.device.type}") + else: + raise ValueError(f"Unknown decoding mode: {mode}") + x = coords[permute.index(0)] + y = coords[permute.index(1)] + z = coords[permute.index(2)] + return torch.stack([x, y, z], dim=-1) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/pyproject.toml b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b13d4322c69d02cdf32b2bbf5f88d5f49eeff32 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/pyproject.toml @@ -0,0 +1,34 @@ +[build-system] +requires = [ + "setuptools>=64", + "wheel", + "torch", + "numpy", + "plyfile", + "trimesh", + "tqdm", + "zstandard", + "easydict" +] +build-backend = "setuptools.build_meta" + + +[project] +name = "o_voxel" +version = "0.0.1" +description = "All about voxel." +requires-python = ">=3.8" +authors = [ + { name = "Jianfeng Xiang", email = "belljig@outlook.com" } +] +dependencies = [ + "torch", + "numpy", + "plyfile", + "trimesh", + "tqdm", + "zstandard", + "easydict", + "cumesh @ git+https://github.com/JeffreyXiang/CuMesh.git", + "flex_gemm @ git+https://github.com/JeffreyXiang/FlexGEMM.git", +] diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/setup.py b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..91cb5cecd3e230e8e44adb6c9c742b9c47a6740a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/setup.py @@ -0,0 +1,67 @@ +from setuptools import setup +from torch.utils.cpp_extension import CUDAExtension, BuildExtension, IS_HIP_EXTENSION +import os + +ROOT = os.path.dirname(os.path.abspath(__file__)) +BUILD_TARGET = os.environ.get("BUILD_TARGET", "auto") + +if BUILD_TARGET == "auto": + if IS_HIP_EXTENSION: + IS_HIP = True + else: + IS_HIP = False +else: + if BUILD_TARGET == "cuda": + IS_HIP = False + elif BUILD_TARGET == "rocm": + IS_HIP = True + +if not IS_HIP: + cc_flag = [] +else: + archs = os.getenv("GPU_ARCHS", "native").split(";") + cc_flag = [f"--offload-arch={arch}" for arch in archs] + +setup( + name="o_voxel", + packages=[ + 'o_voxel', + 'o_voxel.convert', + 'o_voxel.io', + ], + ext_modules=[ + CUDAExtension( + name="o_voxel._C", + sources=[ + # Hashmap functions + "src/hash/hash.cu", + # Convert functions + "src/convert/flexible_dual_grid.cpp", + "src/convert/volumetic_attr.cpp", + ## Serialization functions + "src/serialize/api.cu", + "src/serialize/hilbert.cu", + "src/serialize/z_order.cu", + # IO functions + "src/io/svo.cpp", + "src/io/filter_parent.cpp", + "src/io/filter_neighbor.cpp", + # Rasterization functions + "src/rasterize/rasterize.cu", + + # main + "src/ext.cpp", + ], + include_dirs=[ + os.path.join(ROOT, "third_party/eigen"), + ], + extra_compile_args={ + "cxx": ["-O3", "-std=c++17"], + "nvcc": ["-O3","-std=c++17"] + cc_flag, + } + ) + ], + cmdclass={ + 'build_ext': BuildExtension + } +) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/api.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/api.h new file mode 100644 index 0000000000000000000000000000000000000000..b70551c896b1eea7de24375a051ecfa38badf0b5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/api.h @@ -0,0 +1,122 @@ +/* + * O-Voxel Convertion API + * + * Copyright (C) 2025, Jianfeng XIANG + * All rights reserved. + * + * Licensed under The MIT License [see LICENSE for details] + * + * Written by Jianfeng XIANG + */ + +#pragma once +#include + + +/** + * Extract flexible dual grid from a triangle mesh. + * + * @param vertices: Tensor of shape (N, 3) containing vertex positions. + * @param faces: Tensor of shape (M, 3) containing triangle vertex indices. + * @param voxel_size: Tensor of shape (3,) containing the voxel size in each dimension. + * @param grid_range: Tensor of shape (2, 3) containing the minimum and maximum coordinates of the grid range. + * @param face_weight: Weight for the face edges in the QEM computation. + * @param boundary_weight: Weight for the boundary edges in the QEM computation. + * @param regularization_weight: Regularization factor to apply to the QEM matrices. + * @param timing: Boolean flag to indicate whether to print timing information. + * + * @return a tuple ((x, y, z), vertices, intersected, faces) containing the remeshed vertices and the corresponding voxel grid. + */ +std::tuple mesh_to_flexible_dual_grid_cpu( + const torch::Tensor& vertices, + const torch::Tensor& faces, + const torch::Tensor& voxel_size, + const torch::Tensor& grid_range, + float face_weight, + float boundary_weight, + float regularization_weight, + bool timing +); + + +/** + * Voxelizes a triangle mesh with PBR materials + * + * @param voxel_size [3] tensor containing the size of a voxel + * @param grid_range [6] tensor containing the size of the grid + * @param vertices [N_tri, 3, 3] array containing the triangle vertices + * @param normals [N_tri, 3, 3] array containing the triangle vertex normals + * @param uvs [N_tri, 3, 2] tensor containing the texture coordinates + * @param materialIds [N_tri] tensor containing the material ids + * @param baseColorFactor list of [3] tensor containing the base color factor + * @param baseColorTexture list of [H, W, 3] tensor containing the base color texture + * @param baseColorTextureFilter list of int indicating the base color texture filter (0: NEAREST, 1: LINEAR) + * @param baseColorTextureWrap list of int indicating the base color texture wrap (0: REPEAT, 1: CLAMP_TO_EDGE, 2: MIRRORED_REPEAT) + * @param metallicFactor list of float containing the metallic factor + * @param metallicTexture list of [H, W] tensor containing the metallic texture + * @param metallicTextureFilter list of int indicating the metallic texture filter (0: NEAREST, 1: LINEAR) + * @param metallicTextureWrap list of int indicating the metallic texture wrap (0: REPEAT, 1: CLAMP_TO_EDGE, 2: MIRRORED_REPEAT) + * @param roughnessFactor list of float containing the roughness factor + * @param roughnessTexture list of [H, W] tensor containing the roughness texture + * @param roughnessTextureFilter list of int indicating the roughness texture filter (0: NEAREST, 1: LINEAR) + * @param roughnessTextureWrap list of int indicating the roughness texture wrap (0: REPEAT, 1: CLAMP_TO_EDGE, 2: MIRRORED_REPEAT) + * @param emissiveFactor list of [3] tensor containing the emissive factor + * @param emissiveTexture list of [H, W, 3] tensor containing the emissive texture + * @param emissiveTextureFilter list of int indicating the emissive texture filter (0: NEAREST, 1: LINEAR) + * @param emissiveTextureWrap list of int indicating the emissive texture wrap (0: REPEAT, 1: CLAMP_TO_EDGE, 2: MIRRORED_REPEAT) + * @param alphaMode list of int indicating the alpha mode (0: OPAQUE, 1: MASK, 2: BLEND) + * @param alphaCutoff list of float containing the alpha cutoff + * @param alphaFactor list of float containing the alpha factor + * @param alphaTexture list of [H, W] tensor containing the alpha texture + * @param alphaTextureFilter list of int indicating the alpha texture filter (0: NEAREST, 1: LINEAR) + * @param alphaTextureWrap list of int indicating the alpha texture wrap (0: REPEAT, 1: CLAMP_TO_EDGE, 2: MIRRORED_REPEAT) + * @param normalTexture list of [H, W, 3] tensor containing the normal texture + * @param normalTextureFilter list of int indicating the normal texture filter (0: NEAREST, 1: LINEAR) + * @param normalTextureWrap list of int indicating the normal texture wrap (0: REPEAT, 1: CLAMP_TO_EDGE, 2: MIRRORED_REPEAT) + * @param mipLevelOffset float indicating the mip level offset for texture mipmap + * + * @return tuple containing: + * - coords: tensor of shape [N, 3] containing the voxel coordinates + * - out_baseColor: tensor of shape [N, 3] containing the base color of each voxel + * - out_metallic: tensor of shape [N, 1] containing the metallic of each voxel + * - out_roughness: tensor of shape [N, 1] containing the roughness of each voxel + * - out_emissive: tensor of shape [N, 3] containing the emissive of each voxel + * - out_alpha: tensor of shape [N, 1] containing the alpha of each voxel + * - out_normal: tensor of shape [N, 3] containing the normal of each voxel + */ +std::tuple +textured_mesh_to_volumetric_attr_cpu( + const torch::Tensor& voxel_size, + const torch::Tensor& grid_range, + const torch::Tensor& vertices, + const torch::Tensor& normals, + const torch::Tensor& uvs, + const torch::Tensor& materialIds, + const std::vector& baseColorFactor, + const std::vector& baseColorTexture, + const std::vector& baseColorTextureFilter, + const std::vector& baseColorTextureWrap, + const std::vector& metallicFactor, + const std::vector& metallicTexture, + const std::vector& metallicTextureFilter, + const std::vector& metallicTextureWrap, + const std::vector& roughnessFactor, + const std::vector& roughnessTexture, + const std::vector& roughnessTextureFilter, + const std::vector& roughnessTextureWrap, + const std::vector& emissiveFactor, + const std::vector& emissiveTexture, + const std::vector& emissiveTextureFilter, + const std::vector& emissiveTextureWrap, + const std::vector& alphaMode, + const std::vector& alphaCutoff, + const std::vector& alphaFactor, + const std::vector& alphaTexture, + const std::vector& alphaTextureFilter, + const std::vector& alphaTextureWrap, + const std::vector& normalTexture, + const std::vector& normalTextureFilter, + const std::vector& normalTextureWrap, + const float mipLevelOffset, + const bool timing +); diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/flexible_dual_grid.cpp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/flexible_dual_grid.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad89edc01d1efb9d2644f251560c60de243cb1dd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/flexible_dual_grid.cpp @@ -0,0 +1,775 @@ +#include +#include +#include +#include +#include + +#include "api.h" + + +constexpr size_t kInvalidIndex = std::numeric_limits::max(); + + +struct float3 {float x, y, z; float& operator[](int i) {return (&x)[i];}}; +struct int3 {int x, y, z; int& operator[](int i) {return (&x)[i];}}; +struct int4 {int x, y, z, w; int& operator[](int i) {return (&x)[i];}}; +struct bool3 {bool x, y, z; bool& operator[](int i) {return (&x)[i];}}; + + +template +static inline U lerp(const T& a, const T& b, const T& t, const U& val_a, const U& val_b) { + if (a == b) return val_a; // Avoid divide by zero + T alpha = (t - a) / (b - a); + return (1 - alpha) * val_a + alpha * val_b; +} + + +template +static auto get_or_default(const Map& map, const Key& key, const Default& default_val) -> typename Map::mapped_type { + auto it = map.find(key); + return (it != map.end()) ? it->second : default_val; +} + + +// 3D voxel coordinate +struct VoxelCoord { + int x, y, z; + + int& operator[](int i) { + return (&x)[i]; + } + + bool operator==(const VoxelCoord& other) const { + return x == other.x && y == other.y && z == other.z; + } +}; + +// Hash function for VoxelCoord to use in unordered_map +namespace std { +template <> +struct hash { + size_t operator()(const VoxelCoord& v) const { + const std::size_t p1 = 73856093; + const std::size_t p2 = 19349663; + const std::size_t p3 = 83492791; + return (std::size_t)(v.x) * p1 ^ (std::size_t)(v.y) * p2 ^ (std::size_t)(v.z) * p3; + } +}; +} + + +void intersect_qef( + const Eigen::Vector3f& voxel_size, + const Eigen::Vector3i& grid_min, + const Eigen::Vector3i& grid_max, + const std::vector& triangles, // 3 vertices per triangle + std::unordered_map& hash_table, // Hash table for voxel lookup + std::vector& voxels, // Output: Voxel coordinates + std::vector& means, // Output: Mean vertex positions for each voxel + std::vector& cnt, // Output: Number of intersections for each voxel + std::vector& intersected, // Output: Whether edge of voxel intersects with triangle + std::vector& qefs // Output: QEF matrices for each voxel +) { + const size_t N_tri = triangles.size() / 3; + + for (size_t i = 0; i < N_tri; ++i) { + const Eigen::Vector3f& v0 = triangles[i * 3 + 0]; + const Eigen::Vector3f& v1 = triangles[i * 3 + 1]; + const Eigen::Vector3f& v2 = triangles[i * 3 + 2]; + + // Compute edge vectors and face normal + Eigen::Vector3f e0 = v1 - v0; + Eigen::Vector3f e1 = v2 - v1; + Eigen::Vector3f n = e0.cross(e1).normalized(); + Eigen::Vector4f plane; + plane << n.x(), n.y(), n.z(), -n.dot(v0); + auto Q = plane * plane.transpose(); + + // Scan-line algorithm to find intersections with the voxel grid from three directions + /* + t0 + | \ + | t1 + | / + t2 + */ + auto scan_line_fill = [&] (const int ax2) { + int ax0 = (ax2 + 1) % 3; + int ax1 = (ax2 + 2) % 3; + + // Canonical question + std::array t = { + Eigen::Vector3d(v0[ax0], v0[ax1], v0[ax2]), + Eigen::Vector3d(v1[ax0], v1[ax1], v1[ax2]), + Eigen::Vector3d(v2[ax0], v2[ax1], v2[ax2]) + }; + std::sort(t.begin(), t.end(), [](const Eigen::Vector3d& a, const Eigen::Vector3d& b) { return a.y() < b.y(); }); + + // Scan-line algorithm + int start = std::clamp(int(t[0].y() / voxel_size[ax1]), grid_min[ax1], grid_max[ax1] - 1); + int mid = std::clamp(int(t[1].y() / voxel_size[ax1]), grid_min[ax1], grid_max[ax1] - 1); + int end = std::clamp(int(t[2].y() / voxel_size[ax1]), grid_min[ax1], grid_max[ax1] - 1); + + auto scan_line_half = [&] (const int row_start, const int row_end, const Eigen::Vector3d t0, const Eigen::Vector3d t1, const Eigen::Vector3d t2) { + /* + t0 + | \ + t3-t4 + | \ + t1---t2 + */ + for (int y_idx = row_start; y_idx < row_end; ++y_idx) { + double y = (y_idx + 1) * voxel_size[ax1]; + Eigen::Vector2d t3 = lerp(t0.y(), t1.y(), y, Eigen::Vector2d(t0.x(), t0.z()), Eigen::Vector2d(t1.x(), t1.z())); + Eigen::Vector2d t4 = lerp(t0.y(), t2.y(), y, Eigen::Vector2d(t0.x(), t0.z()), Eigen::Vector2d(t2.x(), t2.z())); + if (t3.x() > t4.x()) std::swap(t3, t4); + int line_start = std::clamp(int(t3.x() / voxel_size[ax0]), grid_min[ax0], grid_max[ax0] - 1); + int line_end = std::clamp(int(t4.x() / voxel_size[ax0]), grid_min[ax0], grid_max[ax0] - 1); + for (int x_idx = line_start; x_idx < line_end; ++x_idx) { + double x = (x_idx + 1) * voxel_size[ax0]; + double z = lerp(t3.x(), t4.x(), x, t3.y(), t4.y()); + int z_idx = int(z / voxel_size[ax2]); + if (z_idx >= grid_min[ax2] && z_idx < grid_max[ax2]) { + // For 4-connected voxels + for (int dx = 0; dx < 2; ++dx) { + for (int dy = 0; dy < 2; ++dy) { + VoxelCoord coord; + coord[ax0] = x_idx + dx; coord[ax1] = y_idx + dy; coord[ax2] = z_idx; + Eigen::Vector3d intersect; + intersect[ax0] = x; intersect[ax1] = y; intersect[ax2] = z; + auto kv = hash_table.find(coord); + if (kv == hash_table.end()) { + hash_table[coord] = voxels.size(); + voxels.push_back({coord.x, coord.y, coord.z}); + means.push_back(intersect.cast()); + cnt.push_back(1); + intersected.push_back({false, false, false}); + qefs.push_back(Q); + if (dx == 0 && dy == 0) + intersected.back()[ax2] = true; + } + else { + auto i = kv->second; + means[i] += intersect.cast(); + cnt[i] += 1; + if (dx == 0 && dy == 0) + intersected[i][ax2] = true; + qefs[i] += Q; + } + } + } + } + } + } + }; + scan_line_half(start, mid, t[0], t[1], t[2]); + scan_line_half(mid, end, t[2], t[1], t[0]); + }; + scan_line_fill(0); + scan_line_fill(1); + scan_line_fill(2); + } +} + + +void face_qef( + const Eigen::Vector3f& voxel_size, + const Eigen::Vector3i& grid_min, + const Eigen::Vector3i& grid_max, + const std::vector& triangles, // 3 vertices per triangle + std::unordered_map& hash_table, // Hash table for voxel lookup + std::vector& qefs // Output: QEF matrices for each voxel +) { + const size_t N_tri = triangles.size() / 3; + + for (size_t i = 0; i < N_tri; ++i) { + const Eigen::Vector3f& v0 = triangles[i * 3 + 0]; + const Eigen::Vector3f& v1 = triangles[i * 3 + 1]; + const Eigen::Vector3f& v2 = triangles[i * 3 + 2]; + + // Compute edge vectors and face normal + Eigen::Vector3f e0 = v1 - v0; + Eigen::Vector3f e1 = v2 - v1; + Eigen::Vector3f e2 = v0 - v2; + Eigen::Vector3f n = e0.cross(e1).normalized(); + Eigen::Vector4f plane; + plane << n.x(), n.y(), n.z(), -n.dot(v0); + auto Q = plane * plane.transpose(); + + // Compute triangle bounding box in voxel coordinates + Eigen::Vector3f bb_min_f = v0.cwiseMin(v1).cwiseMin(v2).cwiseQuotient(voxel_size); + Eigen::Vector3f bb_max_f = v0.cwiseMax(v1).cwiseMax(v2).cwiseQuotient(voxel_size); + + Eigen::Vector3i bb_min(std::max(static_cast(bb_min_f.x()), grid_min.x()), + std::max(static_cast(bb_min_f.y()), grid_min.y()), + std::max(static_cast(bb_min_f.z()), grid_min.z())); + Eigen::Vector3i bb_max(std::min(static_cast(bb_max_f.x() + 1), grid_max.x()), + std::min(static_cast(bb_max_f.y() + 1), grid_max.y()), + std::min(static_cast(bb_max_f.z() + 1), grid_max.z())); + + // Plane test setup + Eigen::Vector3f c( + n.x() > 0.0f ? voxel_size.x() : 0.0f, + n.y() > 0.0f ? voxel_size.y() : 0.0f, + n.z() > 0.0f ? voxel_size.z() : 0.0f + ); + float d1 = n.dot(c - v0); + float d2 = n.dot(voxel_size - c - v0); + + // XY plane projection test setup + int mul_xy = (n.z() < 0.0f) ? -1 : 1; + Eigen::Vector2f n_xy_e0(-mul_xy * e0.y(), mul_xy * e0.x()); + Eigen::Vector2f n_xy_e1(-mul_xy * e1.y(), mul_xy * e1.x()); + Eigen::Vector2f n_xy_e2(-mul_xy * e2.y(), mul_xy * e2.x()); + + float d_xy_e0 = -n_xy_e0.dot(v0.head<2>()) + n_xy_e0.cwiseMax(0.0f).dot(voxel_size.head<2>()); + float d_xy_e1 = -n_xy_e1.dot(v1.head<2>()) + n_xy_e1.cwiseMax(0.0f).dot(voxel_size.head<2>()); + float d_xy_e2 = -n_xy_e2.dot(v2.head<2>()) + n_xy_e2.cwiseMax(0.0f).dot(voxel_size.head<2>()); + + // YZ plane projection test setup + int mul_yz = (n.x() < 0.0f) ? -1 : 1; + Eigen::Vector2f n_yz_e0(-mul_yz * e0.z(), mul_yz * e0.y()); + Eigen::Vector2f n_yz_e1(-mul_yz * e1.z(), mul_yz * e1.y()); + Eigen::Vector2f n_yz_e2(-mul_yz * e2.z(), mul_yz * e2.y()); + + float d_yz_e0 = -n_yz_e0.dot(Eigen::Vector2f(v0.y(), v0.z())) + n_yz_e0.cwiseMax(0.0f).dot(Eigen::Vector2f(voxel_size.y(), voxel_size.z())); + float d_yz_e1 = -n_yz_e1.dot(Eigen::Vector2f(v1.y(), v1.z())) + n_yz_e1.cwiseMax(0.0f).dot(Eigen::Vector2f(voxel_size.y(), voxel_size.z())); + float d_yz_e2 = -n_yz_e2.dot(Eigen::Vector2f(v2.y(), v2.z())) + n_yz_e2.cwiseMax(0.0f).dot(Eigen::Vector2f(voxel_size.y(), voxel_size.z())); + + // ZX plane projection test setup + int mul_zx = (n.y() < 0.0f) ? -1 : 1; + Eigen::Vector2f n_zx_e0(-mul_zx * e0.x(), mul_zx * e0.z()); + Eigen::Vector2f n_zx_e1(-mul_zx * e1.x(), mul_zx * e1.z()); + Eigen::Vector2f n_zx_e2(-mul_zx * e2.x(), mul_zx * e2.z()); + + float d_zx_e0 = -n_zx_e0.dot(Eigen::Vector2f(v0.z(), v0.x())) + n_zx_e0.cwiseMax(0.0f).dot(Eigen::Vector2f(voxel_size.z(), voxel_size.x())); + float d_zx_e1 = -n_zx_e1.dot(Eigen::Vector2f(v1.z(), v1.x())) + n_zx_e1.cwiseMax(0.0f).dot(Eigen::Vector2f(voxel_size.z(), voxel_size.x())); + float d_zx_e2 = -n_zx_e2.dot(Eigen::Vector2f(v2.z(), v2.x())) + n_zx_e2.cwiseMax(0.0f).dot(Eigen::Vector2f(voxel_size.z(), voxel_size.x())); + + // Loop over candidate voxels inside bounding box + for (int z = bb_min.z(); z < bb_max.z(); ++z) { + for (int y = bb_min.y(); y < bb_max.y(); ++y) { + for (int x = bb_min.x(); x < bb_max.x(); ++x) { + // Voxel center + Eigen::Vector3f p = voxel_size.cwiseProduct(Eigen::Vector3f(x, y, z)); + + // Plane through box test + float nDOTp = n.dot(p); + if (((nDOTp + d1) * (nDOTp + d2)) > 0.0f) continue; + + // XY projection test + Eigen::Vector2f p_xy(p.x(), p.y()); + if (n_xy_e0.dot(p_xy) + d_xy_e0 < 0) continue; + if (n_xy_e1.dot(p_xy) + d_xy_e1 < 0) continue; + if (n_xy_e2.dot(p_xy) + d_xy_e2 < 0) continue; + + // YZ projection test + Eigen::Vector2f p_yz(p.y(), p.z()); + if (n_yz_e0.dot(p_yz) + d_yz_e0 < 0) continue; + if (n_yz_e1.dot(p_yz) + d_yz_e1 < 0) continue; + if (n_yz_e2.dot(p_yz) + d_yz_e2 < 0) continue; + + // ZX projection test + Eigen::Vector2f p_zx(p.z(), p.x()); + if (n_zx_e0.dot(p_zx) + d_zx_e0 < 0) continue; + if (n_zx_e1.dot(p_zx) + d_zx_e1 < 0) continue; + if (n_zx_e2.dot(p_zx) + d_zx_e2 < 0) continue; + + // Passed all tests — mark voxel + auto coord = VoxelCoord{x, y, z}; + auto kv = hash_table.find(coord); + if (kv != hash_table.end()) { + qefs[kv->second] += Q; + } + } + } + } + } +} + + +void boundry_qef( + const Eigen::Vector3f& voxel_size, + const Eigen::Vector3i& grid_min, + const Eigen::Vector3i& grid_max, + const std::vector& boundries, // 2 vertices per segment + const float boundary_weight, // Weight for boundary edges + std::unordered_map& hash_table, // Hash table for voxel lookup + std::vector& qefs // Output: QEF matrices for each voxel +) { + for (size_t i = 0; i < boundries.size() / 2; ++i) { + const Eigen::Vector3f& v0 = boundries[i * 2 + 0]; + const Eigen::Vector3f& v1 = boundries[i * 2 + 1]; + + // Calculate the QEF for the edge (boundary) defined by v0 and v1 + Eigen::Vector3d dir(v1.x() - v0.x(), v1.y() - v0.y(), v1.z() - v0.z()); + double segment_length = dir.norm(); + if (segment_length < 1e-6d) continue; // Skip degenerate edges (zero-length) + dir.normalize(); // unit direction vector + + // Projection matrix orthogonal to the direction: I - d d^T + Eigen::Matrix3f A = Eigen::Matrix3f::Identity() - (dir * dir.transpose()).cast(); + + // b = -A * v0 + Eigen::Vector3f b = -A * v0; + + // c = v0^T * A * v0 + float c = v0.transpose() * A * v0; + + // Now pack this into a 4x4 QEF matrix + Eigen::Matrix4f Q = Eigen::Matrix4f::Zero(); + Q.block<3, 3>(0, 0) = A; + Q.block<3, 1>(0, 3) = b; + Q.block<1, 3>(3, 0) = b.transpose(); + Q(3, 3) = c; + + // DDA Traversal logic directly inside the function + + // Starting and ending voxel coordinates + Eigen::Vector3i v0_voxel = (v0.cwiseQuotient(voxel_size)).array().floor().cast(); + Eigen::Vector3i v1_voxel = (v1.cwiseQuotient(voxel_size)).array().floor().cast(); + + // Determine step direction for each axis based on the line direction + Eigen::Vector3i step = (dir.array() > 0).select(Eigen::Vector3i(1, 1, 1), Eigen::Vector3i(-1, -1, -1)); + + Eigen::Vector3d tMax, tDelta; + for (int axis = 0; axis < 3; ++axis) { + if (dir[axis] == 0.0d) { + tMax[axis] = std::numeric_limits::infinity(); + tDelta[axis] = std::numeric_limits::infinity(); + } else { + float voxel_border = voxel_size[axis] * (v0_voxel[axis] + (step[axis] > 0 ? 1 : 0)); + tMax[axis] = (voxel_border - v0[axis]) / dir[axis]; + tDelta[axis] = voxel_size[axis] / std::abs(dir[axis]); + } + } + + // Current voxel position + Eigen::Vector3i current = v0_voxel; + + // Store the voxel we start at + std::vector voxels; + voxels.push_back({current.x(), current.y(), current.z()}); + + // Traverse the voxels + while (true) { + int axis; + if (tMax.x() < tMax.y()) { + axis = (tMax.x() < tMax.z()) ? 0 : 2; + } else { + axis = (tMax.y() < tMax.z()) ? 1 : 2; + } + + if (tMax[axis] > segment_length) break; + + current[axis] += step[axis]; + tMax[axis] += tDelta[axis]; + + voxels.push_back({current.x(), current.y(), current.z()}); + } + + // Accumulate QEF for each voxel passed through + for (const auto& coord : voxels) { + // Make sure the voxel is within bounds + if ((coord.x < grid_min.x() || coord.x >= grid_max.x()) || + (coord.y < grid_min.y() || coord.y >= grid_max.y()) || + (coord.z < grid_min.z() || coord.z >= grid_max.z())) continue; + if (!hash_table.count(coord)) continue; // Skip if voxel not in hash table + + // Accumulate the QEF for this voxel + qefs[hash_table[coord]] += boundary_weight * Q; // Scale by boundary weight + } + } +} + + +std::array quad_to_2tri( + const std::vector& vertices, + const int4& quad_indices +) { + int ia = quad_indices.x; + int ib = quad_indices.y; + int ic = quad_indices.z; + int id = quad_indices.w; + + Eigen::Vector3f a(vertices[ia].x, vertices[ia].y, vertices[ia].z); + Eigen::Vector3f b(vertices[ib].x, vertices[ib].y, vertices[ib].z); + Eigen::Vector3f c(vertices[ic].x, vertices[ic].y, vertices[ic].z); + Eigen::Vector3f d(vertices[id].x, vertices[id].y, vertices[id].z); + + // diagonal AC + Eigen::Vector3f n_abc = (b - a).cross(c - a).normalized(); + Eigen::Vector3f n_acd = (c - a).cross(d - a).normalized(); + float angle_ac = std::acos(std::clamp(n_abc.dot(n_acd), -1.0f, 1.0f)); + + // diagonal BD + Eigen::Vector3f n_abd = (b - a).cross(d - a).normalized(); + Eigen::Vector3f n_bcd = (c - b).cross(d - b).normalized(); + float angle_bd = std::acos(std::clamp(n_abd.dot(n_bcd), -1.0f, 1.0f)); + + if (angle_ac <= angle_bd) { + return {int3{ia, ib, ic}, int3{ia, ic, id}}; + } else { + return {int3{ia, ib, id}, int3{ib, ic, id}}; + } +} + + +void face_from_dual_vertices( + const std::unordered_map& hash_table, + const std::vector& voxels, + const std::vector& dual_vertices, + const std::vector& intersected, + std::vector& face_indices +) { + for (int i = 0; i < dual_vertices.size(); ++i) { + int3 coord = voxels[i]; + bool3 is_intersected = intersected[i]; + + // Check existence of neighboring 6 voxels + size_t neigh_indices[6] = { + get_or_default(hash_table, VoxelCoord{coord.x + 1, coord.y, coord.z}, kInvalidIndex), + get_or_default(hash_table, VoxelCoord{coord.x, coord.y + 1, coord.z}, kInvalidIndex), + get_or_default(hash_table, VoxelCoord{coord.x + 1, coord.y + 1, coord.z}, kInvalidIndex), + get_or_default(hash_table, VoxelCoord{coord.x, coord.y, coord.z + 1}, kInvalidIndex), + get_or_default(hash_table, VoxelCoord{coord.x + 1, coord.y, coord.z + 1}, kInvalidIndex), + get_or_default(hash_table, VoxelCoord{coord.x, coord.y + 1, coord.z + 1}, kInvalidIndex) + }; + + // xy-plane + if (is_intersected[2] && neigh_indices[0] != kInvalidIndex && neigh_indices[1] != kInvalidIndex && neigh_indices[2] != kInvalidIndex) { + int4 quad_indices{i, neigh_indices[0], neigh_indices[2], neigh_indices[1]}; + auto tri_indices = quad_to_2tri(dual_vertices, quad_indices); + face_indices.insert(face_indices.end(), tri_indices.begin(), tri_indices.end()); + } + // yz-plane + if (is_intersected[0] && neigh_indices[1] != kInvalidIndex && neigh_indices[3] != kInvalidIndex && neigh_indices[5] != kInvalidIndex) { + int4 quad_indices{i, neigh_indices[1], neigh_indices[5], neigh_indices[3]}; + auto tri_indices = quad_to_2tri(dual_vertices, quad_indices); + face_indices.insert(face_indices.end(), tri_indices.begin(), tri_indices.end()); + } + // xz-plane + if (is_intersected[1] && neigh_indices[0] != kInvalidIndex && neigh_indices[3] != kInvalidIndex && neigh_indices[4] != kInvalidIndex) { + int4 quad_indices{i, neigh_indices[0], neigh_indices[4], neigh_indices[3]}; + auto tri_indices = quad_to_2tri(dual_vertices, quad_indices); + face_indices.insert(face_indices.end(), tri_indices.begin(), tri_indices.end()); + } + } +} + +/** + * Extract flexible dual grid from a triangle mesh. + * + * @param vertices: Tensor of shape (N, 3) containing vertex positions. + * @param faces: Tensor of shape (M, 3) containing triangle vertex indices. + * @param voxel_size: Tensor of shape (3,) containing the voxel size in each dimension. + * @param grid_range: Tensor of shape (2, 3) containing the minimum and maximum coordinates of the grid range. + * @param face_weight: Weight for the face edges in the QEF computation. + * @param boundary_weight: Weight for the boundary edges in the QEF computation. + * @param regularization_weight: Regularization factor to apply to the QEF matrices. + * @param timing: Boolean flag to indicate whether to print timing information. + * + * @return a tuple ((x, y, z), vertices, intersected, faces) containing the remeshed vertices and the corresponding voxel grid. + */ +std::tuple mesh_to_flexible_dual_grid_cpu( + const torch::Tensor& vertices, + const torch::Tensor& faces, + const torch::Tensor& voxel_size, + const torch::Tensor& grid_range, + float face_weight, + float boundary_weight, + float regularization_weight, + bool timing +) { + const int F = faces.size(0); + const float* v_ptr = vertices.data_ptr(); + const int* f_ptr = faces.data_ptr(); + const float* voxel_size_ptr = voxel_size.data_ptr(); + const int* grid_range_ptr = grid_range.data_ptr(); + clock_t start, end; + std::unordered_map hash_table; + std::vector voxels; // Voxel coordinates + std::vector means; // Mean vertex positions for each voxel + std::vector cnt; // Number of intersections for each voxel + std::vector intersected; // Indicate whether edges of voxels intersect with surface + std::vector qefs; // QEF matrices for each voxel + + // Convert tensors to Eigen types + Eigen::Vector3f e_voxel_size(voxel_size_ptr[0], voxel_size_ptr[1], voxel_size_ptr[2]); + Eigen::Vector3i e_grid_min(grid_range_ptr[0], grid_range_ptr[1], grid_range_ptr[2]); + Eigen::Vector3i e_grid_max(grid_range_ptr[3], grid_range_ptr[4], grid_range_ptr[5]); + + // Intersect QEF computation + start = clock(); + std::vector triangles; + triangles.reserve(F * 3); + for (int f = 0; f < F; ++f) { + for (int v = 0; v < 3; ++v) { + triangles.push_back(Eigen::Vector3f( + v_ptr[f_ptr[f * 3 + v] * 3 + 0], + v_ptr[f_ptr[f * 3 + v] * 3 + 1], + v_ptr[f_ptr[f * 3 + v] * 3 + 2] + )); + } + } + intersect_qef(e_voxel_size, e_grid_min, e_grid_max, triangles, hash_table, voxels, means, cnt, intersected, qefs); + end = clock(); + if (timing) std::cout << "Intersect QEF computation took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + + // Face QEF computation + if (face_weight > 0.0f) { + start = clock(); + face_qef(e_voxel_size, e_grid_min, e_grid_max, triangles, hash_table, qefs); + end = clock(); + if (timing) std::cout << "Face QEF computation took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + } + + // Boundary QEF computation + if (boundary_weight > 0.0f) { + start = clock(); + std::map, int> edge_count; + for (int f = 0; f < F; ++f) { + for (int v0 = 0; v0 < 3; ++v0) { + int e0 = f_ptr[f * 3 + v0]; + int e1 = f_ptr[f * 3 + (v0 + 1) % 3]; + if (e0 > e1) std::swap(e0, e1); + edge_count[std::make_pair(e0, e1)]++; + } + } + std::vector boundries; + for (const auto& e : edge_count) { + if (e.second == 1) { + int v0 = e.first.first; + int v1 = e.first.second; + boundries.push_back(Eigen::Vector3f( + v_ptr[v0 * 3 + 0], + v_ptr[v0 * 3 + 1], + v_ptr[v0 * 3 + 2] + )); + boundries.push_back(Eigen::Vector3f( + v_ptr[v1 * 3 + 0], + v_ptr[v1 * 3 + 1], + v_ptr[v1 * 3 + 2] + )); + } + } + boundry_qef(e_voxel_size, e_grid_min, e_grid_max, boundries, boundary_weight, hash_table, qefs); + end = clock(); + if (timing) std::cout << "Boundary QEF computation took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + } + + // Solve the QEF system to obtain final dual vertices + start = clock(); + std::vector dual_vertices(voxels.size()); + for (int i = 0; i < voxels.size(); ++i) { + int3 coord = voxels[i]; + Eigen::Matrix4f Q = qefs[i]; + float min_corner[3] = { + coord.x * e_voxel_size.x(), + coord.y * e_voxel_size.y(), + coord.z * e_voxel_size.z() + }; + float max_corner[3] = { + (coord.x + 1) * e_voxel_size.x(), + (coord.y + 1) * e_voxel_size.y(), + (coord.z + 1) * e_voxel_size.z() + }; + + // Add regularization term + if (regularization_weight > 0.0f) { + Eigen::Vector3f p = means[i] / cnt[i]; + + // Construct the QEF matrix for this vertex + Eigen::Matrix4f Qreg = Eigen::Matrix4f::Zero(); + Qreg.topLeftCorner<3,3>() = Eigen::Matrix3f::Identity(); + Qreg.block<3,1>(0,3) = -p; + Qreg.block<1,3>(3,0) = -p.transpose(); + Qreg(3,3) = p.dot(p); + + Q += regularization_weight * cnt[i] * Qreg; // Scale by regularization weight + } + + // Solve unconstrained + Eigen::Matrix3f A = Q.topLeftCorner<3, 3>(); + Eigen::Vector3f b = -Q.block<3, 1>(0, 3); + Eigen::Vector3f v_new = A.colPivHouseholderQr().solve(b); + + if (!( + v_new.x() >= min_corner[0] && v_new.x() <= max_corner[0] && + v_new.y() >= min_corner[1] && v_new.y() <= max_corner[1] && + v_new.z() >= min_corner[2] && v_new.z() <= max_corner[2] + )) { + // Starting enumeration of constraints + float best = std::numeric_limits::infinity(); + + // Solve single-constraint + auto solve_single_constraint = [&](int fixed_axis) { + int ax1 = (fixed_axis + 1) % 3; + int ax2 = (fixed_axis + 2) % 3; + + Eigen::Matrix2f A; + Eigen::Matrix2f B; + Eigen::Vector2f q, b, x; + + A << Q(ax1, ax1), Q(ax1, ax2), + Q(ax2, ax1), Q(ax2, ax2); + B << Q(ax1, fixed_axis), Q(ax1, 3), + Q(ax2, fixed_axis), Q(ax2, 3); + auto Asol = A.colPivHouseholderQr(); + + // if lower bound + q << min_corner[fixed_axis], 1; + b = -B * q; + x = Asol.solve(b); + if ( + x.x() >= min_corner[ax1] && x.x() <= max_corner[ax1] && + x.y() >= min_corner[ax2] && x.y() <= max_corner[ax2] + ) { + Eigen::Vector4f p; + p[fixed_axis] = min_corner[fixed_axis]; + p[ax1] = x.x(); + p[ax2] = x.y(); + p[3] = 1.0f; + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + + // if upper bound + q << max_corner[fixed_axis], 1; + b = -B * q; + x = Asol.solve(b); + if ( + x.x() >= min_corner[ax1] && x.x() <= max_corner[ax1] && + x.y() >= min_corner[ax2] && x.y() <= max_corner[ax2] + ) { + Eigen::Vector4f p; + p[fixed_axis] = max_corner[fixed_axis]; + p[ax1] = x.x(); + p[ax2] = x.y(); + p[3] = 1.0f; + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + }; + solve_single_constraint(0); // fix x + solve_single_constraint(1); // fix y + solve_single_constraint(2); // fix z + + // Solve two-constraint + auto solve_two_constraint = [&](int free_axis) { + int ax1 = (free_axis + 1) % 3; + int ax2 = (free_axis + 2) % 3; + + float a, x; + Eigen::Vector3f b, q; + + a = Q(free_axis, free_axis); + b << Q(free_axis, ax1), Q(free_axis, ax2), Q(free_axis, 3); + + // if lower-lower bound + q << min_corner[ax1], min_corner[ax2], 1; + x = -(b.dot(q)) / a; + if (x >= min_corner[free_axis] && x <= max_corner[free_axis]) { + Eigen::Vector4f p; + p[free_axis] = x; + p[ax1] = min_corner[ax1]; + p[ax2] = min_corner[ax2]; + p[3] = 1.0f; + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + + // if lower-upper bound + q << min_corner[ax1], max_corner[ax2], 1; + x = -(b.dot(q)) / a; + if (x >= min_corner[free_axis] && x <= max_corner[free_axis]) { + Eigen::Vector4f p; + p[free_axis] = x; + p[ax1] = min_corner[ax1]; + p[ax2] = max_corner[ax2]; + p[3] = 1.0f; + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + + // if upper-lower bound + q << max_corner[ax1], min_corner[ax2], 1; + x = -(b.dot(q)) / a; + if (x >= min_corner[free_axis] && x <= max_corner[free_axis]) { + Eigen::Vector4f p; + p[free_axis] = x; + p[ax1] = max_corner[ax1]; + p[ax2] = min_corner[ax2]; + p[3] = 1.0f; + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + + // if upper-upper bound + q << max_corner[ax1], max_corner[ax2], 1; + x = -(b.dot(q)) / a; + if (x >= min_corner[free_axis] && x <= max_corner[free_axis]) { + Eigen::Vector4f p; + p[free_axis] = x; + p[ax1] = max_corner[ax1]; + p[ax2] = max_corner[ax2]; + p[3] = 1.0f; + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + }; + solve_two_constraint(0); // free x + solve_two_constraint(1); // free y + solve_two_constraint(2); // free z + + // Solve three-constraint + for (int x_constraint = 0; x_constraint < 2; ++x_constraint) { + for (int y_constraint = 0; y_constraint < 2; ++y_constraint) { + for (int z_constraint = 0; z_constraint < 2; ++z_constraint) { + Eigen::Vector4f p; + p[0] = x_constraint ? min_corner[0] : max_corner[0]; + p[1] = y_constraint ? min_corner[1] : max_corner[1]; + p[2] = z_constraint ? min_corner[2] : max_corner[2]; + p[3] = 1.0f; + + float err = p.transpose() * Q * p; + if (err < best) { + best = err; + v_new << p[0], p[1], p[2]; + } + } + } + } + } + + // Store the dual vertex and voxel grid coordinates + dual_vertices[i] = float3{v_new.x(), v_new.y(), v_new.z()}; + } + end = clock(); + if (timing) std::cout << "Dual vertices computation took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + + return std::make_tuple( + torch::from_blob(voxels.data(), {int(voxels .size()), 3}, torch::kInt32).clone(), + torch::from_blob(dual_vertices.data(), {int(dual_vertices.size()), 3}, torch::kFloat32).clone(), + torch::from_blob(intersected.data(), {int(intersected.size()), 3}, torch::kBool).clone() + ); +} + diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/volumetic_attr.cpp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/volumetic_attr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64c3d0984500128fbd82a68341a47e8acd6fb6cf --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/convert/volumetic_attr.cpp @@ -0,0 +1,872 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "api.h" + + +constexpr size_t kInvalidIndex = std::numeric_limits::max(); + + +static bool is_power_of_two(int n) { + return n > 0 && (n & (n - 1)) == 0; +} + + +template +static inline U lerp(const T& a, const T& b, const T& t, const U& val_a, const U& val_b) { + if (a == b) return val_a; // Avoid divide by zero + T alpha = (t - a) / (b - a); + return (1 - alpha) * val_a + alpha * val_b; +} + + +template +static auto get_or_default(const Map& map, const Key& key, const Default& default_val) -> typename Map::mapped_type { + auto it = map.find(key); + return (it != map.end()) ? it->second : default_val; +} + + +// 3D voxel coordinate +struct VoxelCoord { + int x, y, z; + + int& operator[](int i) { + return (&x)[i]; + } + + bool operator==(const VoxelCoord& other) const { + return x == other.x && y == other.y && z == other.z; + } +}; + +// Hash function for VoxelCoord to use in unordered_map +namespace std { +template <> +struct hash { + size_t operator()(const VoxelCoord& v) const { + const std::size_t p1 = 73856093; + const std::size_t p2 = 19349663; + const std::size_t p3 = 83492791; + return (std::size_t)(v.x) * p1 ^ (std::size_t)(v.y) * p2 ^ (std::size_t)(v.z) * p3; + } +}; +} + + +/** + * Compute the Normal Tangent and Bitangent vectors for a triangle. + * + * @param v0 The first vertex of the triangle. + * @param v1 The second vertex of the triangle. + * @param v2 The third vertex of the triangle. + * @param uv0 The texture coordinates of the first vertex. + * @param uv1 The texture coordinates of the second vertex. + * @param uv2 The texture coordinates of the third vertex. + * + * @return A tuple containing: + * - t The tangent vector. + * - b The bitangent vector. + * - n The normal vector. + * - mip_length The norms of the partial derivatives of the 3D coordinates with respect to the 2D texture coordinates. + */ +static std::tuple compute_TBN( + const Eigen::Vector3f& v0, + const Eigen::Vector3f& v1, + const Eigen::Vector3f& v2, + const Eigen::Vector2f& uv0, + const Eigen::Vector2f& uv1, + const Eigen::Vector2f& uv2 +) { + Eigen::Vector3f e1 = v1 - v0; + Eigen::Vector3f e2 = v2 - v0; + Eigen::Vector2f duv1 = uv1 - uv0; + Eigen::Vector2f duv2 = uv2 - uv0; + Eigen::Vector3f n = e1.cross(e2).normalized(); + + float det = duv1.x() * duv2.y() - duv1.y() * duv2.x(); + if (fabs(det) < 1e-6) { + // Use default + Eigen::Vector3f t(1.0f, 0.0f, 0.0f); + Eigen::Vector3f b(0.0f, 1.0f, 0.0f); + Eigen::Vector2f mip_length(1e6, 1e6); + return std::make_tuple(t, b, n, mip_length); + } + + float invDet = 1.0f / det; + Eigen::Vector3f t = (duv2.y() * e1 - duv1.y() * e2); + Eigen::Vector3f b = (duv1.x() * e2 - duv2.x() * e1); + float t_norm = t.norm(); + float b_norm = b.norm(); + t = t / t_norm; + b = b / b_norm; + Eigen::Vector2f mip_length(invDet * t_norm, invDet * b_norm); + + return std::make_tuple(t, b, n, mip_length); +} + + +/** + * Project a point onto a triangle defined by three vertices. + * + * @param p The point to project. + * @param a The first vertex of the triangle. + * @param b The second vertex of the triangle. + * @param c The third vertex of the triangle. + * @param n The normal of the triangle. + * + * @return The projected point represented as barycentric coordinates (u, v, w) and distance from the plane. + */ +static Eigen::Vector4f project_onto_triangle( + const Eigen::Vector3f& p, + const Eigen::Vector3f& a, + const Eigen::Vector3f& b, + const Eigen::Vector3f& c, + const Eigen::Vector3f& n +) { + float d = (p - a).dot(n); + + Eigen::Vector3f p_proj = p - d * n; + Eigen::Vector3f ab = b - a; + Eigen::Vector3f ac = c - a; + Eigen::Vector3f ap = p_proj - a; + + float d00 = ab.dot(ab); + float d01 = ab.dot(ac); + float d11 = ac.dot(ac); + float d20 = ap.dot(ab); + float d21 = ap.dot(ac); + + float denom = d00 * d11 - d01 * d01; + float v = (d11 * d20 - d01 * d21) / denom; + float w = (d00 * d21 - d01 * d20) / denom; + float u = 1.0f - v - w; + + return Eigen::Vector4f(u, v, w, d); +} + + +static inline int wrap_texcoord(const int& x, const int& W, const int& filter) { + if (filter == 0) { // REPEAT + return (x % W + W) % W; + } else if (filter == 1) { // CLAMP_TO_EDGE + return std::max(0, std::min(x, W - 1)); + } else if (filter == 2) { // MIRROR_REPEAT + int period = 2 * W; + int x_mod = (x % period + period) % period; + return (x_mod < W) ? x_mod : (period - x_mod - 1); + } else { + // Default to repeat + return (x % W + W) % W; + } +} + + +static std::vector> build_mipmaps( + const uint8_t* texture, + const int& H, const int& W, const int& C +) { + if (H != W || !is_power_of_two(H)) { + throw std::invalid_argument("Texture width and height must be equal and a power of two."); + } + std::vector> mipmaps; + const uint8_t* cur_map = texture; + int cur_H = H; + int cur_W = W; + int next_H = cur_H >> 1; + int next_W = cur_W >> 1; + while (next_H > 0 && next_W > 0) { + std::vector next_map(next_H * next_W * C); + for (int y = 0; y < next_H; y++) { + for (int x = 0; x < next_W; x++) { + for (int c = 0; c < C; c++) { + size_t sum = 0; + size_t xx = static_cast(x) << 1; + size_t yy = static_cast(y) << 1; + sum += cur_map[yy * static_cast(cur_W) * C + xx * C + c]; + sum += cur_map[(yy + 1) * static_cast(cur_W) * C + xx * C + c]; + sum += cur_map[yy * static_cast(cur_W) * C + (xx + 1) * C + c]; + sum += cur_map[(yy + 1) * static_cast(cur_W) * C + (xx + 1) * C + c]; + next_map[y * next_W * C + x * C + c] = static_cast(sum / 4); + } + } + } + mipmaps.push_back(std::move(next_map)); + cur_map = mipmaps.back().data(); + cur_H = next_H; + cur_W = next_W; + next_H = cur_H >> 1; + next_W = cur_W >> 1; + } + return mipmaps; +} + + +static void sample_texture( + const uint8_t* texture, + const int& H, const int& W, const int& C, + const float& u, const float& v, + const int& filter, const int& wrap, + float* color +) { + float x = u * W; + float y = (1 - v) * H; + if (filter == 0) { // NEAREST + int x_int = floorf(x); + int y_int = floorf(y); + x_int = wrap_texcoord(x_int, W, wrap); + y_int = wrap_texcoord(y_int, H, wrap); + for (int c = 0; c < C; c++) { + color[c] = texture[y_int * W * C + x_int * C + c] / 255.0f; + } + } + else { // LINEAR + int x_low = floorf(x - 0.5); + int x_high = x_low + 1; + int y_low = floorf(y - 0.5); + int y_high = y_low + 1; + float w_x = x - x_low - 0.5; + float w_y = y - y_low - 0.5; + x_low = wrap_texcoord(x_low, W, wrap); + x_high = wrap_texcoord(x_high, W, wrap); + y_low = wrap_texcoord(y_low, H, wrap); + y_high = wrap_texcoord(y_high, H, wrap); + for (int c = 0; c < C; c++) { + color[c] = (1 - w_x) * (1 - w_y) * texture[y_low * W * C + x_low * C + c] + + w_x * (1 - w_y) * texture[y_low * W * C + x_high * C + c] + + (1 - w_x) * w_y * texture[y_high * W * C + x_low * C + c] + + w_x * w_y * texture[y_high * W * C + x_high * C + c]; + color[c] /= 255.0f; + } + } +} + + +static void sample_texture_mipmap( + const uint8_t* texture, + const int& H, const int& W, const int& C, + const std::vector>& mipmaps, + const float& u, const float& v, const float& mip_length, const float& mipLevelOffset, + const int& filter, const int& wrap, + float* color +) { + if (filter == 0) { // NEAREST + sample_texture(texture, H, W, C, u, v, filter, wrap, color); + } + else { // LINEAR + float mip_level = std::log2(mip_length * H) + mipLevelOffset; + if (!std::isfinite(mip_level) || mip_level <= 0 || mipmaps.empty()) { + sample_texture(texture, H, W, C, u, v, filter, wrap, color); + } + else if (mip_level >= mipmaps.size()) { + sample_texture(mipmaps[mipmaps.size() - 1].data(), H >> mipmaps.size(), W >> mipmaps.size(), C, u, v, filter, wrap, color); + } + else { + int lower_mip_level = std::floor(mip_level); + int upper_mip_level = lower_mip_level + 1; + float mip_frac = mip_level - lower_mip_level; + const uint8_t* lower_mip_ptr = lower_mip_level == 0 ? texture : mipmaps[lower_mip_level - 1].data(); + const uint8_t* upper_mip_ptr = mipmaps[upper_mip_level - 1].data(); + int lower_mip_H = H >> lower_mip_level; + int lower_mip_W = W >> lower_mip_level; + int upper_mip_H = H >> upper_mip_level; + int upper_mip_W = W >> upper_mip_level; + std::vector lower_mip_sample(C); + std::vector upper_mip_sample(C); + sample_texture(lower_mip_ptr, lower_mip_H, lower_mip_W, C, u, v, filter, wrap, lower_mip_sample.data()); + sample_texture(upper_mip_ptr, upper_mip_H, upper_mip_W, C, u, v, filter, wrap, upper_mip_sample.data()); + for (int c = 0; c < C; c++) { + color[c] = (1 - mip_frac) * lower_mip_sample[c] + mip_frac * upper_mip_sample[c]; + } + } + } +} + + +static std::tuple, std::vector, std::vector, std::vector, std::vector, std::vector, std::vector> +voxelize_trimesh_pbr_impl( + const float* voxel_size, + const int* grid_range, + const int N_tri, + const float* vertices, + const float* normals, + const float* uvs, + const int* materialIds, + const std::vector baseColorFactor, + const std::vector baseColorTexture, + const std::vector H_bcTex, const std::vector W_bcTex, + const std::vector baseColorTextureFilter, + const std::vector baseColorTextureWrap, + const std::vector metallicFactor, + const std::vector metallicTexture, + const std::vector H_mtlTex, const std::vector W_mtlTex, + const std::vector metallicTextureFilter, + const std::vector metallicTextureWrap, + const std::vector roughnessFactor, + const std::vector roughnessTexture, + const std::vector H_rghTex, const std::vector W_rghTex, + const std::vector roughnessTextureFilter, + const std::vector roughnessTextureWrap, + const std::vector emissiveFactor, + const std::vector emissiveTexture, + const std::vector H_emTex, const std::vector W_emTex, + const std::vector emissiveTextureFilter, + const std::vector emissiveTextureWrap, + const std::vector alphaMode, + const std::vector alphaCutoff, + const std::vector alphaFactor, + const std::vector alphaTexture, + const std::vector H_aTex, const std::vector W_aTex, + const std::vector alphaTextureFilter, + const std::vector alphaTextureWrap, + const std::vector normalTexture, + const std::vector H_nTex, const std::vector W_nTex, + const std::vector normalTextureFilter, + const std::vector normalTextureWrap, + const float mipLevelOffset, + const bool timing +) { + clock_t start, end; + + // Common variables used in the voxelization process + Eigen::Vector3f delta_p(voxel_size[0], voxel_size[1], voxel_size[2]); + Eigen::Vector3i grid_min(grid_range[0], grid_range[1], grid_range[2]); + Eigen::Vector3i grid_max(grid_range[3], grid_range[4], grid_range[5]); + + // Construct Mipmaps + start = clock(); + std::vector>> baseColorMipmaps(baseColorTexture.size()); + std::vector>> metallicMipmaps(metallicTexture.size()); + std::vector>> roughnessMipmaps(roughnessTexture.size()); + std::vector>> emissiveMipmaps(emissiveTexture.size()); + std::vector>> alphaMipmaps(alphaTexture.size()); + std::vector>> normalMipmaps(normalTexture.size()); + for (size_t i = 0; i < baseColorTexture.size(); i++) { + if (baseColorTexture[i] != nullptr && baseColorTextureFilter[i] != 0) { + baseColorMipmaps[i] = build_mipmaps(baseColorTexture[i], H_bcTex[i], W_bcTex[i], 3); + } + } + for (size_t i = 0; i < metallicTexture.size(); i++) { + if (metallicTexture[i] != nullptr && metallicTextureFilter[i] != 0) { + metallicMipmaps[i] = build_mipmaps(metallicTexture[i], H_mtlTex[i], W_mtlTex[i], 1); + } + } + for (size_t i = 0; i < roughnessTexture.size(); i++) { + if (roughnessTexture[i] != nullptr && roughnessTextureFilter[i] != 0) { + roughnessMipmaps[i] = build_mipmaps(roughnessTexture[i], H_rghTex[i], W_rghTex[i], 1); + } + } + for (size_t i = 0; i < emissiveTexture.size(); i++) { + if (emissiveTexture[i] != nullptr && emissiveTextureFilter[i] != 0) { + emissiveMipmaps[i] = build_mipmaps(emissiveTexture[i], H_emTex[i], W_emTex[i], 3); + } + } + for (size_t i = 0; i < alphaTexture.size(); i++) { + if (alphaTexture[i] != nullptr && alphaTextureFilter[i] != 0) { + alphaMipmaps[i] = build_mipmaps(alphaTexture[i], H_aTex[i], W_aTex[i], 1); + } + } + for (size_t i = 0; i < normalTexture.size(); i++) { + if (normalTexture[i] != nullptr && normalTextureFilter[i] != 0) { + normalMipmaps[i] = build_mipmaps(normalTexture[i], H_nTex[i], W_nTex[i], 3); + } + } + end = clock(); + if (timing) std::cout << "Mipmaps construction took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + + // Buffers + std::unordered_map hash_table; + std::vector coords; + std::vector buf_weights; + std::vector buf_baseColors; + std::vector buf_metallics; + std::vector buf_roughnesses; + std::vector buf_emissives; + std::vector buf_alphas; + std::vector buf_normals; + + // Enumerate all triangles + start = clock(); + for (size_t tid = 0; tid < N_tri; tid++) { + // COMPUTE COMMON TRIANGLE PROPERTIES + // Move vertices to origin using bbox + size_t ptr = tid * 9; + Eigen::Vector3f v0(vertices[ptr], vertices[ptr + 1], vertices[ptr + 2]); + Eigen::Vector3f v1(vertices[ptr + 3], vertices[ptr + 4], vertices[ptr + 5]); + Eigen::Vector3f v2(vertices[ptr + 6], vertices[ptr + 7], vertices[ptr + 8]); + // Normals + Eigen::Vector3f n0(normals[ptr], normals[ptr + 1], normals[ptr + 2]); + Eigen::Vector3f n1(normals[ptr + 3], normals[ptr + 4], normals[ptr + 5]); + Eigen::Vector3f n2(normals[ptr + 6], normals[ptr + 7], normals[ptr + 8]); + // UV vectors + ptr = tid * 6; + Eigen::Vector2f uv0(uvs[ptr], uvs[ptr + 1]); + Eigen::Vector2f uv1(uvs[ptr + 2], uvs[ptr + 3]); + Eigen::Vector2f uv2(uvs[ptr + 4], uvs[ptr + 5]); + // TBN + auto tbn = compute_TBN(v0, v1, v2, uv0, uv1, uv2); + Eigen::Vector3f t = std::get<0>(tbn); + Eigen::Vector3f b = std::get<1>(tbn); + Eigen::Vector3f n = std::get<2>(tbn); + Eigen::Vector2f v_mip_length = std::get<3>(tbn); + float mip_length = delta_p.maxCoeff() / std::sqrt(v_mip_length.x() * v_mip_length.y()); + // Material ID + int mid = materialIds[tid]; + + // Find intersected voxel for each triangle + std::unordered_set intersected_voxels; + // Scan-line algorithm to find intersections with the voxel grid from three directions + /* + t0 + | \ + | t1 + | / + t2 + */ + auto scan_line_fill = [&] (const int ax2) { + int ax0 = (ax2 + 1) % 3; + int ax1 = (ax2 + 2) % 3; + + // Canonical question + std::array t = { + Eigen::Vector3d(v0[ax0], v0[ax1], v0[ax2]), + Eigen::Vector3d(v1[ax0], v1[ax1], v1[ax2]), + Eigen::Vector3d(v2[ax0], v2[ax1], v2[ax2]) + }; + std::sort(t.begin(), t.end(), [](const Eigen::Vector3d& a, const Eigen::Vector3d& b) { return a.y() < b.y(); }); + + // Scan-line algorithm + int start = std::clamp(int(t[0].y() / voxel_size[ax1]), grid_min[ax1], grid_max[ax1] - 1); + int mid = std::clamp(int(t[1].y() / voxel_size[ax1]), grid_min[ax1], grid_max[ax1] - 1); + int end = std::clamp(int(t[2].y() / voxel_size[ax1]), grid_min[ax1], grid_max[ax1] - 1); + + auto scan_line_half = [&] (const int row_start, const int row_end, const Eigen::Vector3d t0, const Eigen::Vector3d t1, const Eigen::Vector3d t2) { + /* + t0 + | \ + t3-t4 + | \ + t1---t2 + */ + for (int y_idx = row_start; y_idx < row_end; ++y_idx) { + double y = (y_idx + 1) * voxel_size[ax1]; + Eigen::Vector2d t3 = lerp(t0.y(), t1.y(), y, Eigen::Vector2d(t0.x(), t0.z()), Eigen::Vector2d(t1.x(), t1.z())); + Eigen::Vector2d t4 = lerp(t0.y(), t2.y(), y, Eigen::Vector2d(t0.x(), t0.z()), Eigen::Vector2d(t2.x(), t2.z())); + if (t3.x() > t4.x()) std::swap(t3, t4); + int line_start = std::clamp(int(t3.x() / voxel_size[ax0]), grid_min[ax0], grid_max[ax0] - 1); + int line_end = std::clamp(int(t4.x() / voxel_size[ax0]), grid_min[ax0], grid_max[ax0] - 1); + for (int x_idx = line_start; x_idx < line_end; ++x_idx) { + double x = (x_idx + 1) * voxel_size[ax0]; + double z = lerp(t3.x(), t4.x(), x, t3.y(), t4.y()); + int z_idx = int(z / voxel_size[ax2]); + if (z_idx >= grid_min[ax2] && z_idx < grid_max[ax2]) { + // For 4-connected voxels + for (int dx = 0; dx < 2; ++dx) { + for (int dy = 0; dy < 2; ++dy) { + VoxelCoord coord; + coord[ax0] = x_idx + dx; coord[ax1] = y_idx + dy; coord[ax2] = z_idx; + intersected_voxels.insert(coord); + } + } + } + } + } + }; + scan_line_half(start, mid, t[0], t[1], t[2]); + scan_line_half(mid, end, t[2], t[1], t[0]); + }; + scan_line_fill(0); + scan_line_fill(1); + scan_line_fill(2); + + // For all intersected voxels, ample texture and write to voxel grid + for (auto voxel : intersected_voxels) { + int x = voxel.x; + int y = voxel.y; + int z = voxel.z; + + // Compute barycentric coordinates and weight + Eigen::Vector4f barycentric = project_onto_triangle( + Eigen::Vector3f((x + 0.5f) * delta_p.x(), (y + 0.5f) * delta_p.y(), (z + 0.5f) * delta_p.z()), + v0, v1, v2, n + ); + Eigen::Vector2f uv = { + barycentric.x() * uv0.x() + barycentric.y() * uv1.x() + barycentric.z() * uv2.x(), + barycentric.x() * uv0.y() + barycentric.y() * uv1.y() + barycentric.z() * uv2.y() + }; + Eigen::Vector3f int_n = { + barycentric.x() * n0.x() + barycentric.y() * n1.x() + barycentric.z() * n2.x(), + barycentric.x() * n0.y() + barycentric.y() * n1.y() + barycentric.z() * n2.y(), + barycentric.x() * n0.z() + barycentric.y() * n1.z() + barycentric.z() * n2.z() + }; + float weight = 1 - barycentric.w(); + + /// base color + float baseColor[3] = {1, 1, 1}; + if (baseColorTexture[mid]) { + sample_texture_mipmap( + baseColorTexture[mid], + H_bcTex[mid], W_bcTex[mid], 3, + baseColorMipmaps[mid], + uv.x(), uv.y(), mip_length, mipLevelOffset, + baseColorTextureFilter[mid], baseColorTextureWrap[mid], + baseColor + ); + } + baseColor[0] *= baseColorFactor[mid][0]; + baseColor[1] *= baseColorFactor[mid][1]; + baseColor[2] *= baseColorFactor[mid][2]; + + /// metallic + float metallic = 1.0f; + if (metallicTexture[mid]) { + sample_texture_mipmap( + metallicTexture[mid], + H_mtlTex[mid], W_mtlTex[mid], 1, + metallicMipmaps[mid], + uv.x(), uv.y(), mip_length, mipLevelOffset, + metallicTextureFilter[mid], metallicTextureWrap[mid], + &metallic + ); + } + metallic *= metallicFactor[mid]; + + /// roughness + float roughness = 1.0f; + if (roughnessTexture[mid]) { + sample_texture_mipmap( + roughnessTexture[mid], + H_rghTex[mid], W_rghTex[mid], 1, + roughnessMipmaps[mid], + uv.x(), uv.y(), mip_length, mipLevelOffset, + roughnessTextureFilter[mid], roughnessTextureWrap[mid], + &roughness + ); + } + roughness *= roughnessFactor[mid]; + + /// emissive + float emissive[3] = {1, 1, 1}; + if (emissiveTexture[mid]) { + sample_texture_mipmap( + emissiveTexture[mid], + H_emTex[mid], W_emTex[mid], 3, + roughnessMipmaps[mid], + uv.x(), uv.y(), mip_length, mipLevelOffset, + emissiveTextureFilter[mid], emissiveTextureWrap[mid], + emissive + ); + } + emissive[0] *= emissiveFactor[mid][0]; + emissive[1] *= emissiveFactor[mid][1]; + emissive[2] *= emissiveFactor[mid][2]; + + /// alpha + float alpha = 1.0f; + if (alphaMode[mid] != 0) { + if (alphaTexture[mid]) { + sample_texture_mipmap( + alphaTexture[mid], + H_aTex[mid], W_aTex[mid], 1, + alphaMipmaps[mid], + uv.x(), uv.y(), mip_length, mipLevelOffset, + alphaTextureFilter[mid], alphaTextureWrap[mid], + &alpha + ); + } + alpha *= alphaFactor[mid]; + if (alphaMode[mid] == 1) { // MASK + alpha = alpha < alphaCutoff[mid] ? 0.0f : 1.0f; + } + } + + /// normal + float normal[3] = {int_n.x(), int_n.y(), int_n.z()}; + if (normalTexture[mid]) { + sample_texture_mipmap( + normalTexture[mid], + H_nTex[mid], W_nTex[mid], 3, + normalMipmaps[mid], + uv.x(), uv.y(), mip_length, mipLevelOffset, + normalTextureFilter[mid], normalTextureWrap[mid], + normal + ); + normal[0] = normal[0] * 2 - 1; + normal[1] = normal[1] * 2 - 1; + normal[2] = normal[2] * 2 - 1; + Eigen::Vector3f _n = (normal[0] * t + normal[1] * b + normal[2] * int_n).normalized(); + normal[0] = _n.x(); + normal[1] = _n.y(); + normal[2] = _n.z(); + } + + // Write to voxel grid + auto coord = VoxelCoord{x-grid_min.x(), y-grid_min.y(), z-grid_min.z()}; + auto kv = hash_table.find(coord); + if (kv == hash_table.end()) { + hash_table[coord] = coords.size(); + coords.push_back({coord.x, coord.y, coord.z}); + buf_weights.push_back(weight); + buf_baseColors.push_back(Eigen::Vector3f(baseColor[0], baseColor[1], baseColor[2]) * weight); + buf_metallics.push_back(metallic * weight); + buf_roughnesses.push_back(roughness * weight); + buf_emissives.push_back(Eigen::Vector3f(emissive[0], emissive[1], emissive[2]) * weight); + buf_alphas.push_back(alpha * weight); + buf_normals.push_back(Eigen::Vector3f(normal[0], normal[1], normal[2]) * weight); + } + else { + auto i = kv->second; + buf_weights[i] += weight; + buf_baseColors[i] += Eigen::Vector3f(baseColor[0], baseColor[1], baseColor[2]) * weight; + buf_metallics[i] += metallic * weight; + buf_roughnesses[i] += roughness * weight; + buf_emissives[i] += Eigen::Vector3f(emissive[0], emissive[1], emissive[2]) * weight; + buf_alphas[i] += alpha * weight; + buf_normals[i] += Eigen::Vector3f(normal[0], normal[1], normal[2]) * weight; + } + } + } + end = clock(); + if (timing) std::cout << "Voxelization took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + + // Normalize buffers + start = clock(); + std::vector out_coord(coords.size() * 3); + std::vector out_baseColor(coords.size() * 3); + std::vector out_metallic(coords.size()); + std::vector out_roughness(coords.size()); + std::vector out_emissive(coords.size() * 3); + std::vector out_alpha(coords.size()); + std::vector out_normal(coords.size() * 3); + for (int i = 0; i < coords.size(); i++) { + out_coord[i * 3 + 0] = coords[i].x; + out_coord[i * 3 + 1] = coords[i].y; + out_coord[i * 3 + 2] = coords[i].z; + out_baseColor[i * 3 + 0] = buf_baseColors[i].x() / buf_weights[i]; + out_baseColor[i * 3 + 1] = buf_baseColors[i].y() / buf_weights[i]; + out_baseColor[i * 3 + 2] = buf_baseColors[i].z() / buf_weights[i]; + out_metallic[i] = buf_metallics[i] / buf_weights[i]; + out_roughness[i] = buf_roughnesses[i] / buf_weights[i]; + out_emissive[i * 3 + 0] = buf_emissives[i].x() / buf_weights[i]; + out_emissive[i * 3 + 1] = buf_emissives[i].y() / buf_weights[i]; + out_emissive[i * 3 + 2] = buf_emissives[i].z() / buf_weights[i]; + out_alpha[i] = buf_alphas[i] / buf_weights[i]; + out_normal[i * 3 + 0] = buf_normals[i].x() / buf_weights[i]; + out_normal[i * 3 + 1] = buf_normals[i].y() / buf_weights[i]; + out_normal[i * 3 + 2] = buf_normals[i].z() / buf_weights[i]; + } + end = clock(); + if (timing) std::cout << "Normalization took " << double(end - start) / CLOCKS_PER_SEC << " seconds." << std::endl; + + return std::make_tuple( + std::move(out_coord), + std::move(out_baseColor), + std::move(out_metallic), + std::move(out_roughness), + std::move(out_emissive), + std::move(out_alpha), + std::move(out_normal) + ); +} + + +std::tuple +textured_mesh_to_volumetric_attr_cpu( + const torch::Tensor& voxel_size, + const torch::Tensor& grid_range, + const torch::Tensor& vertices, + const torch::Tensor& normals, + const torch::Tensor& uvs, + const torch::Tensor& materialIds, + const std::vector& baseColorFactor, + const std::vector& baseColorTexture, + const std::vector& baseColorTextureFilter, + const std::vector& baseColorTextureWrap, + const std::vector& metallicFactor, + const std::vector& metallicTexture, + const std::vector& metallicTextureFilter, + const std::vector& metallicTextureWrap, + const std::vector& roughnessFactor, + const std::vector& roughnessTexture, + const std::vector& roughnessTextureFilter, + const std::vector& roughnessTextureWrap, + const std::vector& emissiveFactor, + const std::vector& emissiveTexture, + const std::vector& emissiveTextureFilter, + const std::vector& emissiveTextureWrap, + const std::vector& alphaMode, + const std::vector& alphaCutoff, + const std::vector& alphaFactor, + const std::vector& alphaTexture, + const std::vector& alphaTextureFilter, + const std::vector& alphaTextureWrap, + const std::vector& normalTexture, + const std::vector& normalTextureFilter, + const std::vector& normalTextureWrap, + const float mipLevelOffset, + const bool timing +) { + auto N_mat = baseColorFactor.size(); + int N_tri = vertices.size(0); + + // Get the size of the input tensors + std::vector baseColorFactor_ptrs(N_mat); + std::vector baseColorTexture_ptrs(N_mat); + std::vector H_bcTex(N_mat), W_bcTex(N_mat); + std::vector metallicFactor_vec(N_mat); + std::vector metallicTexture_ptrs(N_mat); + std::vector H_mtlTex(N_mat), W_mtlTex(N_mat); + std::vector roughnessFactor_vec(N_mat); + std::vector roughnessTexture_ptrs(N_mat); + std::vector H_rghTex(N_mat), W_rghTex(N_mat); + std::vector emissiveFactor_ptrs(N_mat); + std::vector emissiveTexture_ptrs(N_mat); + std::vector H_emTex(N_mat), W_emTex(N_mat); + std::vector alphaMode_vec(N_mat); + std::vector alphaCutoff_vec(N_mat); + std::vector alphaFactor_vec(N_mat); + std::vector alphaTexture_ptrs(N_mat); + std::vector H_aTex(N_mat), W_aTex(N_mat); + std::vector normalTexture_ptrs(N_mat); + std::vector H_nTex(N_mat), W_nTex(N_mat); + + for (int i = 0; i < N_mat; ++i) { + baseColorFactor_ptrs[i] = baseColorFactor[i].contiguous().data_ptr(); + if (baseColorTexture[i].numel() > 0) { + baseColorTexture_ptrs[i] = baseColorTexture[i].contiguous().data_ptr(); + H_bcTex[i] = baseColorTexture[i].size(0); + W_bcTex[i] = baseColorTexture[i].size(1); + } + else { + baseColorTexture_ptrs[i] = nullptr; + H_bcTex[i] = 0; + W_bcTex[i] = 0; + } + metallicFactor_vec[i] = metallicFactor[i]; + if (metallicTexture[i].numel() > 0) { + metallicTexture_ptrs[i] = metallicTexture[i].contiguous().data_ptr(); + H_mtlTex[i] = metallicTexture[i].size(0); + W_mtlTex[i] = metallicTexture[i].size(1); + } + else { + metallicTexture_ptrs[i] = nullptr; + H_mtlTex[i] = 0; + W_mtlTex[i] = 0; + } + roughnessFactor_vec[i] = roughnessFactor[i]; + if (roughnessTexture[i].numel() > 0) { + roughnessTexture_ptrs[i] = roughnessTexture[i].contiguous().data_ptr(); + H_rghTex[i] = roughnessTexture[i].size(0); + W_rghTex[i] = roughnessTexture[i].size(1); + } + else { + roughnessTexture_ptrs[i] = nullptr; + H_rghTex[i] = 0; + W_rghTex[i] = 0; + } + emissiveFactor_ptrs[i] = emissiveFactor[i].contiguous().data_ptr(); + if (emissiveTexture[i].numel() > 0) { + emissiveTexture_ptrs[i] = emissiveTexture[i].contiguous().data_ptr(); + H_emTex[i] = emissiveTexture[i].size(0); + W_emTex[i] = emissiveTexture[i].size(1); + } + else { + emissiveTexture_ptrs[i] = nullptr; + H_emTex[i] = 0; + W_emTex[i] = 0; + } + alphaMode_vec[i] = alphaMode[i]; + alphaCutoff_vec[i] = alphaCutoff[i]; + alphaFactor_vec[i] = alphaFactor[i]; + if (alphaTexture[i].numel() > 0) { + alphaTexture_ptrs[i] = alphaTexture[i].contiguous().data_ptr(); + H_aTex[i] = alphaTexture[i].size(0); + W_aTex[i] = alphaTexture[i].size(1); + } + else { + alphaTexture_ptrs[i] = nullptr; + H_aTex[i] = 0; + W_aTex[i] = 0; + } + if (normalTexture[i].numel() > 0) { + normalTexture_ptrs[i] = normalTexture[i].contiguous().data_ptr(); + H_nTex[i] = normalTexture[i].size(0); + W_nTex[i] = normalTexture[i].size(1); + } + else { + normalTexture_ptrs[i] = nullptr; + H_nTex[i] = 0; + W_nTex[i] = 0; + } + } + + auto outputs = voxelize_trimesh_pbr_impl( + voxel_size.contiguous().data_ptr(), + grid_range.contiguous().data_ptr(), + N_tri, + vertices.contiguous().data_ptr(), + normals.contiguous().data_ptr(), + uvs.contiguous().data_ptr(), + materialIds.contiguous().data_ptr(), + baseColorFactor_ptrs, + baseColorTexture_ptrs, + H_bcTex, W_bcTex, + baseColorTextureFilter, baseColorTextureWrap, + metallicFactor_vec, + metallicTexture_ptrs, + H_mtlTex, W_mtlTex, + metallicTextureFilter, metallicTextureWrap, + roughnessFactor_vec, + roughnessTexture_ptrs, + H_rghTex, W_rghTex, + roughnessTextureFilter, roughnessTextureWrap, + emissiveFactor_ptrs, + emissiveTexture_ptrs, + H_emTex, W_emTex, + emissiveTextureFilter, emissiveTextureWrap, + alphaMode_vec, + alphaCutoff_vec, + alphaFactor_vec, + alphaTexture_ptrs, + H_aTex, W_aTex, + alphaTextureFilter, alphaTextureWrap, + normalTexture_ptrs, + H_nTex, W_nTex, + normalTextureFilter, normalTextureWrap, + mipLevelOffset, + timing + ); + + std::vector coords_vec = std::get<0>(outputs); + std::vector baseColors_vec = std::get<1>(outputs); + std::vector metallics_vec = std::get<2>(outputs); + std::vector roughnesses_vec = std::get<3>(outputs); + std::vector emissives_vec = std::get<4>(outputs); + std::vector alphas_vec = std::get<5>(outputs); + std::vector normals_vec = std::get<6>(outputs); + + // Create output tensors + auto out_coords = torch::from_blob(coords_vec.data(), {static_cast(coords_vec.size() / 3), 3}, torch::kInt32).clone(); + auto out_baseColors = torch::from_blob(baseColors_vec.data(), {static_cast(baseColors_vec.size() / 3), 3}, torch::kFloat32).clone(); + auto out_metallics = torch::from_blob(metallics_vec.data(), {static_cast(metallics_vec.size())}, torch::kFloat32).clone(); + auto out_roughnesses = torch::from_blob(roughnesses_vec.data(), {static_cast(roughnesses_vec.size())}, torch::kFloat32).clone(); + auto out_emissives = torch::from_blob(emissives_vec.data(), {static_cast(emissives_vec.size() / 3), 3}, torch::kFloat32).clone(); + auto out_alphas = torch::from_blob(alphas_vec.data(), {static_cast(alphas_vec.size())}, torch::kFloat32).clone(); + auto out_normals = torch::from_blob(normals_vec.data(), {static_cast(normals_vec.size() / 3), 3}, torch::kFloat32).clone(); + + return std::make_tuple( + out_coords, + out_baseColors, + out_metallics, + out_roughnesses, + out_emissives, + out_alphas, + out_normals + ); +} + diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/ext.cpp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/ext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2ac946de4ccc50206c104899cb7e9d59c76177b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/ext.cpp @@ -0,0 +1,37 @@ +#include +#include "hash/api.h" +#include "convert/api.h" +#include "io/api.h" +#include "serialize/api.h" +#include "rasterize/api.h" + + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + // Hash functions + m.def("hashmap_insert_cuda", &hashmap_insert_cuda); + m.def("hashmap_lookup_cuda", &hashmap_lookup_cuda); + m.def("hashmap_insert_3d_cuda", &hashmap_insert_3d_cuda); + m.def("hashmap_lookup_3d_cuda", &hashmap_lookup_3d_cuda); + m.def("hashmap_insert_3d_idx_as_val_cuda", &hashmap_insert_3d_idx_as_val_cuda); + // Convert functions + m.def("mesh_to_flexible_dual_grid_cpu", &mesh_to_flexible_dual_grid_cpu, py::call_guard()); + m.def("textured_mesh_to_volumetric_attr_cpu", &textured_mesh_to_volumetric_attr_cpu, py::call_guard()); + // Serialization functions + m.def("z_order_encode_cpu", &z_order_encode_cpu, py::call_guard()); + m.def("z_order_decode_cpu", &z_order_decode_cpu, py::call_guard()); + m.def("hilbert_encode_cpu", &hilbert_encode_cpu, py::call_guard()); + m.def("hilbert_decode_cpu", &hilbert_decode_cpu, py::call_guard()); + m.def("z_order_encode_cuda", &z_order_encode_cuda, py::call_guard()); + m.def("z_order_decode_cuda", &z_order_decode_cuda, py::call_guard()); + m.def("hilbert_encode_cuda", &hilbert_encode_cuda, py::call_guard()); + m.def("hilbert_decode_cuda", &hilbert_decode_cuda, py::call_guard()); + // IO functions + m.def("encode_sparse_voxel_octree_cpu", &encode_sparse_voxel_octree_cpu, py::call_guard()); + m.def("decode_sparse_voxel_octree_cpu", &decode_sparse_voxel_octree_cpu, py::call_guard()); + m.def("encode_sparse_voxel_octree_attr_parent_cpu", &encode_sparse_voxel_octree_attr_parent_cpu, py::call_guard()); + m.def("decode_sparse_voxel_octree_attr_parent_cpu", &decode_sparse_voxel_octree_attr_parent_cpu, py::call_guard()); + m.def("encode_sparse_voxel_octree_attr_neighbor_cpu", &encode_sparse_voxel_octree_attr_neighbor_cpu, py::call_guard()); + m.def("decode_sparse_voxel_octree_attr_neighbor_cpu", &decode_sparse_voxel_octree_attr_neighbor_cpu, py::call_guard()); + // Rasterization functions + m.def("rasterize_voxels_cuda", &rasterize_voxels_cuda); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/api.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/api.h new file mode 100644 index 0000000000000000000000000000000000000000..7693667b591c2c3f1fd871ba4a57020530aec755 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/api.h @@ -0,0 +1,111 @@ +/* + * Hashmap + * + * Copyright (C) 2025, Jianfeng XIANG + * All rights reserved. + * + * Licensed under The MIT License [see LICENSE for details] + * + * Written by Jianfeng XIANG + */ + +#pragma once +#include + + +#define BLOCK_SIZE 256 + + +/** + * Insert keys into the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param keys [M] uint32/uint64 tensor containing the keys to be inserted + * @param values [M] uint32/uint64 tensor containing the values to be inserted + */ +void hashmap_insert_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& keys, + const torch::Tensor& values +); + + +/** + * Lookup keys in the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param keys [M] uint32/uint64 tensor containing the keys to be looked up + * @return [M] uint32/uint64 tensor containing the values of the keys + */ +torch::Tensor hashmap_lookup_cuda( + const torch::Tensor& hashmap_keys, + const torch::Tensor& hashmap_values, + const torch::Tensor& keys +); + + +/** + * Insert 3D coordinates into the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param coords [M, 4] int32 tensor containing the keys to be inserted + * @param values [M] uint32/uint64 tensor containing the values to be inserted + * @param W the number of width dimensions + * @param H the number of height dimensions + * @param D the number of depth dimensions + */ +void hashmap_insert_3d_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& coords, + const torch::Tensor& values, + int W, + int H, + int D +); + + +/** + * Lookup 3D coordinates in the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param coords [M, 4] int32 tensor containing the keys to be looked up + * @param W the number of width dimensions + * @param H the number of height dimensions + * @param D the number of depth dimensions + * + * @return [M] uint32/uint64 tensor containing the values of the keys + */ +torch::Tensor hashmap_lookup_3d_cuda( + const torch::Tensor& hashmap_keys, + const torch::Tensor& hashmap_values, + const torch::Tensor& coords, + int W, + int H, + int D +); + + +/** + * Insert 3D coordinates into the hashmap using index as value + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param coords [M, 4] int32 tensor containing the keys to be inserted + * @param W the number of width dimensions + * @param H the number of height dimensions + * @param D the number of depth dimensions + */ +void hashmap_insert_3d_idx_as_val_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& coords, + int W, + int H, + int D +); diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/hash.cu b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/hash.cu new file mode 100644 index 0000000000000000000000000000000000000000..c56d2239f71242f200d43f11f30b341e5e43139d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/hash.cu @@ -0,0 +1,446 @@ +#include +#include +#include + +#include "api.h" +#include "hash.cuh" + + +template +static __global__ void hashmap_insert_cuda_kernel( + const size_t N, + const size_t M, + K* __restrict__ hashmap_keys, + V* __restrict__ hashmap_values, + const K* __restrict__ keys, + const V* __restrict__ values +) { + size_t thread_id = blockIdx.x * blockDim.x + threadIdx.x; + if (thread_id < M) + { + K key = keys[thread_id]; + V value = values[thread_id]; + linear_probing_insert(hashmap_keys, hashmap_values, key, value, N); + } +} + + +template +static void dispatch_hashmap_insert_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& keys, + const torch::Tensor& values +) { + hashmap_insert_cuda_kernel<<< + (keys.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE + >>>( + hashmap_keys.size(0), + keys.size(0), + hashmap_keys.data_ptr(), + hashmap_values.data_ptr(), + keys.data_ptr(), + values.data_ptr() + ); +} + + +/** + * Insert keys into the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param keys [M] uint32/uint64 tensor containing the keys to be inserted + * @param values [M] uint32/uint64 tensor containing the values to be inserted + */ +void hashmap_insert_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& keys, + const torch::Tensor& values +) { + // Dispatch to 32-bit or 64-bit kernel + if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt32) { + TORCH_CHECK(keys.dtype() == torch::kUInt32, "Keys must be uint32"); + TORCH_CHECK(values.dtype() == torch::kUInt32, "Values must be uint32"); + dispatch_hashmap_insert_cuda(hashmap_keys, hashmap_values, keys, values); + } + else if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt64) { + TORCH_CHECK(keys.dtype() == torch::kUInt32, "Keys must be uint32"); + TORCH_CHECK(values.dtype() == torch::kUInt64, "Values must be uint64"); + dispatch_hashmap_insert_cuda(hashmap_keys, hashmap_values, keys, values); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt32) { + TORCH_CHECK(keys.dtype() == torch::kUInt64, "Keys must be uint64"); + TORCH_CHECK(values.dtype() == torch::kUInt32, "Values must be uint32"); + dispatch_hashmap_insert_cuda(hashmap_keys, hashmap_values, keys, values); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt64) { + TORCH_CHECK(keys.dtype() == torch::kUInt64, "Keys must be uint64"); + TORCH_CHECK(values.dtype() == torch::kUInt64, "Values must be uint64"); + dispatch_hashmap_insert_cuda(hashmap_keys, hashmap_values, keys, values); + } + else { + TORCH_CHECK(false, "Unsupported data type"); + } +} + + +template +static __global__ void hashmap_lookup_cuda_kernel( + const size_t N, + const size_t M, + const K * __restrict__ hashmap_keys, + const V * __restrict__ hashmap_values, + const K * __restrict__ keys, + V * __restrict__ values +) { + size_t thread_id = blockIdx.x * blockDim.x + threadIdx.x; + if (thread_id < M) { + K key = keys[thread_id]; + values[thread_id] = linear_probing_lookup(hashmap_keys, hashmap_values, key, N); + } +} + + +template +static void dispatch_hashmap_lookup_cuda( + const torch::Tensor& hashmap_keys, + const torch::Tensor& hashmap_values, + const torch::Tensor& keys, + torch::Tensor& values +) { + hashmap_lookup_cuda_kernel<<< + (keys.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE + >>>( + hashmap_keys.size(0), + keys.size(0), + hashmap_keys.data_ptr(), + hashmap_values.data_ptr(), + keys.data_ptr(), + values.data_ptr() + ); +} + + +/** + * Lookup keys in the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param keys [M] uint32/uint64 tensor containing the keys to be looked up + * @return [M] uint32/uint64 tensor containing the values of the keys + */ +torch::Tensor hashmap_lookup_cuda( + const torch::Tensor& hashmap_keys, + const torch::Tensor& hashmap_values, + const torch::Tensor& keys +) { + // Allocate output tensor + auto output = torch::empty({keys.size(0)}, torch::dtype(hashmap_values.dtype()).device(hashmap_values.device())); + + // Dispatch to 32-bit or 64-bit kernel + if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt32) { + TORCH_CHECK(keys.dtype() == torch::kUInt32, "Keys must be uint32"); + TORCH_CHECK(output.dtype() == torch::kUInt32, "Output must be uint32"); + dispatch_hashmap_lookup_cuda(hashmap_keys, hashmap_values, keys, output); + } + else if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt64) { + TORCH_CHECK(keys.dtype() == torch::kUInt32, "Keys must be uint32"); + TORCH_CHECK(output.dtype() == torch::kUInt64, "Output must be uint64"); + dispatch_hashmap_lookup_cuda(hashmap_keys, hashmap_values, keys, output); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt32) { + TORCH_CHECK(keys.dtype() == torch::kUInt64, "Keys must be uint64"); + TORCH_CHECK(output.dtype() == torch::kUInt32, "Output must be uint32"); + dispatch_hashmap_lookup_cuda(hashmap_keys, hashmap_values, keys, output); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt64) { + TORCH_CHECK(keys.dtype() == torch::kUInt64, "Keys must be uint64"); + TORCH_CHECK(output.dtype() == torch::kUInt64, "Output must be uint64"); + dispatch_hashmap_lookup_cuda(hashmap_keys, hashmap_values, keys, output); + } + else { + TORCH_CHECK(false, "Unsupported data type"); + } + + return output; +} + + +template +static __global__ void hashmap_insert_3d_cuda_kernel( + const size_t N, + const size_t M, + const int W, + const int H, + const int D, + K* __restrict__ hashmap_keys, + V* __restrict__ hashmap_values, + const int32_t* __restrict__ coords, + const V* __restrict__ values +) { + size_t thread_id = blockIdx.x * blockDim.x + threadIdx.x; + if (thread_id < M) { + int4 coord = reinterpret_cast(coords)[thread_id]; + int b = coord.x; + int x = coord.y; + int y = coord.z; + int z = coord.w; + size_t flat_idx = (size_t)b * W * H * D + (size_t)x * H * D + (size_t)y * D + z; + K key = static_cast(flat_idx); + V value = values[thread_id]; + linear_probing_insert(hashmap_keys, hashmap_values, key, value, N); + } +} + + +template +static void dispatch_hashmap_insert_3d_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& coords, + const torch::Tensor& values, + int W, int H, int D +) { + hashmap_insert_3d_cuda_kernel<<< + (coords.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE + >>>( + hashmap_keys.size(0), + coords.size(0), + W, H, D, + hashmap_keys.data_ptr(), + hashmap_values.data_ptr(), + coords.data_ptr(), + values.data_ptr() + ); +} + + +/** + * Insert 3D coordinates into the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param coords [M, 4] int32 tensor containing the keys to be inserted + * @param values [M] uint32/uint64 tensor containing the values to be inserted + * @param W the number of width dimensions + * @param H the number of height dimensions + * @param D the number of depth dimensions + */ +void hashmap_insert_3d_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& coords, + const torch::Tensor& values, + int W, + int H, + int D +) { + TORCH_CHECK(coords.dtype() == torch::kInt32, "Coords must be int32"); + + // Dispatch to 32-bit or 64-bit kernel + if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt32) { + TORCH_CHECK(values.dtype() == torch::kUInt32, "Values must be uint32"); + dispatch_hashmap_insert_3d_cuda(hashmap_keys, hashmap_values, coords, values, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt64) { + TORCH_CHECK(values.dtype() == torch::kUInt64, "Values must be uint64"); + dispatch_hashmap_insert_3d_cuda(hashmap_keys, hashmap_values, coords, values, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt32) { + TORCH_CHECK(values.dtype() == torch::kUInt32, "Values must be uint32"); + dispatch_hashmap_insert_3d_cuda(hashmap_keys, hashmap_values, coords, values, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt64) { + TORCH_CHECK(values.dtype() == torch::kUInt64, "Values must be uint64"); + dispatch_hashmap_insert_3d_cuda(hashmap_keys, hashmap_values, coords, values, W, H, D); + } + else { + TORCH_CHECK(false, "Unsupported data type"); + } +} + + +template +static __global__ void hashmap_lookup_3d_cuda_kernel( + const size_t N, + const size_t M, + const int W, + const int H, + const int D, + const K* __restrict__ hashmap_keys, + const V* __restrict__ hashmap_values, + const int32_t* __restrict__ coords, + V* __restrict__ values +) { + const size_t thread_id = blockIdx.x * blockDim.x + threadIdx.x; + if (thread_id < M) { + int4 coord = reinterpret_cast(coords)[thread_id]; + int b = coord.x; + int x = coord.y; + int y = coord.z; + int z = coord.w; + if (x < 0 || x >= W || y < 0 || y >= H || z < 0 || z >= D) { + values[thread_id] = std::numeric_limits::max(); + return; + } + size_t flat_idx = (size_t)b * W * H * D + (size_t)x * H * D + (size_t)y * D + z; + K key = static_cast(flat_idx); + values[thread_id] = linear_probing_lookup(hashmap_keys, hashmap_values, key, N); + } +} + + +template +static void dispatch_hashmap_lookup_3d_cuda( + const torch::Tensor& hashmap_keys, + const torch::Tensor& hashmap_values, + const torch::Tensor& coords, + torch::Tensor& values, + int W, int H, int D +) { + hashmap_lookup_3d_cuda_kernel<<< + (coords.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE + >>>( + hashmap_keys.size(0), + coords.size(0), + W, H, D, + hashmap_keys.data_ptr(), + hashmap_values.data_ptr(), + coords.data_ptr(), + values.data_ptr() + ); +} + + +/** + * Lookup 3D coordinates in the hashmap + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param coords [M, 4] int32 tensor containing the keys to be looked up + * @param W the number of width dimensions + * @param H the number of height dimensions + * @param D the number of depth dimensions + * + * @return [M] uint32/uint64 tensor containing the values of the keys + */ +torch::Tensor hashmap_lookup_3d_cuda( + const torch::Tensor& hashmap_keys, + const torch::Tensor& hashmap_values, + const torch::Tensor& coords, + int W, + int H, + int D +) { + // Allocate output tensor + auto output = torch::empty({coords.size(0)}, torch::dtype(hashmap_values.dtype()).device(hashmap_values.device())); + + // Dispatch to 32-bit or 64-bit kernel + if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt32) { + dispatch_hashmap_lookup_3d_cuda(hashmap_keys, hashmap_values, coords, output, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt64) { + dispatch_hashmap_lookup_3d_cuda(hashmap_keys, hashmap_values, coords, output, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt32) { + dispatch_hashmap_lookup_3d_cuda(hashmap_keys, hashmap_values, coords, output, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt64) { + dispatch_hashmap_lookup_3d_cuda(hashmap_keys, hashmap_values, coords, output, W, H, D); + } + else { + TORCH_CHECK(false, "Unsupported data type"); + } + + return output; +} + + +template +static __global__ void hashmap_insert_3d_idx_as_val_cuda_kernel( + const size_t N, + const size_t M, + const int W, + const int H, + const int D, + K* __restrict__ hashmap, + V* __restrict__ values, + const int32_t* __restrict__ coords +) { + const size_t thread_id = blockIdx.x * blockDim.x + threadIdx.x; + if (thread_id < M) { + int4 coord = reinterpret_cast(coords)[thread_id]; + int b = coord.x; + int x = coord.y; + int y = coord.z; + int z = coord.w; + size_t flat_idx = (size_t)b * W * H * D + (size_t)x * H * D + (size_t)y * D + z; + K key = static_cast(flat_idx); + V value = static_cast(thread_id); + linear_probing_insert(hashmap, values, key, value, N); + } +} + + +template +static void dispatch_hashmap_insert_3d_idx_as_val_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& coords, + int W, int H, int D +) { + hashmap_insert_3d_idx_as_val_cuda_kernel<<< + (coords.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE + >>>( + hashmap_keys.size(0), + coords.size(0), + W, H, D, + hashmap_keys.data_ptr(), + hashmap_values.data_ptr(), + coords.data_ptr() + ); +} + + +/** + * Insert 3D coordinates into the hashmap using index as value + * + * @param hashmap_keys [N] uint32/uint64 tensor containing the hashmap keys + * @param hashmap_values [N] uint32/uint64 tensor containing the hashmap values + * @param coords [M, 4] int32 tensor containing the keys to be inserted + * @param W the number of width dimensions + * @param H the number of height dimensions + * @param D the number of depth dimensions + */ +void hashmap_insert_3d_idx_as_val_cuda( + torch::Tensor& hashmap_keys, + torch::Tensor& hashmap_values, + const torch::Tensor& coords, + int W, + int H, + int D +) { + // Dispatch to 32-bit or 64-bit kernel + if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt32) { + dispatch_hashmap_insert_3d_idx_as_val_cuda(hashmap_keys, hashmap_values, coords, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt32 && hashmap_values.dtype() == torch::kUInt64) { + dispatch_hashmap_insert_3d_idx_as_val_cuda(hashmap_keys, hashmap_values, coords, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt32) { + dispatch_hashmap_insert_3d_idx_as_val_cuda(hashmap_keys, hashmap_values, coords, W, H, D); + } + else if (hashmap_keys.dtype() == torch::kUInt64 && hashmap_values.dtype() == torch::kUInt64) { + dispatch_hashmap_insert_3d_idx_as_val_cuda(hashmap_keys, hashmap_values, coords, W, H, D); + } + else { + TORCH_CHECK(false, "Unsupported data type"); + } +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/hash.cuh b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/hash.cuh new file mode 100644 index 0000000000000000000000000000000000000000..b7bcf1b57c16fec09374d39f63288a947530403f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/hash/hash.cuh @@ -0,0 +1,87 @@ +// 32 bit Murmur3 hash +__forceinline__ __device__ size_t hash(uint32_t k, size_t N) { + k ^= k >> 16; + k *= 0x85ebca6b; + k ^= k >> 13; + k *= 0xc2b2ae35; + k ^= k >> 16; + return k % N; +} + + +// 64 bit Murmur3 hash +__forceinline__ __device__ size_t hash(uint64_t k, size_t N) { + k ^= k >> 33; + k *= 0xff51afd7ed558ccdULL; + k ^= k >> 33; + k *= 0xc4ceb9fe1a85ec53ULL; + k ^= k >> 33; + return k % N; +} + + +template +__forceinline__ __device__ void linear_probing_insert( + K* hashmap_keys, + V* hashmap_values, + const K key, + const V value, + const size_t N +) { + size_t slot = hash(key, N); + while (true) { + K prev = atomicCAS(&hashmap_keys[slot], std::numeric_limits::max(), key); + if (prev == std::numeric_limits::max() || prev == key) { + hashmap_values[slot] = value; + return; + } + slot = slot + 1; + if (slot >= N) slot = 0; + } +} + + +template +__forceinline__ __device__ void linear_probing_insert( + uint64_t* hashmap_keys, + V* hashmap_values, + const uint64_t key, + const V value, + const size_t N +) { + size_t slot = hash(key, N); + while (true) { + uint64_t prev = atomicCAS( + reinterpret_cast(&hashmap_keys[slot]), + static_cast(std::numeric_limits::max()), + static_cast(key) + ); + if (prev == std::numeric_limits::max() || prev == key) { + hashmap_values[slot] = value; + return; + } + slot = (slot + 1) % N; + } +} + + +template +__forceinline__ __device__ V linear_probing_lookup( + const K* hashmap_keys, + const V* hashmap_values, + const K key, + const size_t N +) { + size_t slot = hash(key, N); + while (true) { + K prev = hashmap_keys[slot]; + if (prev == std::numeric_limits::max()) { + return std::numeric_limits::max(); + } + if (prev == key) { + return hashmap_values[slot]; + } + slot = slot + 1; + if (slot >= N) slot = 0; + } +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/api.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/api.h new file mode 100644 index 0000000000000000000000000000000000000000..116eb177a26a1ce698a25bf047fd419cf05d82b4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/api.h @@ -0,0 +1,109 @@ +/* + * Efficient Sparse Voxel storage as Sparse Voxel Zip files (.svz) + * + * Copyright (C) 2025, Jianfeng XIANG + * All rights reserved. + * + * Licensed under The MIT License [see LICENSE for details] + * + * Written by Jianfeng XIANG + */ + +#pragma once +#include +#include + + +/** + * Encode a list of sparse voxel morton codes into a sparse voxel octree + * NOTE: The input indices must be sorted in ascending order + * + * @param codes [N] uint32 tensor containing the morton codes + * @param depth The depth of the sparse voxel octree + * + * @return uint8 tensor containing the sparse voxel octree + */ +torch::Tensor encode_sparse_voxel_octree_cpu( + const torch::Tensor& codes, + const uint32_t depth +); + + +/** + * Decode a sparse voxel octree into a list of sparse voxel morton codes + * + * @param octree uint8 tensor containing the sparse voxel octree + * @param depth The depth of the sparse voxel octree + * + * @return [N] uint32 tensor containing the morton codes + * The codes are sorted in ascending order + */ +torch::Tensor decode_sparse_voxel_octree_cpu( + const torch::Tensor& octree, + const uint32_t depth +); + + + +/** + * Encode the attribute of a sparse voxel octree into deltas from its parent node. + * + * @param octree uint8 tensor containing the sparse voxel octree + * @param depth The depth of the sparse voxel octree + * @param attr [N, C] tensor containing the attribute of each sparse voxel + * + * @return uint8 tensor containing the deltas + */ +torch::Tensor encode_sparse_voxel_octree_attr_parent_cpu( + const torch::Tensor& octree, + const uint32_t depth, + const torch::Tensor& attr +); + + +/** + * Decode the attribute of a sparse voxel octree from its parent node and its deltas. + * + * @param octree uint8 tensor containing the sparse voxel octree + * @param depth The depth of the sparse voxel octree + * @param delta uint8 tensor containing the deltas + * + * @return [N, C] tensor containing the attribute of each sparse voxel + */ +torch::Tensor decode_sparse_voxel_octree_attr_parent_cpu( + const torch::Tensor& octree, + const uint32_t depth, + const torch::Tensor& delta +); + + +/** + * Encode the attribute of a sparse voxel octree into deltas from its neighbors. + * + * @param coord [N, 3] tensor containing the coordinates of each sparse voxel + * @param res The resolution of the sparse voxel grid + * @param attr [N, C] tensor containing the attribute of each sparse voxel + * + * @return uint8 tensor containing the deltas + */ +torch::Tensor encode_sparse_voxel_octree_attr_neighbor_cpu( + const torch::Tensor& coord, + const uint32_t res, + const torch::Tensor& attr +); + + +/** + * Decode the attribute of a sparse voxel octree from its neighbors and deltas. + * + * @param coord [N, 3] tensor containing the coordinates of each sparse voxel + * @param res The resolution of the sparse voxel grid + * @param delta [N, C] tensor containing the deltas + * + * @return [N, C] tensor containing the attribute of each sparse voxel + */ +torch::Tensor decode_sparse_voxel_octree_attr_neighbor_cpu( + const torch::Tensor& coord, + const uint32_t res, + const torch::Tensor& delta +); diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/filter_neighbor.cpp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/filter_neighbor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3af406eb5f5ae5a54fa7a572c601322a0c72e577 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/filter_neighbor.cpp @@ -0,0 +1,178 @@ +#include +#include "api.h" + +#include +#include +#include + + +/** + * Encode the attribute of a sparse voxel octree into deltas from its neighbors. + * + * @param coord [N, 3] tensor containing the coordinates of each sparse voxel + * @param res The resolution of the sparse voxel grid + * @param attr [N, C] tensor containing the attribute of each sparse voxel + * + * @return uint8 tensor containing the deltas + */ +torch::Tensor encode_sparse_voxel_octree_attr_neighbor_cpu( + const torch::Tensor& coord, + const uint32_t res, + const torch::Tensor& attr +) { + size_t N = coord.size(0); + size_t C = attr.size(1); + int* coord_data = coord.data_ptr(); + uint8_t* attr_data = attr.data_ptr(); + std::vector buffer(res * res * res * (C + 1), 0); + + // Densify the coordinates + for (int i = 0; i < N; i++) { + int x = coord_data[i * 3 + 0]; + int y = coord_data[i * 3 + 1]; + int z = coord_data[i * 3 + 2]; + int ptr = (z * res * res + y * res + x) * (C + 1); + buffer[ptr + C] = 1; + for (int c = 0; c < C; c++) { + buffer[ptr + c] = attr_data[i * C + c]; + } + } + + // Compute the deltas + for (int z = res-1; z >= 0; z--) { + for (int y = res-1; y >= 0; y--) { + for (int x = res-1; x >= 0; x--) { + int ptr = (z * res * res + y * res + x) * (C + 1); + int neignbor_ptr = -1; + int tmp_ptr; + if (!buffer[ptr + C]) continue; + // x + tmp_ptr = (z * res * res + y * res + (x - 1)) * (C + 1); + if (x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // y + tmp_ptr = (z * res * res + (y - 1) * res + x) * (C + 1); + if (y > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // z + tmp_ptr = ((z - 1) * res * res + y * res + x) * (C + 1); + if (z > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // xy + tmp_ptr = (z * res * res + (y - 1) * res + (x - 1)) * (C + 1); + if (y > 0 && x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // xz + tmp_ptr = ((z - 1) * res * res + y * res + (x - 1)) * (C + 1); + if (z > 0 && x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // yz + tmp_ptr = ((z - 1) * res * res + (y - 1) * res + x) * (C + 1); + if (z > 0 && y > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // xyz + tmp_ptr = ((z - 1) * res * res + (y - 1) * res + (x - 1)) * (C + 1); + if (z > 0 && y > 0 && x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + if (neignbor_ptr >= 0) { + for (int c = 0; c < C; c++) { + buffer[ptr + c] -= buffer[neignbor_ptr + c]; + } + } + } + } + } + + // Pack the deltas into a uint8 tensor + torch::Tensor delta = torch::zeros({N, C}, torch::dtype(torch::kUInt8)); + uint8_t* delta_data = delta.data_ptr(); + for (int i = 0; i < N; i++) { + int x = coord_data[i * 3 + 0]; + int y = coord_data[i * 3 + 1]; + int z = coord_data[i * 3 + 2]; + int ptr = (z * res * res + y * res + x) * (C + 1); + for (int c = 0; c < C; c++) { + delta_data[i * C + c] = buffer[ptr + c]; + } + } + return delta; +} + + +/** + * Decode the attribute of a sparse voxel octree from its neighbors and deltas. + * + * @param coord [N, 3] tensor containing the coordinates of each sparse voxel + * @param res The resolution of the sparse voxel grid + * @param delta [N, C] tensor containing the deltas + * + * @return [N, C] tensor containing the attribute of each sparse voxel + */ +torch::Tensor decode_sparse_voxel_octree_attr_neighbor_cpu( + const torch::Tensor& coord, + const uint32_t res, + const torch::Tensor& delta +) { + size_t N = coord.size(0); + size_t C = delta.size(1); + int* coord_data = coord.data_ptr(); + uint8_t* delta_data = delta.data_ptr(); + std::vector buffer(res * res * res * (C + 1), 0); + + // Densify the coordinates + for (int i = 0; i < N; i++) { + int x = coord_data[i * 3 + 0]; + int y = coord_data[i * 3 + 1]; + int z = coord_data[i * 3 + 2]; + int ptr = (z * res * res + y * res + x) * (C + 1); + buffer[ptr + C] = 1; + for (int c = 0; c < C; c++) { + buffer[ptr + c] = delta_data[i * C + c]; + } + } + + // Reconstruct the attribute + for (int z = 0; z < res; z++) { + for (int y = 0; y < res; y++) { + for (int x = 0; x < res; x++) { + int ptr = (z * res * res + y * res + x) * (C + 1); + int neignbor_ptr = -1; + int tmp_ptr; + if (!buffer[ptr + C]) continue; + // x + tmp_ptr = (z * res * res + y * res + (x - 1)) * (C + 1); + if (x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // y + tmp_ptr = (z * res * res + (y - 1) * res + x) * (C + 1); + if (y > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // z + tmp_ptr = ((z - 1) * res * res + y * res + x) * (C + 1); + if (z > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // xy + tmp_ptr = (z * res * res + (y - 1) * res + (x - 1)) * (C + 1); + if (y > 0 && x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // xz + tmp_ptr = ((z - 1) * res * res + y * res + (x - 1)) * (C + 1); + if (z > 0 && x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // yz + tmp_ptr = ((z - 1) * res * res + (y - 1) * res + x) * (C + 1); + if (z > 0 && y > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + // xyz + tmp_ptr = ((z - 1) * res * res + (y - 1) * res + (x - 1)) * (C + 1); + if (z > 0 && y > 0 && x > 0 && buffer[tmp_ptr + C]) neignbor_ptr = tmp_ptr; + if (neignbor_ptr >= 0) { + for (int c = 0; c < C; c++) { + buffer[ptr + c] += buffer[neignbor_ptr + c]; + } + } + } + } + } + + // Pack the attribute into a uint8 tensor + torch::Tensor attr = torch::zeros({N, C}, torch::dtype(torch::kUInt8)); + uint8_t* attr_data = attr.data_ptr(); + for (int i = 0; i < N; i++) { + int x = coord_data[i * 3 + 0]; + int y = coord_data[i * 3 + 1]; + int z = coord_data[i * 3 + 2]; + int ptr = (z * res * res + y * res + x) * (C + 1); + for (int c = 0; c < C; c++) { + attr_data[i * C + c] = buffer[ptr + c]; + } + } + return attr; +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/filter_parent.cpp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/filter_parent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0beadaf4cb27d398388e6b6e6fde9e8357bacd3d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/filter_parent.cpp @@ -0,0 +1,165 @@ +#include +#include "api.h" +#include "lut.h" + +#include +#include +#include + + +std::vector encode_recursive( + const uint8_t* svo, + const uint32_t depth, + const uint8_t* attr, + const size_t C, + uint32_t& svo_ptr, + uint32_t& attr_ptr, + uint32_t& delta_ptr, + uint32_t self_delta_ptr, + uint32_t cur_depth, + uint8_t* delta +) { + std::vector node_attr(C, 0); + if (cur_depth == depth) { + // Leaf node + for (size_t i = 0; i < C; i++) { + node_attr[i] = attr[attr_ptr + i]; + if (self_delta_ptr != 0 || cur_depth == 0) { + delta[self_delta_ptr + i] = node_attr[i]; + } + } + attr_ptr += C; + } + else { + // Internal node + uint8_t node = svo[svo_ptr]; + uint32_t child_delta_ptr = delta_ptr; + uint8_t cnt = lut_1cnt[node]; + svo_ptr++; + delta_ptr += C * (cnt - 1); + for (uint8_t i = 0; i < cnt; i++) { + auto child_attr = encode_recursive( + svo, depth, attr, C, svo_ptr, attr_ptr, delta_ptr, i == cnt-1 ? 0 : child_delta_ptr+i*C, cur_depth+1, delta + ); + for (size_t j = 0; j < C; j++) { + if (i == 0) { + node_attr[j] = child_attr[j]; + } + else { + delta[child_delta_ptr + (i-1)*C + j] = child_attr[j] - delta[child_delta_ptr + (i-1)*C + j]; + } + } + } + if (self_delta_ptr != 0 || cur_depth == 0) { + for (size_t i = 0; i < C; i++) { + delta[self_delta_ptr + i] = node_attr[i]; + } + } + } + return node_attr; +} + + +/** + * Encode the attribute of a sparse voxel octree into deltas from its parent node. + * + * @param octree uint8 tensor containing the sparse voxel octree + * @param depth The depth of the sparse voxel octree + * @param attr [N, C] tensor containing the attribute of each sparse voxel + * + * @return uint8 tensor containing the deltas + */ +torch::Tensor encode_sparse_voxel_octree_attr_parent_cpu( + const torch::Tensor& octree, + const uint32_t depth, + const torch::Tensor& attr +) { + size_t N_leaf = attr.size(0); + size_t N_node = octree.size(0); + size_t C = attr.size(1); + uint8_t* octree_data = octree.data_ptr(); + uint8_t* attr_data = attr.data_ptr(); + + torch::Tensor delta = torch::zeros({N_leaf, C}, torch::kUInt8); + uint32_t svo_ptr = 0; + uint32_t attr_ptr = 0; + uint32_t delta_ptr = C; + encode_recursive(octree_data, depth, attr_data, C, svo_ptr, attr_ptr, delta_ptr, 0, 0, delta.data_ptr()); + + return delta; +} + + +void decode_recursive( + const uint8_t* svo, + const uint32_t depth, + const uint8_t* delta, + const size_t C, + uint32_t& svo_ptr, + uint32_t& attr_ptr, + uint32_t& delta_ptr, + uint32_t cur_depth, + uint8_t* cur_attr, + uint8_t* attr +) { + if (cur_depth == depth) { + // Leaf node + for (size_t i = 0; i < C; i++) { + attr[attr_ptr + i] = cur_attr[i]; + } + attr_ptr += C; + } + else { + // Internal node + uint8_t node = svo[svo_ptr]; + uint32_t child_delta_ptr = delta_ptr; + std::vector child_attr(cur_attr, cur_attr + C); + uint8_t cnt = lut_1cnt[node]; + svo_ptr++; + delta_ptr += C * (cnt - 1); + for (uint8_t i = 0; i < cnt; i++) { + for (size_t j = 0; j < C; j++) { + if (i > 0) { + child_attr[j] += delta[child_delta_ptr + (i-1)*C + j]; + } + } + decode_recursive( + svo, depth, delta, C, svo_ptr, attr_ptr, delta_ptr, cur_depth+1, child_attr.data(), attr + ); + } + } +} + + +/** + * Decode the attribute of a sparse voxel octree from its parent node and its deltas. + * + * @param octree uint8 tensor containing the sparse voxel octree + * @param depth The depth of the sparse voxel octree + * @param delta uint8 tensor containing the deltas + * + * @return [N, C] tensor containing the attribute of each sparse voxel + */ +torch::Tensor decode_sparse_voxel_octree_attr_parent_cpu( + const torch::Tensor& octree, + const uint32_t depth, + const torch::Tensor& delta +) { + size_t N_node = octree.size(0); + size_t N_leaf = delta.size(0); + size_t C = delta.size(1); + uint8_t* octree_data = octree.data_ptr(); + uint8_t* delta_data = delta.data_ptr(); + + torch::Tensor attr = torch::zeros({N_leaf, C}, torch::kUInt8); + uint32_t svo_ptr = 0; + uint32_t attr_ptr = 0; + uint32_t delta_ptr = C; + + // Recursively decode the attribute + decode_recursive( + octree_data, depth, delta_data, C, svo_ptr, attr_ptr, delta_ptr, 0, delta_data, attr.data_ptr() + ); + + return attr; +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/lut.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/lut.h new file mode 100644 index 0000000000000000000000000000000000000000..d790ae9b29074e52d0c070aa05005e1928474214 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/lut.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +// np.array([bin(i).count('1') for i in range(256)], dtype=np.uint8) +uint8_t lut_1cnt[256] = { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, + 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, + 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, + 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, + 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, + 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, + 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, + 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, + 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, + 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, + 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 +}; diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/svo.cpp b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/svo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6775284d130ca902ff119e12fdf9198eae504e18 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/io/svo.cpp @@ -0,0 +1,138 @@ +#include +#include "api.h" + +#include +#include + + +/** + * Encode a list of sparse voxel morton codes into a sparse voxel octree + * NOTE: The input indices must be sorted in ascending order + * + * @param codes [N] uint32 tensor containing the morton codes + * @param depth The depth of the sparse voxel octree + * + * @return uint8 tensor containing the sparse voxel octree + */ +torch::Tensor encode_sparse_voxel_octree_cpu( + const torch::Tensor& codes, + const uint32_t depth +) { + size_t N_leaf = codes.size(0); + int* codes_data = codes.data_ptr(); + + std::vector svo; + std::vector stack(depth-1); + std::vector insert_stack(depth); + std::vector stack_ptr(depth); + uint32_t code, insert_from; + + // Root node + svo.push_back(0); + stack_ptr[0] = 0; + + // Iterate over all codes and encode them into SVO + for (int i = 0; i < N_leaf; i++) { + code = codes_data[i]; + + // Convert code to insert stack (3bit per level) + for (uint32_t j = 0; j < depth; j++) { + insert_stack[j] = (code >> (3*(depth-1-j))) & 0x7; + } + + // Compare insert stack to stack to determine which level to insert + if (i == 0) { + // First code, insert at level 0 + insert_from = 0; + } + else { + // Compare insert stack to stack + for (insert_from = 0; insert_from < depth-1; insert_from++) { + if (insert_stack[insert_from] != stack[insert_from]) { + break; + } + } + } + + // Insert new nodes from insert_from to depth-1 + for (uint32_t j = insert_from; j < depth; j++) { + // Add new node to SVO + if (j > insert_from) { + svo.push_back(0); + stack_ptr[j] = svo.size()-1; + } + // Update parent pointers + svo[stack_ptr[j]] |= (1 << insert_stack[j]); + // Update stack + if (j < depth-1) { + stack[j] = insert_stack[j]; + } + } + } + + // Convert SVO to tensor + torch::Tensor svo_tensor = torch::from_blob(svo.data(), {svo.size()}, torch::kUInt8).clone(); + return svo_tensor; +} + + +void decode_sparse_voxel_octree_cpu_recursive( + const uint8_t* svo, + const uint32_t depth, + uint32_t& ptr, + std::vector& stack, + std::vector& codes +) { + uint8_t node = svo[ptr]; + if (stack.size() == depth-1) { + // Leaf node, add code to list + uint32_t code = 0; + for (uint32_t i = 0; i < depth-1; i++) { + code |= (static_cast(stack[i]) << (3*(depth-1-i))); + } + for (uint8_t i = 0; i < 8; i++) { + if (node & (1 << i)) { + code = (code & ~0x7) | i; + codes.push_back(code); + } + } + ptr++; + } + else { + // Internal node, recurse + ptr++; + for (uint8_t i = 0; i < 8; i++) { + if (node & (1 << i)) { + stack.push_back(i); + decode_sparse_voxel_octree_cpu_recursive(svo, depth, ptr, stack, codes); + stack.pop_back(); + } + } + } +} + + +/** + * Decode a sparse voxel octree into a list of sparse voxel morton codes + * + * @param octree uint8 tensor containing the sparse voxel octree + * @param depth The depth of the sparse voxel octree + * + * @return [N] uint32 tensor containing the morton codes + * The codes are sorted in ascending order + */ +torch::Tensor decode_sparse_voxel_octree_cpu( + const torch::Tensor& octree, + const uint32_t depth +) { + uint8_t* octree_data = octree.data_ptr(); + std::vector codes; + std::vector stack; + stack.reserve(depth-2); + uint32_t ptr = 0; + // Decode SVO into list of codes + decode_sparse_voxel_octree_cpu_recursive(octree_data, depth, ptr, stack, codes); + // Convert codes to tensor + torch::Tensor codes_tensor = torch::from_blob(codes.data(), {codes.size()}, torch::kInt32).clone(); + return codes_tensor; +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/api.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/api.h new file mode 100644 index 0000000000000000000000000000000000000000..26212fd9c5bf8e61c2315027edbc6be4eb78428d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/api.h @@ -0,0 +1,47 @@ +/* + * Sparse Voxel Rasterizer + * + * Copyright (C) 2025, Jianfeng XIANG + * All rights reserved. + * + * Licensed under The MIT License [see LICENSE for details] + * + * Written by Jianfeng XIANG + */ + +#pragma once +#include + + +/** + * Rasterize a sparse voxel octree with CUDA backend + * + * @param positions Tensor of shape (N, 3) containing the positions of the octree nodes in [0, 1]^3 + * @param attrs Tensor of shape (N, 1) containing the attributes of the octree nodes + * @param voxel_size Float containing the size of the voxels + * @param viewmatrix Tensor of shape (4, 4) containing the view matrix + * @param projmatrix Tensor of shape (4, 4) containing the projection matrix + * @param campos Tensor of shape (3) containing the camera position + * @param tan_fovx Float containing the tangent of the horizontal field of view + * @param tan_fovy Float containing the tangent of the vertical field of view + * @param image_height Integer containing the image height + * @param image_width Integer containing the image width + * + * @return A tuple containing: + * - Tensor of shape (C, H, W) containing the output color + * - Tensor of shape (H, W) containing the output depth + * - Tensor of shape (H, W) containing the output alpha + */ +std::tuple +rasterize_voxels_cuda( + const torch::Tensor& positions, + const torch::Tensor& attrs, + const float voxel_size, + const torch::Tensor& viewmatrix, + const torch::Tensor& projmatrix, + const torch::Tensor& campos, + const float tan_fovx, + const float tan_fovy, + const int image_height, + const int image_width +); diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/auxiliary.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/auxiliary.h new file mode 100644 index 0000000000000000000000000000000000000000..f4abfbc6c4792c21a59a2a637b49066946ae1586 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/auxiliary.h @@ -0,0 +1,285 @@ +#pragma once +#include "config.h" + + +#define BLOCK_SIZE (BLOCK_X * BLOCK_Y) + + +__forceinline__ __device__ float ndc2Pix(float v, int S) +{ + return ((v + 1.0) * S - 1.0) * 0.5; +} + + +__forceinline__ __device__ void getRect(const int4 bbox, uint2& rect_min, uint2& rect_max, dim3 grid) +{ + rect_min = { + min(grid.x, max((int)0, (int)((bbox.x) / BLOCK_X))), + min(grid.y, max((int)0, (int)((bbox.y) / BLOCK_Y))) + }; + rect_max = { + min(grid.x, max((int)0, (int)((bbox.z + BLOCK_X - 1) / BLOCK_X))), + min(grid.y, max((int)0, (int)((bbox.w + BLOCK_Y - 1) / BLOCK_Y))) + }; +} + + +__forceinline__ __device__ float3 normalize(const float3& v) +{ + float inv_norm = 1.0f / sqrt(v.x * v.x + v.y * v.y + v.z * v.z); + return { v.x * inv_norm, v.y * inv_norm, v.z * inv_norm }; +} + + +__forceinline__ __device__ float3 transformPoint4x3(const float3& p, const float* matrix) +{ + float3 transformed = { + matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12], + matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13], + matrix[2] * p.x + matrix[6] * p.y + matrix[10] * p.z + matrix[14], + }; + return transformed; +} + + +__forceinline__ __device__ float4 transformPoint4x4(const float3& p, const float* matrix) +{ + float4 transformed = { + matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12], + matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13], + matrix[2] * p.x + matrix[6] * p.y + matrix[10] * p.z + matrix[14], + matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15] + }; + return transformed; +} + + +__forceinline__ __device__ float3 transformVec4x3(const float3& p, const float* matrix) +{ + float3 transformed = { + matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z, + matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z, + matrix[2] * p.x + matrix[6] * p.y + matrix[10] * p.z, + }; + return transformed; +} + + +__forceinline__ __device__ float3 transformVec4x3Transpose(const float3& p, const float* matrix) +{ + float3 transformed = { + matrix[0] * p.x + matrix[1] * p.y + matrix[2] * p.z, + matrix[4] * p.x + matrix[5] * p.y + matrix[6] * p.z, + matrix[8] * p.x + matrix[9] * p.y + matrix[10] * p.z, + }; + return transformed; +} + + +__forceinline__ __device__ float dnormvdz(float3 v, float3 dv) +{ + float sum2 = v.x * v.x + v.y * v.y + v.z * v.z; + float invsum32 = 1.0f / sqrt(sum2 * sum2 * sum2); + float dnormvdz = (-v.x * v.z * dv.x - v.y * v.z * dv.y + (sum2 - v.z * v.z) * dv.z) * invsum32; + return dnormvdz; +} + + +__forceinline__ __device__ float3 dnormvdv(float3 v, float3 dv) +{ + float sum2 = v.x * v.x + v.y * v.y + v.z * v.z; + float invsum32 = 1.0f / sqrt(sum2 * sum2 * sum2); + + float3 dnormvdv; + dnormvdv.x = ((+sum2 - v.x * v.x) * dv.x - v.y * v.x * dv.y - v.z * v.x * dv.z) * invsum32; + dnormvdv.y = (-v.x * v.y * dv.x + (sum2 - v.y * v.y) * dv.y - v.z * v.y * dv.z) * invsum32; + dnormvdv.z = (-v.x * v.z * dv.x - v.y * v.z * dv.y + (sum2 - v.z * v.z) * dv.z) * invsum32; + return dnormvdv; +} + + +__forceinline__ __device__ float4 dnormvdv(float4 v, float4 dv) +{ + float sum2 = v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w; + float invsum32 = 1.0f / sqrt(sum2 * sum2 * sum2); + + float4 vdv = { v.x * dv.x, v.y * dv.y, v.z * dv.z, v.w * dv.w }; + float vdv_sum = vdv.x + vdv.y + vdv.z + vdv.w; + float4 dnormvdv; + dnormvdv.x = ((sum2 - v.x * v.x) * dv.x - v.x * (vdv_sum - vdv.x)) * invsum32; + dnormvdv.y = ((sum2 - v.y * v.y) * dv.y - v.y * (vdv_sum - vdv.y)) * invsum32; + dnormvdv.z = ((sum2 - v.z * v.z) * dv.z - v.z * (vdv_sum - vdv.z)) * invsum32; + dnormvdv.w = ((sum2 - v.w * v.w) * dv.w - v.w * (vdv_sum - vdv.w)) * invsum32; + return dnormvdv; +} + + +__forceinline__ __device__ float sigmoid(float x) +{ + return 1.0f / (1.0f + expf(-x)); +} + + +__forceinline__ __device__ bool in_frustum(int idx, + const float3& p_orig, + const float* viewmatrix, + const float* projmatrix, + float3& p_view) +{ + // Bring points to screen space + float4 p_hom = transformPoint4x4(p_orig, projmatrix); + float p_w = 1.0f / (p_hom.w + 0.0000001f); + float3 p_proj = { p_hom.x * p_w, p_hom.y * p_w, p_hom.z * p_w }; + p_view = transformPoint4x3(p_orig, viewmatrix); + + if (p_view.z <= 0.2f)// || ((p_proj.x < -1.3 || p_proj.x > 1.3 || p_proj.y < -1.3 || p_proj.y > 1.3))) + { + return false; + } + return true; +} + + +__forceinline__ __device__ uint32_t expandBits(uint32_t v) +{ + v = (v * 0x00010001u) & 0xFF0000FFu; + v = (v * 0x00000101u) & 0x0F00F00Fu; + v = (v * 0x00000011u) & 0xC30C30C3u; + v = (v * 0x00000005u) & 0x49249249u; + return v; +} + + +__forceinline__ __device__ int2 project(const float3& p, const float* matrix, const int& width, const int& height) +{ + float3 p_hom = { + matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12], + matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13], + matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15] + }; + float p_w = 1.0f / (p_hom.z + 0.0000001f); + return { (int)((p_hom.x * p_w + 1.0f) * 0.5f * width), (int)((p_hom.y * p_w + 1.0f) * 0.5f * height) }; +} + + +#define GET_BBOX_FIRST(A, B, C) \ +vertex.x = point.x A half_scale.x; \ +vertex.y = point.y B half_scale.y; \ +vertex.z = point.z C half_scale.z; \ +p_screen = project(vertex, projmatrix, width, height); \ +bbox.x = p_screen.x; \ +bbox.y = p_screen.y; \ +bbox.z = p_screen.x + 1; \ +bbox.w = p_screen.y + 1; + +#define GET_BBOX_OTHER(A, B, C) \ +vertex.x = point.x A half_scale.x; \ +vertex.y = point.y B half_scale.y; \ +vertex.z = point.z C half_scale.z; \ +p_screen = project(vertex, projmatrix, width, height); \ +bbox.x = min(bbox.x, p_screen.x); \ +bbox.y = min(bbox.y, p_screen.y); \ +bbox.z = max(bbox.z, p_screen.x + 1); \ +bbox.w = max(bbox.w, p_screen.y + 1); + + +__forceinline__ __device__ int4 get_bbox( + const float3& point, + const float3& scale, + const float* projmatrix, + const int& width, + const int& height +) { + float3 half_scale = { scale.x * 0.5f, scale.y * 0.5f, scale.z * 0.5f }; + float3 vertex; + int2 p_screen; + int4 bbox; + + GET_BBOX_FIRST(-, -, -); + GET_BBOX_OTHER(+, -, -); + GET_BBOX_OTHER(-, +, -); + GET_BBOX_OTHER(+, +, -); + GET_BBOX_OTHER(-, -, +); + GET_BBOX_OTHER(+, -, +); + GET_BBOX_OTHER(-, +, +); + GET_BBOX_OTHER(+, +, +); + + bbox.x = max(0, bbox.x); + bbox.y = max(0, bbox.y); + bbox.z = min(width, bbox.z); + bbox.w = min(height, bbox.w); + if (bbox.x >= bbox.z || bbox.y >= bbox.w) // bbox is empty + return { 0, 0, 0, 0 }; + return bbox; +} + + +// Fast ray-box intersection, returns the intersection distance +__forceinline__ __device__ float2 get_ray_voxel_intersection( + const float3& ray_origin, + const float3& ray_direction, + const float3& voxel_min, + const float3& voxel_max +) { + // Careful with the division by zero + float3 inv_direction; + inv_direction.x = ray_direction.x == 0.0f ? 1e10f : 1.0f / ray_direction.x; + inv_direction.y = ray_direction.y == 0.0f ? 1e10f : 1.0f / ray_direction.y; + inv_direction.z = ray_direction.z == 0.0f ? 1e10f : 1.0f / ray_direction.z; + float3 t0 = { + (voxel_min.x - ray_origin.x) * inv_direction.x, + (voxel_min.y - ray_origin.y) * inv_direction.y, + (voxel_min.z - ray_origin.z) * inv_direction.z + }; + float3 t1 = { + (voxel_max.x - ray_origin.x) * inv_direction.x, + (voxel_max.y - ray_origin.y) * inv_direction.y, + (voxel_max.z - ray_origin.z) * inv_direction.z + }; + float3 tmin = { + min(t0.x, t1.x), + min(t0.y, t1.y), + min(t0.z, t1.z) + }; + float3 tmax = { + max(t0.x, t1.x), + max(t0.y, t1.y), + max(t0.z, t1.z) + }; + float tmin_max = max(tmin.x, max(tmin.y, tmin.z)); + float tmax_min = min(tmax.x, min(tmax.y, tmax.z)); + return { tmin_max, tmax_min }; +} + + +__forceinline__ __device__ float3 getRayDir( + const uint2& pix, + const int& width, + const int& height, + const float& tan_fovx, + const float& tan_fovy, + const float* viewmatrix +) { + float x = (2.0f * (pix.x + 0.5f) / width - 1.0f) * tan_fovx; + float y = (2.0f * (pix.y + 0.5f) / height - 1.0f) * tan_fovy; + float3 ray_dir = { + viewmatrix[0] * x + viewmatrix[1] * y + viewmatrix[2], + viewmatrix[4] * x + viewmatrix[5] * y + viewmatrix[6], + viewmatrix[8] * x + viewmatrix[9] * y + viewmatrix[10] + }; + return normalize(ray_dir); +} + + +#ifdef DEBUG +#define CHECK_CUDA(...) __VA_ARGS__; {\ +auto ret = cudaDeviceSynchronize(); \ +if (ret != cudaSuccess) { \ +std::cerr << "\n[CUDA ERROR] in " << __FILE__ << "\nLine " << __LINE__ << ": " << cudaGetErrorString(ret); \ +throw std::runtime_error(cudaGetErrorString(ret)); \ +}} +#define DEBUG_PRINT(...) printf(__VA_ARGS__) +#else +#define CHECK_CUDA(...) __VA_ARGS__ +#define DEBUG_PRINT(...) +#endif \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/config.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/config.h new file mode 100644 index 0000000000000000000000000000000000000000..0bf4bab2805019d65dd1ed203096693bc70cfb60 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/config.h @@ -0,0 +1,5 @@ +#pragma once + +#define BLOCK_X 8 +#define BLOCK_Y 8 +#define MEM_ALIGNMENT 128 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/rasterize.cu b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/rasterize.cu new file mode 100644 index 0000000000000000000000000000000000000000..cc7291d0ded215fd94458a27e48a3bc9c787f792 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/rasterize/rasterize.cu @@ -0,0 +1,396 @@ +#include + +#include +#include "cuda_runtime.h" + +#include +namespace cg = cooperative_groups; + +#include "config.h" +#include "auxiliary.h" +#include "api.h" + + +/** + * Preprocess input 3D points + */ +static __global__ void preprocess( + const int num_nodes, + const float* positions, + const float voxel_size, + const float* viewmatrix, + const float* projmatrix, + const int width, + const int height, + const dim3 grid, + int4* bboxes, + float* depths, + uint32_t* tiles_touched +) { + auto idx = cg::this_grid().thread_rank(); + if (idx >= num_nodes) + return; + + // Initialize bboxes and touched tiles to 0. If this isn't changed, + // this voxel will not be processed further. + bboxes[idx] = { 0, 0, 0, 0 }; + tiles_touched[idx] = 0; + + // Perform near culling, quit if outside. + float3 p_orig = { + positions[3 * idx], + positions[3 * idx + 1], + positions[3 * idx + 2] + }; + float3 p_view; + if (!in_frustum(idx, p_orig, viewmatrix, projmatrix, p_view)) + return; + + // Project 8 vertices of the voxel to screen space to find the + // bounding box of the projected points. + float3 scale = { voxel_size, voxel_size, voxel_size }; + int4 bbox = get_bbox(p_orig, scale, projmatrix, width, height); + uint2 rect_min, rect_max; + getRect(bbox, rect_min, rect_max, grid); + if ((rect_max.x - rect_min.x) * (rect_max.y - rect_min.y) == 0) + return; + + // Store some useful helper data for the next steps. + depths[idx] = p_view.z; + bboxes[idx] = bbox; + tiles_touched[idx] = (rect_max.y - rect_min.y) * (rect_max.x - rect_min.x); +} + + +/** + * Generates one key/value pair for all voxel / tile overlaps. + * Run once per voxel (1:N mapping). + * + * @param P Number of points. + * @param grid Grid size. + * @param depths Depths of points. + * @param offsets Offsets for writing keys/values. + * @param bboxes Bounding boxes of voxels. + * @param keys_unsorted Unsorted keys. + * @param values_unsorted Unsorted values. + */ +static __global__ void duplicateWithKeys( + int P, dim3 grid, + const float* depths, + const int64_t* offsets, + const int4* bboxes, + int64_t* keys_unsorted, + uint32_t* values_unsorted +) { + auto idx = cg::this_grid().thread_rank(); + if (idx >= P) + return; + + // Generate no key/value pair for invisible voxels + if (bboxes[idx].w > 0) + { + // Find this voxel's offset in buffer for writing keys/values. + int64_t off = (idx == 0) ? 0 : offsets[idx - 1]; + uint2 rect_min, rect_max; + getRect(bboxes[idx], rect_min, rect_max, grid); + + // For each tile that the bounding rect overlaps, emit a + // key/value pair. The key is | tile ID | depth |, + // and the value is the ID of the voxel. Sorting the values + // with this key yields voxel IDs in a list, such that they + // are first sorted by tile and then by depth. + for (int y = rect_min.y; y < rect_max.y; y++) + { + for (int x = rect_min.x; x < rect_max.x; x++) + { + int64_t key = y * grid.x + x; + key <<= 32; + key |= *((uint32_t*)&depths[idx]); + keys_unsorted[off] = key; + values_unsorted[off] = idx; + off++; + } + } + } +} + + +/** + * Check keys to see if it is at the start/end of one tile's range in the full sorted list. If yes, write start/end of this tile. + * + * @param L Number of points. + * @param point_list_keys List of keys. + * @param ranges Ranges of tiles. + */ +static __global__ void identifyTileRanges(int L, int64_t* point_list_keys, uint2* ranges) +{ + auto idx = cg::this_grid().thread_rank(); + if (idx >= L) + return; + + // Read tile ID from key. Update start/end of tile range if at limit. + int64_t key = point_list_keys[idx]; + uint32_t currtile = key >> 32; + if (idx == 0) + ranges[currtile].x = 0; + else + { + uint32_t prevtile = point_list_keys[idx - 1] >> 32; + if (currtile != prevtile) + { + ranges[prevtile].y = idx; + ranges[currtile].x = idx; + } + } + if (idx == L - 1) + ranges[currtile].y = L; +} + + +/** + * Main rasterization method. Collaboratively works on one tile per + * block, each thread treats one pixel. Alternates between fetching + * and rasterizing data. + * + * @param ranges Ranges of voxel instances for each tile. + * @param point_list List of voxel instances. + * @param C Number of channels. + * @param W Width of the image. + * @param H Height of the image. + * @param cam_pos Camera position. + * @param tan_fovx Tangent of the horizontal field of view. + * @param tan_fovy Tangent of the vertical field of view. + * @param viewmatrix View matrix. + * @param positions Centers of voxels. + * @param attrs Attributes of voxels. + * @param voxel_size Size of voxels. + * @param out_color Output color. + * @param out_depth Output depth. + * @param out_alpha Output alpha. + */ +static __global__ void __launch_bounds__(BLOCK_X * BLOCK_Y) +render( + const uint2* ranges, + const uint32_t* point_list, + const int C, + const int W, + const int H, + const float* cam_pos, + const float tan_fovx, + const float tan_fovy, + const float* viewmatrix, + const float* positions, + const float* attrs, + const float voxel_size, + float* out_color, + float* out_depth, + float* out_alpha +) { + // Identify current tile and associated min/max pixel range. + auto block = cg::this_thread_block(); + uint32_t horizontal_blocks = (W + BLOCK_X - 1) / BLOCK_X; + uint2 pix_min = { block.group_index().x * BLOCK_X, block.group_index().y * BLOCK_Y }; + uint2 pix_max = { min(pix_min.x + BLOCK_X, W), min(pix_min.y + BLOCK_Y , H) }; + uint2 pix = { pix_min.x + block.thread_index().x, pix_min.y + block.thread_index().y }; + uint32_t pix_id = W * pix.y + pix.x; + + // Get ray direction and origin for this pixel. + float3 ray_dir = getRayDir(pix, W, H, tan_fovx, tan_fovy, viewmatrix); + + // Check if this thread is associated with a valid pixel or outside. + bool inside = pix.x < W&& pix.y < H; + // Done threads can help with fetching, but don't rasterize + bool done = !inside; + + // Load start/end range of IDs to process in bit sorted list. + uint2 range = ranges[block.group_index().y * horizontal_blocks + block.group_index().x]; + const int rounds = ((range.y - range.x + BLOCK_SIZE - 1) / BLOCK_SIZE); + int toDo = range.y - range.x; + + // Allocate storage for batches of collectively fetched data. + __shared__ int collected_id[BLOCK_SIZE]; + __shared__ float3 collected_xyz[BLOCK_SIZE]; + + // Initialize helper variables + int hit = -1; + float D; + + // Iterate over batches until all done or range is complete + for (int i = 0; i < rounds; i++, toDo -= BLOCK_SIZE) + { + // End if entire block votes that it is done rasterizing + int num_done = __syncthreads_count(done); + if (num_done == BLOCK_SIZE) + break; + + // Collectively fetch per-voxel data from global to shared + int progress = i * BLOCK_SIZE + block.thread_rank(); + if (range.x + progress < range.y) + { + int coll_id = point_list[range.x + progress]; + collected_id[block.thread_rank()] = coll_id; + collected_xyz[block.thread_rank()] = { + positions[3 * coll_id], + positions[3 * coll_id + 1], + positions[3 * coll_id + 2] + }; + } + block.sync(); + + // Iterate over current batch + for (int j = 0; !done && j < min(BLOCK_SIZE, toDo); j++) + { + // Get ray-voxel intersection + float3 p = collected_xyz[j]; + float3 scale = { voxel_size, voxel_size, voxel_size }; + float3 voxel_min = { p.x - 0.5f * scale.x, p.y - 0.5f * scale.y, p.z - 0.5f * scale.z }; + float3 voxel_max = { p.x + 0.5f * scale.x, p.y + 0.5f * scale.y, p.z + 0.5f * scale.z }; + float2 itsc = get_ray_voxel_intersection(*(float3*)cam_pos, ray_dir, voxel_min, voxel_max); + float itsc_dist = (itsc.y >= itsc.x) ? itsc.y - itsc.x : -1.0f; + if (itsc_dist <= 0.0f) + continue; + + hit = collected_id[j]; + D = itsc.x; + done = true; + } + } + + // All threads that treat valid pixel write out their final + // rendering data to the frame and auxiliary buffers. + if (inside) + { + for (int ch = 0; ch < C; ch++) + if (hit >= 0) out_color[ch * H * W + pix_id] = attrs[hit * C + ch]; + out_depth[pix_id] = D; + out_alpha[pix_id] = hit >= 0 ? 1.0f : 0.0f; + } +} + +void forward( + const int num_nodes, + const int num_channels, + const int width, + const int height, + const float* positions, + const float* attrs, + const float voxel_size, + const float* viewmatrix, + const float* projmatrix, + const float* campos, + const float tan_fovx, + const float tan_fovy, + float* out_color, + float* out_depth, + float* out_alpha +) { + // Parrallel config (2D grid of 2D blocks) + dim3 grid((width + BLOCK_X - 1) / BLOCK_X, (height + BLOCK_Y - 1) / BLOCK_Y, 1); + dim3 block(BLOCK_X, BLOCK_Y, 1); + + // Run preprocessing kernel + auto pt_bboxes = torch::zeros({num_nodes, 4}, torch::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA)); + auto pt_depths = torch::zeros({num_nodes}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA)); + auto pt_tiles_touched = torch::zeros({num_nodes}, torch::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA)); + preprocess<<<(num_nodes+255)/256, 256>>>( + num_nodes, positions, voxel_size, viewmatrix, projmatrix, width, height, grid, + reinterpret_cast(pt_bboxes.data_ptr()), + pt_depths.data_ptr(), + reinterpret_cast(pt_tiles_touched.data_ptr()) + ); + + // Compute prefix sum over full list of touched tile counts by voxels + // E.g., [2, 3, 0, 2, 1] -> [2, 5, 5, 7, 8] + auto pt_offsets = torch::cumsum(pt_tiles_touched, 0); + + // Retrieve total number of voxel instances to launch + int num_rendered = pt_offsets[num_nodes - 1].item(); + if (num_rendered == 0) return; + + // For each instance to be rendered, produce adequate [ tile | depth ] key + auto pt_keys_unsorted = torch::zeros({num_rendered}, torch::TensorOptions().dtype(torch::kInt64).device(torch::kCUDA)); + auto pt_indices_unsorted = torch::zeros({num_rendered}, torch::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA)); + duplicateWithKeys<<<(num_nodes+255)/256, 256>>>( + num_nodes, grid, + pt_depths.data_ptr(), + pt_offsets.data_ptr(), + reinterpret_cast(pt_bboxes.data_ptr()), + pt_keys_unsorted.data_ptr(), + reinterpret_cast(pt_indices_unsorted.data_ptr()) + ); + + // Sort complete list of (duplicated) voxel indices by keys + auto pt_sorted = torch::sort(pt_keys_unsorted, 0); + auto pt_keys = std::get<0>(pt_sorted); + auto pt_order = std::get<1>(pt_sorted); + auto pt_indices = torch::index_select(pt_indices_unsorted, 0, pt_order); + + // Identify start and end of per-tile workloads in sorted list + auto tile_ranges = torch::zeros({grid.x * grid.y, 2}, torch::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA)); + identifyTileRanges<<<(num_rendered+255)/256, 256>>>( + num_rendered, + pt_keys.data_ptr(), + reinterpret_cast(tile_ranges.data_ptr()) + ); + + // Let each tile blend its range of voxels independently in parallel + render<<>>( + reinterpret_cast(tile_ranges.data_ptr()), + reinterpret_cast(pt_indices.data_ptr()), + num_channels, width, height, + campos, tan_fovx, tan_fovy, viewmatrix, + positions, attrs, voxel_size, + out_color, out_depth, out_alpha + ); +} + + +std::tuple +rasterize_voxels_cuda( + const torch::Tensor& positions, + const torch::Tensor& attrs, + const float voxel_size, + const torch::Tensor& viewmatrix, + const torch::Tensor& projmatrix, + const torch::Tensor& campos, + const float tan_fovx, + const float tan_fovy, + const int image_height, + const int image_width +) { + // Sizes + const int P = positions.size(0); + const int C = attrs.size(1); + const int H = image_height; + const int W = image_width; + + // Types + torch::TensorOptions float_opts = torch::TensorOptions().dtype(torch::kFloat32).device(positions.device()); + torch::TensorOptions byte_opts = torch::TensorOptions().dtype(torch::kUInt8).device(positions.device()); + + // Allocate output tensors + torch::Tensor out_color = torch::zeros({C, H, W}, float_opts); + torch::Tensor out_depth = torch::zeros({H, W}, float_opts); + torch::Tensor out_alpha = torch::zeros({H, W}, float_opts); + + // Call Forward + if (P > 0) { + forward( + P, C, W, H, + positions.contiguous().data_ptr(), + attrs.contiguous().data_ptr(), + voxel_size, + viewmatrix.contiguous().data_ptr(), + projmatrix.contiguous().data_ptr(), + campos.contiguous().data_ptr(), + tan_fovx, tan_fovy, + out_color.contiguous().data_ptr(), + out_depth.contiguous().data_ptr(), + out_alpha.contiguous().data_ptr() + ); + } + + return std::make_tuple( + out_color, out_depth, out_alpha + ); +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/api.cu b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/api.cu new file mode 100644 index 0000000000000000000000000000000000000000..8a973bc4543ddb5751112006b9349769a0040872 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/api.cu @@ -0,0 +1,180 @@ +#include +#include "api.h" +#include "z_order.h" +#include "hilbert.h" + + +torch::Tensor +z_order_encode_cpu( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +) { + // Allocate output tensor + torch::Tensor codes = torch::empty_like(x, torch::dtype(torch::kInt32)); + + // Call CUDA kernel + CPU::z_order_encode( + x.size(0), + reinterpret_cast(x.contiguous().data_ptr()), + reinterpret_cast(y.contiguous().data_ptr()), + reinterpret_cast(z.contiguous().data_ptr()), + reinterpret_cast(codes.data_ptr()) + ); + + return codes; +} + + +std::tuple +z_order_decode_cpu( + const torch::Tensor& codes +) { + // Allocate output tensors + torch::Tensor x = torch::empty_like(codes, torch::dtype(torch::kInt32)); + torch::Tensor y = torch::empty_like(codes, torch::dtype(torch::kInt32)); + torch::Tensor z = torch::empty_like(codes, torch::dtype(torch::kInt32)); + + // Call CUDA kernel + CPU::z_order_decode( + codes.size(0), + reinterpret_cast(codes.contiguous().data_ptr()), + reinterpret_cast(x.data_ptr()), + reinterpret_cast(y.data_ptr()), + reinterpret_cast(z.data_ptr()) + ); + + return std::make_tuple(x, y, z); +} + + +torch::Tensor +hilbert_encode_cpu( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +) { + // Allocate output tensor + torch::Tensor codes = torch::empty_like(x); + + // Call CUDA kernel + CPU::hilbert_encode( + x.size(0), + reinterpret_cast(x.contiguous().data_ptr()), + reinterpret_cast(y.contiguous().data_ptr()), + reinterpret_cast(z.contiguous().data_ptr()), + reinterpret_cast(codes.data_ptr()) + ); + + return codes; +} + + +std::tuple +hilbert_decode_cpu( + const torch::Tensor& codes +) { + // Allocate output tensors + torch::Tensor x = torch::empty_like(codes); + torch::Tensor y = torch::empty_like(codes); + torch::Tensor z = torch::empty_like(codes); + + // Call CUDA kernel + CPU::hilbert_decode( + codes.size(0), + reinterpret_cast(codes.contiguous().data_ptr()), + reinterpret_cast(x.data_ptr()), + reinterpret_cast(y.data_ptr()), + reinterpret_cast(z.data_ptr()) + ); + + return std::make_tuple(x, y, z); +} + + +torch::Tensor +z_order_encode_cuda( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +) { + // Allocate output tensor + torch::Tensor codes = torch::empty_like(x, torch::dtype(torch::kInt32)); + + // Call CUDA kernel + CUDA::z_order_encode<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + x.size(0), + reinterpret_cast(x.contiguous().data_ptr()), + reinterpret_cast(y.contiguous().data_ptr()), + reinterpret_cast(z.contiguous().data_ptr()), + reinterpret_cast(codes.data_ptr()) + ); + + return codes; +} + + +std::tuple +z_order_decode_cuda( + const torch::Tensor& codes +) { + // Allocate output tensors + torch::Tensor x = torch::empty_like(codes, torch::dtype(torch::kInt32)); + torch::Tensor y = torch::empty_like(codes, torch::dtype(torch::kInt32)); + torch::Tensor z = torch::empty_like(codes, torch::dtype(torch::kInt32)); + + // Call CUDA kernel + CUDA::z_order_decode<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + codes.size(0), + reinterpret_cast(codes.contiguous().data_ptr()), + reinterpret_cast(x.data_ptr()), + reinterpret_cast(y.data_ptr()), + reinterpret_cast(z.data_ptr()) + ); + + return std::make_tuple(x, y, z); +} + + +torch::Tensor +hilbert_encode_cuda( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +) { + // Allocate output tensor + torch::Tensor codes = torch::empty_like(x); + + // Call CUDA kernel + CUDA::hilbert_encode<<<(x.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + x.size(0), + reinterpret_cast(x.contiguous().data_ptr()), + reinterpret_cast(y.contiguous().data_ptr()), + reinterpret_cast(z.contiguous().data_ptr()), + reinterpret_cast(codes.data_ptr()) + ); + + return codes; +} + + +std::tuple +hilbert_decode_cuda( + const torch::Tensor& codes +) { + // Allocate output tensors + torch::Tensor x = torch::empty_like(codes); + torch::Tensor y = torch::empty_like(codes); + torch::Tensor z = torch::empty_like(codes); + + // Call CUDA kernel + CUDA::hilbert_decode<<<(codes.size(0) + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE>>>( + codes.size(0), + reinterpret_cast(codes.contiguous().data_ptr()), + reinterpret_cast(x.data_ptr()), + reinterpret_cast(y.data_ptr()), + reinterpret_cast(z.data_ptr()) + ); + + return std::make_tuple(x, y, z); +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/api.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/api.h new file mode 100644 index 0000000000000000000000000000000000000000..70da702f3776354a7984169798ca9fdbf9d2d1a9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/api.h @@ -0,0 +1,136 @@ +/* + * Serialize a voxel grid + * + * Copyright (C) 2025, Jianfeng XIANG + * All rights reserved. + * + * Licensed under The MIT License [see LICENSE for details] + * + * Written by Jianfeng XIANG + */ + +#pragma once +#include + + +#define BLOCK_SIZE 256 + + +/** + * Z-order encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +torch::Tensor +z_order_encode_cuda( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +); + + +/** + * Z-order decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * + * @return 3 tensors [N] containing the x, y, z coordinates + */ +std::tuple +z_order_decode_cuda( + const torch::Tensor& codes +); + + +/** + * Hilbert encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the Hilbert encoded values + */ +torch::Tensor +hilbert_encode_cuda( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +); + + +/** + * Hilbert decode 3D points + * + * @param codes [N] tensor containing the Hilbert encoded values + * + * @return 3 tensors [N] containing the x, y, z coordinates + */ +std::tuple +hilbert_decode_cuda( + const torch::Tensor& codes +); + + +/** + * Z-order encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +torch::Tensor +z_order_encode_cpu( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +); + + +/** + * Z-order decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * + * @return 3 tensors [N] containing the x, y, z coordinates + */ +std::tuple +z_order_decode_cpu( + const torch::Tensor& codes +); + + +/** + * Hilbert encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the Hilbert encoded values + */ +torch::Tensor +hilbert_encode_cpu( + const torch::Tensor& x, + const torch::Tensor& y, + const torch::Tensor& z +); + + +/** + * Hilbert decode 3D points + * + * @param codes [N] tensor containing the Hilbert encoded values + * + * @return 3 tensors [N] containing the x, y, z coordinates + */ +std::tuple +hilbert_decode_cpu( + const torch::Tensor& codes +); diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/hilbert.cu b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/hilbert.cu new file mode 100644 index 0000000000000000000000000000000000000000..715b0569d1e0c803cf2742475b47b3ef07de25cd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/hilbert.cu @@ -0,0 +1,230 @@ +#include +#include + +#include +namespace cg = cooperative_groups; + +#include "hilbert.h" + + +// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit. +static __host__ __device__ uint32_t expandBits(uint32_t v) +{ + v = (v * 0x00010001u) & 0xFF0000FFu; + v = (v * 0x00000101u) & 0x0F00F00Fu; + v = (v * 0x00000011u) & 0xC30C30C3u; + v = (v * 0x00000005u) & 0x49249249u; + return v; +} + + +// Removes 2 zeros after each bit in a 30-bit integer. +static __host__ __device__ uint32_t extractBits(uint32_t v) +{ + v = v & 0x49249249; + v = (v ^ (v >> 2)) & 0x030C30C3u; + v = (v ^ (v >> 4)) & 0x0300F00Fu; + v = (v ^ (v >> 8)) & 0x030000FFu; + v = (v ^ (v >> 16)) & 0x000003FFu; + return v; +} + + +__host__ void CPU::hilbert_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +) { + for (size_t thread_id = 0; thread_id < N; thread_id++) { + uint32_t point[3] = {x[thread_id], y[thread_id], z[thread_id]}; + + uint32_t m = 1 << 9, q, p, t; + + // Inverse undo excess work + q = m; + while (q > 1) { + p = q - 1; + for (int i = 0; i < 3; i++) { + if (point[i] & q) { + point[0] ^= p; // invert + } else { + t = (point[0] ^ point[i]) & p; + point[0] ^= t; + point[i] ^= t; + } + } + q >>= 1; + } + + // Gray encode + for (int i = 1; i < 3; i++) { + point[i] ^= point[i - 1]; + } + t = 0; + q = m; + while (q > 1) { + if (point[2] & q) { + t ^= q - 1; + } + q >>= 1; + } + for (int i = 0; i < 3; i++) { + point[i] ^= t; + } + + // Convert to 3D Hilbert code + uint32_t xx = expandBits(point[0]); + uint32_t yy = expandBits(point[1]); + uint32_t zz = expandBits(point[2]); + + codes[thread_id] = xx * 4 + yy * 2 + zz; + } +} + + +__host__ void CPU::hilbert_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +) { + for (size_t thread_id = 0; thread_id < N; thread_id++) { + uint32_t point[3]; + point[0] = extractBits(codes[thread_id] >> 2); + point[1] = extractBits(codes[thread_id] >> 1); + point[2] = extractBits(codes[thread_id]); + + uint32_t m = 2 << 9, q, p, t; + + // Gray decode by H ^ (H/2) + t = point[2] >> 1; + for (int i = 2; i > 0; i--) { + point[i] ^= point[i - 1]; + } + point[0] ^= t; + + // Undo excess work + q = 2; + while (q != m) { + p = q - 1; + for (int i = 2; i >= 0; i--) { + if (point[i] & q) { + point[0] ^= p; + } else { + t = (point[0] ^ point[i]) & p; + point[0] ^= t; + point[i] ^= t; + } + } + q <<= 1; + } + + x[thread_id] = point[0]; + y[thread_id] = point[1]; + z[thread_id] = point[2]; + } +} + + +__global__ void CUDA::hilbert_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + uint32_t point[3] = {x[thread_id], y[thread_id], z[thread_id]}; + + uint32_t m = 1 << 9, q, p, t; + + // Inverse undo excess work + q = m; + while (q > 1) { + p = q - 1; + for (int i = 0; i < 3; i++) { + if (point[i] & q) { + point[0] ^= p; // invert + } else { + t = (point[0] ^ point[i]) & p; + point[0] ^= t; + point[i] ^= t; + } + } + q >>= 1; + } + + // Gray encode + for (int i = 1; i < 3; i++) { + point[i] ^= point[i - 1]; + } + t = 0; + q = m; + while (q > 1) { + if (point[2] & q) { + t ^= q - 1; + } + q >>= 1; + } + for (int i = 0; i < 3; i++) { + point[i] ^= t; + } + + // Convert to 3D Hilbert code + uint32_t xx = expandBits(point[0]); + uint32_t yy = expandBits(point[1]); + uint32_t zz = expandBits(point[2]); + + codes[thread_id] = xx * 4 + yy * 2 + zz; +} + + +__global__ void CUDA::hilbert_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + uint32_t point[3]; + point[0] = extractBits(codes[thread_id] >> 2); + point[1] = extractBits(codes[thread_id] >> 1); + point[2] = extractBits(codes[thread_id]); + + uint32_t m = 2 << 9, q, p, t; + + // Gray decode by H ^ (H/2) + t = point[2] >> 1; + for (int i = 2; i > 0; i--) { + point[i] ^= point[i - 1]; + } + point[0] ^= t; + + // Undo excess work + q = 2; + while (q != m) { + p = q - 1; + for (int i = 2; i >= 0; i--) { + if (point[i] & q) { + point[0] ^= p; + } else { + t = (point[0] ^ point[i]) & p; + point[0] ^= t; + point[i] ^= t; + } + } + q <<= 1; + } + + x[thread_id] = point[0]; + y[thread_id] = point[1]; + z[thread_id] = point[2]; +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/hilbert.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/hilbert.h new file mode 100644 index 0000000000000000000000000000000000000000..55f5bc000474361045cdb4a2202b41045d4a0a03 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/hilbert.h @@ -0,0 +1,74 @@ +#pragma once + +namespace CUDA { +/** + * Hilbert encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +__global__ void hilbert_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +); + + +/** + * Hilbert decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + */ +__global__ void hilbert_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +); +} // namespace CUDA + + +namespace CPU { +/** + * Hilbert encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +__host__ void hilbert_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +); + + +/** + * Hilbert decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + */ +__host__ void hilbert_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +); +} // namespace CPU diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/z_order.cu b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/z_order.cu new file mode 100644 index 0000000000000000000000000000000000000000..d4ae1181fee2ffed19576ac3b38e6f2d39533d2e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/z_order.cu @@ -0,0 +1,97 @@ +#include +#include + +#include +namespace cg = cooperative_groups; + +#include "z_order.h" + + +// Expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit. +static __host__ __device__ uint32_t expandBits(uint32_t v) +{ + v = (v * 0x00010001u) & 0xFF0000FFu; + v = (v * 0x00000101u) & 0x0F00F00Fu; + v = (v * 0x00000011u) & 0xC30C30C3u; + v = (v * 0x00000005u) & 0x49249249u; + return v; +} + + +// Removes 2 zeros after each bit in a 30-bit integer. +static __host__ __device__ uint32_t extractBits(uint32_t v) +{ + v = v & 0x49249249; + v = (v ^ (v >> 2)) & 0x030C30C3u; + v = (v ^ (v >> 4)) & 0x0300F00Fu; + v = (v ^ (v >> 8)) & 0x030000FFu; + v = (v ^ (v >> 16)) & 0x000003FFu; + return v; +} + + +__host__ void CPU::z_order_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +) { + for (size_t thread_id = 0; thread_id < N; thread_id++) { + uint32_t xx = expandBits(x[thread_id]); + uint32_t yy = expandBits(y[thread_id]); + uint32_t zz = expandBits(z[thread_id]); + + codes[thread_id] = xx * 4 + yy * 2 + zz; + } +} + + +__host__ void CPU::z_order_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +) { + for (size_t thread_id = 0; thread_id < N; thread_id++) { + x[thread_id] = extractBits(codes[thread_id] >> 2); + y[thread_id] = extractBits(codes[thread_id] >> 1); + z[thread_id] = extractBits(codes[thread_id]); + } +} + + + +__global__ void CUDA::z_order_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + uint32_t xx = expandBits(x[thread_id]); + uint32_t yy = expandBits(y[thread_id]); + uint32_t zz = expandBits(z[thread_id]); + + codes[thread_id] = xx * 4 + yy * 2 + zz; +} + + +__global__ void CUDA::z_order_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +) { + size_t thread_id = cg::this_grid().thread_rank(); + if (thread_id >= N) return; + + x[thread_id] = extractBits(codes[thread_id] >> 2); + y[thread_id] = extractBits(codes[thread_id] >> 1); + z[thread_id] = extractBits(codes[thread_id]); +} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/z_order.h b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/z_order.h new file mode 100644 index 0000000000000000000000000000000000000000..5ae9c22ccac43fb78609795c7cbd54b8e822cd7a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/src/serialize/z_order.h @@ -0,0 +1,74 @@ +#pragma once + +namespace CUDA { +/** + * Z-order encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +__global__ void z_order_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +); + + +/** + * Z-order decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + */ +__global__ void z_order_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +); +} // namespace CUDA + + +namespace CPU { +/** + * Z-order encode 3D points + * + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + * + * @return [N] tensor containing the z-order encoded values + */ +__host__ void z_order_encode( + size_t N, + const uint32_t* x, + const uint32_t* y, + const uint32_t* z, + uint32_t* codes +); + + +/** + * Z-order decode 3D points + * + * @param codes [N] tensor containing the z-order encoded values + * @param x [N] tensor containing the x coordinates + * @param y [N] tensor containing the y coordinates + * @param z [N] tensor containing the z coordinates + */ +__host__ void z_order_decode( + size_t N, + const uint32_t* codes, + uint32_t* x, + uint32_t* y, + uint32_t* z +); +} // namespace CPU diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/setup.sh b/OVOW/engine/oneposeviagen/TRELLIS2/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..e09e2b1d8bd3f2e89b87c211ebbaa0b3ce881d8d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/setup.sh @@ -0,0 +1,139 @@ +# Read Arguments +TEMP=`getopt -o h --long help,new-env,basic,flash-attn,cumesh,o-voxel,flexgemm,nvdiffrast,nvdiffrec -n 'setup.sh' -- "$@"` + +eval set -- "$TEMP" + +HELP=false +NEW_ENV=false +BASIC=false +FLASHATTN=false +CUMESH=false +OVOXEL=false +FLEXGEMM=false +NVDIFFRAST=false +NVDIFFREC=false +ERROR=false + + +if [ "$#" -eq 1 ] ; then + HELP=true +fi + +while true ; do + case "$1" in + -h|--help) HELP=true ; shift ;; + --new-env) NEW_ENV=true ; shift ;; + --basic) BASIC=true ; shift ;; + --flash-attn) FLASHATTN=true ; shift ;; + --cumesh) CUMESH=true ; shift ;; + --o-voxel) OVOXEL=true ; shift ;; + --flexgemm) FLEXGEMM=true ; shift ;; + --nvdiffrast) NVDIFFRAST=true ; shift ;; + --nvdiffrec) NVDIFFREC=true ; shift ;; + --) shift ; break ;; + *) ERROR=true ; break ;; + esac +done + +if [ "$ERROR" = true ] ; then + echo "Error: Invalid argument" + HELP=true +fi + +if [ "$HELP" = true ] ; then + echo "Usage: setup.sh [OPTIONS]" + echo "Options:" + echo " -h, --help Display this help message" + echo " --new-env Create a new conda environment" + echo " --basic Install basic dependencies" + echo " --flash-attn Install flash-attention" + echo " --cumesh Install cumesh" + echo " --o-voxel Install o-voxel" + echo " --flexgemm Install flexgemm" + echo " --nvdiffrast Install nvdiffrast" + echo " --nvdiffrec Install nvdiffrec" + return +fi + +# Get system information +WORKDIR=$(pwd) +if command -v nvidia-smi > /dev/null; then + PLATFORM="cuda" +elif command -v rocminfo > /dev/null; then + PLATFORM="hip" +else + echo "Error: No supported GPU found" + exit 1 +fi + +if [ "$NEW_ENV" = true ] ; then + conda create -n trellis2 python=3.10 + conda activate trellis2 + if [ "$PLATFORM" = "cuda" ] ; then + pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cu124 + elif [ "$PLATFORM" = "hip" ] ; then + pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/rocm6.2.4 + fi +fi + +if [ "$BASIC" = true ] ; then + pip install imageio imageio-ffmpeg tqdm easydict opencv-python-headless ninja trimesh transformers gradio==6.0.1 tensorboard pandas lpips zstandard + pip install git+https://github.com/EasternJournalist/utils3d.git@9a4eb15e4021b67b12c460c7057d642626897ec8 + sudo apt install -y libjpeg-dev + pip install pillow-simd + pip install kornia timm +fi + +if [ "$FLASHATTN" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + pip install flash-attn==2.7.3 + elif [ "$PLATFORM" = "hip" ] ; then + echo "[FLASHATTN] Prebuilt binaries not found. Building from source..." + mkdir -p /tmp/extensions + git clone --recursive https://github.com/ROCm/flash-attention.git /tmp/extensions/flash-attention + cd /tmp/extensions/flash-attention + git checkout tags/v2.7.3-cktile + GPU_ARCHS=gfx942 python setup.py install #MI300 series + cd $WORKDIR + else + echo "[FLASHATTN] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$NVDIFFRAST" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + mkdir -p /tmp/extensions + git clone -b v0.4.0 https://github.com/NVlabs/nvdiffrast.git /tmp/extensions/nvdiffrast + pip install /tmp/extensions/nvdiffrast --no-build-isolation + else + echo "[NVDIFFRAST] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$NVDIFFREC" = true ] ; then + if [ "$PLATFORM" = "cuda" ] ; then + mkdir -p /tmp/extensions + git clone -b renderutils https://github.com/JeffreyXiang/nvdiffrec.git /tmp/extensions/nvdiffrec + pip install /tmp/extensions/nvdiffrec --no-build-isolation + else + echo "[NVDIFFREC] Unsupported platform: $PLATFORM" + fi +fi + +if [ "$CUMESH" = true ] ; then + mkdir -p /tmp/extensions + git clone https://github.com/JeffreyXiang/CuMesh.git /tmp/extensions/CuMesh --recursive + pip install /tmp/extensions/CuMesh --no-build-isolation +fi + +if [ "$FLEXGEMM" = true ] ; then + mkdir -p /tmp/extensions + git clone https://github.com/JeffreyXiang/FlexGEMM.git /tmp/extensions/FlexGEMM --recursive + pip install /tmp/extensions/FlexGEMM --no-build-isolation +fi + +if [ "$OVOXEL" = true ] ; then + mkdir -p /tmp/extensions + cp -r o-voxel /tmp/extensions/o-voxel + pip install /tmp/extensions/o-voxel --no-build-isolation +fi diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/train.py b/OVOW/engine/oneposeviagen/TRELLIS2/train.py new file mode 100644 index 0000000000000000000000000000000000000000..258be3c4126c16c92e6a8370900b0d4d342bfeab --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/train.py @@ -0,0 +1,158 @@ +import os +import sys +import json +import glob +import argparse +from easydict import EasyDict as edict + +import torch +import torch.multiprocessing as mp +import numpy as np +import random + +from trellis2 import models, datasets, trainers +from trellis2.utils.dist_utils import setup_dist + + +def find_ckpt(cfg): + # Load checkpoint + cfg['load_ckpt'] = None + if cfg.load_dir != '': + if cfg.ckpt == 'latest': + files = glob.glob(os.path.join(cfg.load_dir, 'ckpts', 'misc_*.pt')) + if len(files) != 0: + cfg.load_ckpt = max([ + int(os.path.basename(f).split('step')[-1].split('.')[0]) + for f in files + ]) + elif cfg.ckpt == 'none': + cfg.load_ckpt = None + else: + cfg.load_ckpt = int(cfg.ckpt) + return cfg + + +def setup_rng(rank): + torch.manual_seed(rank) + torch.cuda.manual_seed_all(rank) + np.random.seed(rank) + random.seed(rank) + + +def get_model_summary(model): + model_summary = 'Parameters:\n' + model_summary += '=' * 128 + '\n' + model_summary += f'{"Name":<{72}}{"Shape":<{32}}{"Type":<{16}}{"Grad"}\n' + num_params = 0 + num_trainable_params = 0 + for name, param in model.named_parameters(): + model_summary += f'{name:<{72}}{str(param.shape):<{32}}{str(param.dtype):<{16}}{param.requires_grad}\n' + num_params += param.numel() + if param.requires_grad: + num_trainable_params += param.numel() + model_summary += '\n' + model_summary += f'Number of parameters: {num_params}\n' + model_summary += f'Number of trainable parameters: {num_trainable_params}\n' + return model_summary + + +def main(local_rank, cfg): + # Set up distributed training + rank = cfg.node_rank * cfg.num_gpus + local_rank + world_size = cfg.num_nodes * cfg.num_gpus + if world_size > 1: + setup_dist(rank, local_rank, world_size, cfg.master_addr, cfg.master_port) + + # Seed rngs + setup_rng(rank) + + # Load data + dataset = getattr(datasets, cfg.dataset.name)(cfg.data_dir, **cfg.dataset.args) + + # Build model + model_dict = { + name: getattr(models, model.name)(**model.args).cuda() + for name, model in cfg.models.items() + } + + # Model summary + if rank == 0: + for name, backbone in model_dict.items(): + model_summary = get_model_summary(backbone) + print(f'\n\nBackbone: {name}\n' + model_summary) + with open(os.path.join(cfg.output_dir, f'{name}_model_summary.txt'), 'w') as fp: + print(model_summary, file=fp) + + # Build trainer + trainer = getattr(trainers, cfg.trainer.name)(model_dict, dataset, **cfg.trainer.args, output_dir=cfg.output_dir, load_dir=cfg.load_dir, step=cfg.load_ckpt) + + # Train + if not cfg.tryrun: + if cfg.profile: + trainer.profile() + else: + trainer.run() + + +if __name__ == '__main__': + # Arguments and config + parser = argparse.ArgumentParser() + ## config + parser.add_argument('--config', type=str, required=True, help='Experiment config file') + ## io and resume + parser.add_argument('--output_dir', type=str, required=True, help='Output directory') + parser.add_argument('--load_dir', type=str, default='', help='Load directory, default to output_dir') + parser.add_argument('--ckpt', type=str, default='latest', help='Checkpoint step to resume training, default to latest') + parser.add_argument('--data_dir', type=str, default='./data/', help='Data directory') + parser.add_argument('--auto_retry', type=int, default=3, help='Number of retries on error') + ## dubug + parser.add_argument('--tryrun', action='store_true', help='Try run without training') + parser.add_argument('--profile', action='store_true', help='Profile training') + ## multi-node and multi-gpu + parser.add_argument('--num_nodes', type=int, default=1, help='Number of nodes') + parser.add_argument('--node_rank', type=int, default=0, help='Node rank') + parser.add_argument('--num_gpus', type=int, default=-1, help='Number of GPUs per node, default to all') + parser.add_argument('--master_addr', type=str, default='localhost', help='Master address for distributed training') + parser.add_argument('--master_port', type=str, default='12345', help='Port for distributed training') + opt = parser.parse_args() + opt.load_dir = opt.load_dir if opt.load_dir != '' else opt.output_dir + opt.num_gpus = torch.cuda.device_count() if opt.num_gpus == -1 else opt.num_gpus + ## Load config + config = json.load(open(opt.config, 'r')) + ## Combine arguments and config + cfg = edict() + cfg.update(opt.__dict__) + cfg.update(config) + print('\n\nConfig:') + print('=' * 80) + print(json.dumps(cfg.__dict__, indent=4)) + + # Prepare output directory + if cfg.node_rank == 0: + os.makedirs(cfg.output_dir, exist_ok=True) + ## Save command and config + with open(os.path.join(cfg.output_dir, 'command.txt'), 'w') as fp: + print(' '.join(['python'] + sys.argv), file=fp) + with open(os.path.join(cfg.output_dir, 'config.json'), 'w') as fp: + json.dump(config, fp, indent=4) + + # Run + if cfg.auto_retry == 0: + cfg = find_ckpt(cfg) + if cfg.num_gpus > 1: + mp.spawn(main, args=(cfg,), nprocs=cfg.num_gpus, join=True) + else: + main(0, cfg) + else: + for rty in range(cfg.auto_retry): + try: + cfg = find_ckpt(cfg) + if cfg.num_gpus > 1: + mp.spawn(main, args=(cfg,), nprocs=cfg.num_gpus, join=True) + else: + main(0, cfg) + break + except Exception as e: + print(f'Error: {e}') + print(f'Retrying ({rty + 1}/{cfg.auto_retry})...') + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20d240afc9c26a21aee76954628b3d4ef9a1ccbd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/__init__.py @@ -0,0 +1,6 @@ +from . import models +from . import modules +from . import pipelines +from . import renderers +from . import representations +from . import utils diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f7d9487d8d83f085146d037ccd5291bfb9419b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/__init__.py @@ -0,0 +1,46 @@ +import importlib + +__attributes = { + 'FlexiDualGridDataset': 'flexi_dual_grid', + 'SparseVoxelPbrDataset':'sparse_voxel_pbr', + + 'SparseStructureLatent': 'sparse_structure_latent', + 'TextConditionedSparseStructureLatent': 'sparse_structure_latent', + 'ImageConditionedSparseStructureLatent': 'sparse_structure_latent', + + 'SLat': 'structured_latent', + 'ImageConditionedSLat': 'structured_latent', + 'SLatShape': 'structured_latent_shape', + 'ImageConditionedSLatShape': 'structured_latent_shape', + 'SLatPbr': 'structured_latent_svpbr', + 'ImageConditionedSLatPbr': 'structured_latent_svpbr', +} + +__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] + + +# For Pylance +if __name__ == '__main__': + from .flexi_dual_grid import FlexiDualGridDataset + from .sparse_voxel_pbr import SparseVoxelPbrDataset + + from .sparse_structure_latent import SparseStructureLatent, ImageConditionedSparseStructureLatent + from .structured_latent import SLat, ImageConditionedSLat + from .structured_latent_shape import SLatShape, ImageConditionedSLatShape + from .structured_latent_svpbr import SLatPbr, ImageConditionedSLatPbr + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/components.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/components.py new file mode 100644 index 0000000000000000000000000000000000000000..6c593cee959ed91de1c3c11b8930b98ec0967582 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/components.py @@ -0,0 +1,192 @@ +from typing import * +import json +from abc import abstractmethod +import os +import json +import torch +import numpy as np +import pandas as pd +from PIL import Image +from torch.utils.data import Dataset + + +class StandardDatasetBase(Dataset): + """ + Base class for standard datasets. + + Args: + roots (str): paths to the dataset + """ + + def __init__(self, + roots: str, + ): + super().__init__() + try: + self.roots = json.loads(roots) + root_type = 'obj' + except: + self.roots = roots.split(',') + root_type = 'list' + self.instances = [] + self.metadata = pd.DataFrame() + + self._stats = {} + if root_type == 'obj': + for key, root in self.roots.items(): + self._stats[key] = {} + metadata = pd.DataFrame(columns=['sha256']).set_index('sha256') + for _, r in root.items(): + metadata = metadata.combine_first(pd.read_csv(os.path.join(r, 'metadata.csv')).set_index('sha256')) + self._stats[key]['Total'] = len(metadata) + metadata, stats = self.filter_metadata(metadata) + self._stats[key].update(stats) + self.instances.extend([(root, sha256) for sha256 in metadata.index.values]) + self.metadata = pd.concat([self.metadata, metadata]) + else: + for root in self.roots: + key = os.path.basename(root) + self._stats[key] = {} + metadata = pd.read_csv(os.path.join(root, 'metadata.csv')) + self._stats[key]['Total'] = len(metadata) + metadata, stats = self.filter_metadata(metadata) + self._stats[key].update(stats) + self.instances.extend([(root, sha256) for sha256 in metadata['sha256'].values]) + metadata.set_index('sha256', inplace=True) + self.metadata = pd.concat([self.metadata, metadata]) + + @abstractmethod + def filter_metadata(self, metadata: pd.DataFrame) -> Tuple[pd.DataFrame, Dict[str, int]]: + pass + + @abstractmethod + def get_instance(self, root, instance: str) -> Dict[str, Any]: + pass + + def __len__(self): + return len(self.instances) + + def __getitem__(self, index) -> Dict[str, Any]: + try: + root, instance = self.instances[index] + return self.get_instance(root, instance) + except Exception as e: + print(f'Error loading {instance}: {e}') + return self.__getitem__(np.random.randint(0, len(self))) + + def __str__(self): + lines = [] + lines.append(self.__class__.__name__) + lines.append(f' - Total instances: {len(self)}') + lines.append(f' - Sources:') + for key, stats in self._stats.items(): + lines.append(f' - {key}:') + for k, v in stats.items(): + lines.append(f' - {k}: {v}') + return '\n'.join(lines) + + +class ImageConditionedMixin: + def __init__(self, roots, *, image_size=518, **kwargs): + self.image_size = image_size + super().__init__(roots, **kwargs) + + def filter_metadata(self, metadata): + metadata, stats = super().filter_metadata(metadata) + metadata = metadata[metadata['cond_rendered'].notna()] + stats['Cond rendered'] = len(metadata) + return metadata, stats + + def get_instance(self, root, instance): + pack = super().get_instance(root, instance) + + image_root = os.path.join(root['render_cond'], instance) + with open(os.path.join(image_root, 'transforms.json')) as f: + metadata = json.load(f) + n_views = len(metadata['frames']) + view = np.random.randint(n_views) + metadata = metadata['frames'][view] + + image_path = os.path.join(image_root, metadata['file_path']) + image = Image.open(image_path) + + alpha = np.array(image.getchannel(3)) + bbox = np.array(alpha).nonzero() + bbox = [bbox[1].min(), bbox[0].min(), bbox[1].max(), bbox[0].max()] + center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] + hsize = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 2 + aug_hsize = hsize + aug_center_offset = [0, 0] + aug_center = [center[0] + aug_center_offset[0], center[1] + aug_center_offset[1]] + 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)] + image = image.crop(aug_bbox) + + image = image.resize((self.image_size, self.image_size), Image.Resampling.LANCZOS) + alpha = image.getchannel(3) + image = image.convert('RGB') + image = torch.tensor(np.array(image)).permute(2, 0, 1).float() / 255.0 + alpha = torch.tensor(np.array(alpha)).float() / 255.0 + image = image * alpha.unsqueeze(0) + pack['cond'] = image + + return pack + + +class MultiImageConditionedMixin: + def __init__(self, roots, *, image_size=518, max_image_cond_view = 4, **kwargs): + self.image_size = image_size + self.max_image_cond_view = max_image_cond_view + super().__init__(roots, **kwargs) + + def filter_metadata(self, metadata): + metadata, stats = super().filter_metadata(metadata) + metadata = metadata[metadata['cond_rendered'].notna()] + stats['Cond rendered'] = len(metadata) + return metadata, stats + + def get_instance(self, root, instance): + pack = super().get_instance(root, instance) + + image_root = os.path.join(root['render_cond'], instance) + with open(os.path.join(image_root, 'transforms.json')) as f: + metadata = json.load(f) + + n_views = len(metadata['frames']) + n_sample_views = np.random.randint(1, self.max_image_cond_view+1) + + assert n_views >= n_sample_views, f'Not enough views to sample {n_sample_views} unique images.' + + sampled_views = np.random.choice(n_views, size=n_sample_views, replace=False) + + cond_images = [] + for v in sampled_views: + frame_info = metadata['frames'][v] + image_path = os.path.join(image_root, frame_info['file_path']) + image = Image.open(image_path) + + alpha = np.array(image.getchannel(3)) + bbox = np.array(alpha).nonzero() + bbox = [bbox[1].min(), bbox[0].min(), bbox[1].max(), bbox[0].max()] + center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] + hsize = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 2 + aug_hsize = hsize + aug_center = center + 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), + ] + + img = image.crop(aug_bbox) + img = img.resize((self.image_size, self.image_size), Image.Resampling.LANCZOS) + alpha = img.getchannel(3) + img = img.convert('RGB') + img = torch.tensor(np.array(img)).permute(2, 0, 1).float() / 255.0 + alpha = torch.tensor(np.array(alpha)).float() / 255.0 + img = img * alpha.unsqueeze(0) + + cond_images.append(img) + + pack['cond'] = [torch.stack(cond_images, dim=0)] # (V,3,H,W) + return pack diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/flexi_dual_grid.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/flexi_dual_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..f870d83bfd3d51856943e1dec215bbf7d5b1924b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/flexi_dual_grid.py @@ -0,0 +1,173 @@ +import os +import numpy as np +import pickle +import torch +import utils3d +from .components import StandardDatasetBase +from ..modules import sparse as sp +from ..renderers import MeshRenderer +from ..representations import Mesh +from ..utils.data_utils import load_balanced_group_indices +import o_voxel + + +class FlexiDualGridVisMixin: + @torch.no_grad() + def visualize_sample(self, x: dict): + mesh = x['mesh'] + + renderer = MeshRenderer({'near': 1, 'far': 3}) + renderer.rendering_options.resolution = 512 + renderer.rendering_options.ssaa = 4 + + # Build camera + yaws = [0, np.pi / 2, np.pi, 3 * np.pi / 2] + yaws_offset = np.random.uniform(-np.pi / 4, np.pi / 4) + yaws = [y + yaws_offset for y in yaws] + pitch = [np.random.uniform(-np.pi / 4, np.pi / 4) for _ in range(4)] + + exts = [] + ints = [] + for yaw, pitch in zip(yaws, pitch): + orig = torch.tensor([ + np.sin(yaw) * np.cos(pitch), + np.cos(yaw) * np.cos(pitch), + np.sin(pitch), + ]).float().cuda() * 2 + fov = torch.deg2rad(torch.tensor(30)).cuda() + extrinsics = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda()) + intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + exts.append(extrinsics) + ints.append(intrinsics) + + # Build each representation + images = [] + for m in mesh: + image = torch.zeros(3, 1024, 1024).cuda() + tile = [2, 2] + for j, (ext, intr) in enumerate(zip(exts, ints)): + image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = \ + renderer.render(m.cuda(), ext, intr)['normal'] + images.append(image) + images = torch.stack(images) + + return images + + +class FlexiDualGridDataset(FlexiDualGridVisMixin, StandardDatasetBase): + """ + Flexible Dual Grid Dataset + + Args: + roots (str): path to the dataset + resolution (int): resolution of the voxel grid + min_aesthetic_score (float): minimum aesthetic score of the instances to be included in the dataset + """ + + def __init__( + self, + roots, + resolution: int = 1024, + max_active_voxels: int = 1000000, + max_num_faces: int = None, + min_aesthetic_score: float = 5.0, + ): + self.resolution = resolution + self.min_aesthetic_score = min_aesthetic_score + self.max_active_voxels = max_active_voxels + self.max_num_faces = max_num_faces + self.value_range = (0, 1) + + super().__init__(roots) + + self.loads = [self.metadata.loc[sha256, f'dual_grid_size'] for _, sha256 in self.instances] + + def __str__(self): + lines = [ + super().__str__(), + f' - Resolution: {self.resolution}', + ] + return '\n'.join(lines) + + def filter_metadata(self, metadata): + stats = {} + metadata = metadata[metadata[f'dual_grid_converted'] == True] + stats['Dual Grid Converted'] = len(metadata) + if self.min_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score] + stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata) + metadata = metadata[metadata[f'dual_grid_size'] <= self.max_active_voxels] + stats[f'Active Voxels <= {self.max_active_voxels}'] = len(metadata) + if self.max_num_faces is not None: + metadata = metadata[metadata['num_faces'] <= self.max_num_faces] + stats[f'Faces <= {self.max_num_faces}'] = len(metadata) + return metadata, stats + + def read_mesh(self, root, instance): + with open(os.path.join(root, f'{instance}.pickle'), 'rb') as f: + dump = pickle.load(f) + start = 0 + vertices = [] + faces = [] + for obj in dump['objects']: + if obj['vertices'].size == 0 or obj['faces'].size == 0: + continue + vertices.append(obj['vertices']) + faces.append(obj['faces'] + start) + start += len(obj['vertices']) + vertices = torch.from_numpy(np.concatenate(vertices, axis=0)).float() + faces = torch.from_numpy(np.concatenate(faces, axis=0)).long() + vertices_min = vertices.min(dim=0)[0] + vertices_max = vertices.max(dim=0)[0] + center = (vertices_min + vertices_max) / 2 + scale = 0.99999 / (vertices_max - vertices_min).max() + vertices = (vertices - center) * scale + assert torch.all(vertices >= -0.5) and torch.all(vertices <= 0.5), 'vertices out of range' + return {'mesh': [Mesh(vertices=vertices, faces=faces)]} + + def read_dual_grid(self, root, instance): + coords, attr = o_voxel.io.read_vxz(os.path.join(root, f'{instance}.vxz'), num_threads=4) + vertices = sp.SparseTensor( + (attr['vertices'] / 255.0).float(), + torch.cat([torch.zeros_like(coords[:, 0:1]), coords], dim=-1), + ) + intersected = vertices.replace(torch.cat([ + attr['intersected'] % 2, + attr['intersected'] // 2 % 2, + attr['intersected'] // 4 % 2, + ], dim=-1).bool()) + return {'vertices': vertices, 'intersected': intersected} + + def get_instance(self, root, instance): + mesh = self.read_mesh(root['mesh_dump'], instance) + dual_grid = self.read_dual_grid(root['dual_grid'], instance) + return {**mesh, **dual_grid} + + @staticmethod + def collate_fn(batch, split_size=None): + if split_size is None: + group_idx = [list(range(len(batch)))] + else: + group_idx = load_balanced_group_indices([b['vertices'].feats.shape[0] for b in batch], split_size) + packs = [] + for group in group_idx: + sub_batch = [batch[i] for i in group] + pack = {} + + keys = [k for k in sub_batch[0].keys()] + for k in keys: + if isinstance(sub_batch[0][k], torch.Tensor): + pack[k] = torch.stack([b[k] for b in sub_batch]) + elif isinstance(sub_batch[0][k], sp.SparseTensor): + pack[k] = sp.sparse_cat([b[k] for b in sub_batch], dim=0) + elif isinstance(sub_batch[0][k], list): + pack[k] = sum([b[k] for b in sub_batch], []) + else: + pack[k] = [b[k] for b in sub_batch] + + packs.append(pack) + + if split_size is None: + return packs[0] + return packs + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/sparse_structure_latent.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/sparse_structure_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..498e1158c429f0eed723c36f263a56719e9124fa --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/sparse_structure_latent.py @@ -0,0 +1,160 @@ +import os +import json +from typing import * +import numpy as np +import torch +from ..representations import Voxel +from ..renderers import VoxelRenderer +from .components import StandardDatasetBase, ImageConditionedMixin +from .. import models +from ..utils.render_utils import yaw_pitch_r_fov_to_extrinsics_intrinsics + + +class SparseStructureLatentVisMixin: + def __init__( + self, + *args, + pretrained_ss_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16.json', + ss_dec_path: Optional[str] = None, + ss_dec_ckpt: Optional[str] = None, + **kwargs + ): + super().__init__(*args, **kwargs) + self.ss_dec = None + self.pretrained_ss_dec = pretrained_ss_dec + self.ss_dec_path = ss_dec_path + self.ss_dec_ckpt = ss_dec_ckpt + + def _loading_ss_dec(self): + if self.ss_dec is not None: + return + if self.ss_dec_path is not None: + cfg = json.load(open(os.path.join(self.ss_dec_path, 'config.json'), 'r')) + decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args']) + ckpt_path = os.path.join(self.ss_dec_path, 'ckpts', f'decoder_{self.ss_dec_ckpt}.pt') + decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True)) + else: + decoder = models.from_pretrained(self.pretrained_ss_dec) + self.ss_dec = decoder.cuda().eval() + + def _delete_ss_dec(self): + del self.ss_dec + self.ss_dec = None + + @torch.no_grad() + def decode_latent(self, z, batch_size=4): + self._loading_ss_dec() + ss = [] + if self.normalization: + z = z * self.std.to(z.device) + self.mean.to(z.device) + for i in range(0, z.shape[0], batch_size): + ss.append(self.ss_dec(z[i:i+batch_size])) + ss = torch.cat(ss, dim=0) + self._delete_ss_dec() + return ss + + @torch.no_grad() + def visualize_sample(self, x_0: Union[torch.Tensor, dict]): + x_0 = x_0 if isinstance(x_0, torch.Tensor) else x_0['x_0'] + x_0 = self.decode_latent(x_0.cuda()) + + renderer = VoxelRenderer() + renderer.rendering_options.resolution = 512 + renderer.rendering_options.ssaa = 4 + + # build camera + yaw = [0, np.pi/2, np.pi, 3*np.pi/2] + yaw_offset = -16 / 180 * np.pi + yaw = [y + yaw_offset for y in yaw] + pitch = [20 / 180 * np.pi for _ in range(4)] + exts, ints = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, 2, 30) + + images = [] + + # Build each representation + x_0 = x_0.cuda() + for i in range(x_0.shape[0]): + coords = torch.nonzero(x_0[i, 0] > 0, as_tuple=False) + resolution = x_0.shape[-1] + color = coords / resolution + rep = Voxel( + origin=[-0.5, -0.5, -0.5], + voxel_size=1/resolution, + coords=coords, + attrs=color, + layout={ + 'color': slice(0, 3), + } + ) + image = torch.zeros(3, 1024, 1024).cuda() + tile = [2, 2] + for j, (ext, intr) in enumerate(zip(exts, ints)): + res = renderer.render(rep, ext, intr, colors_overwrite=color) + image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['color'] + images.append(image) + + return torch.stack(images) + + +class SparseStructureLatent(SparseStructureLatentVisMixin, StandardDatasetBase): + """ + Sparse structure latent dataset + + Args: + roots (str): path to the dataset + min_aesthetic_score (float): minimum aesthetic score + normalization (dict): normalization stats + pretrained_ss_dec (str): name of the pretrained sparse structure decoder + ss_dec_path (str): path to the sparse structure decoder, if given, will override the pretrained_ss_dec + ss_dec_ckpt (str): name of the sparse structure decoder checkpoint + """ + def __init__(self, + roots: str, + *, + min_aesthetic_score: float = 5.0, + normalization: Optional[dict] = None, + pretrained_ss_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16', + ss_dec_path: Optional[str] = None, + ss_dec_ckpt: Optional[str] = None, + ): + self.min_aesthetic_score = min_aesthetic_score + self.normalization = normalization + self.value_range = (0, 1) + + super().__init__( + roots, + pretrained_ss_dec=pretrained_ss_dec, + ss_dec_path=ss_dec_path, + ss_dec_ckpt=ss_dec_ckpt, + ) + + if self.normalization is not None: + self.mean = torch.tensor(self.normalization['mean']).reshape(-1, 1, 1, 1) + self.std = torch.tensor(self.normalization['std']).reshape(-1, 1, 1, 1) + + def filter_metadata(self, metadata): + stats = {} + metadata = metadata[metadata['ss_latent_encoded'] == True] + stats['With latent'] = len(metadata) + metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score] + stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata) + return metadata, stats + + def get_instance(self, root, instance): + latent = np.load(os.path.join(root['ss_latent'], f'{instance}.npz')) + z = torch.tensor(latent['z']).float() + if self.normalization is not None: + z = (z - self.mean) / self.std + + pack = { + 'x_0': z, + } + return pack + + +class ImageConditionedSparseStructureLatent(ImageConditionedMixin, SparseStructureLatent): + """ + Image-conditioned sparse structure dataset + """ + pass + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/sparse_voxel_pbr.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/sparse_voxel_pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..053cc729678b844b595d68e92305ed055e8bea8e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/sparse_voxel_pbr.py @@ -0,0 +1,298 @@ +import os +import io +from typing import Union +import numpy as np +import pickle +import torch +from PIL import Image +import o_voxel +import utils3d +from .components import StandardDatasetBase +from ..modules import sparse as sp +from ..renderers import VoxelRenderer +from ..representations import Voxel +from ..representations.mesh import MeshWithPbrMaterial, TextureFilterMode, TextureWrapMode, AlphaMode, PbrMaterial, Texture + +from ..utils.data_utils import load_balanced_group_indices + + +def is_power_of_two(n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 + + +def nearest_power_of_two(n: int) -> int: + if n < 1: + raise ValueError("n must be >= 1") + if is_power_of_two(n): + return n + lower = 2 ** (n.bit_length() - 1) + upper = 2 ** n.bit_length() + if n - lower < upper - n: + return lower + else: + return upper + + +class SparseVoxelPbrVisMixin: + @torch.no_grad() + def visualize_sample(self, x: Union[sp.SparseTensor, dict]): + x = x if isinstance(x, sp.SparseTensor) else x['x'] + + renderer = VoxelRenderer() + renderer.rendering_options.resolution = 512 + renderer.rendering_options.ssaa = 4 + + # Build camera + yaws = [0, np.pi / 2, np.pi, 3 * np.pi / 2] + yaws_offset = np.random.uniform(-np.pi / 4, np.pi / 4) + yaws = [y + yaws_offset for y in yaws] + pitch = [np.random.uniform(-np.pi / 4, np.pi / 4) for _ in range(4)] + + exts = [] + ints = [] + for yaw, pitch in zip(yaws, pitch): + orig = torch.tensor([ + np.sin(yaw) * np.cos(pitch), + np.cos(yaw) * np.cos(pitch), + np.sin(pitch), + ]).float().cuda() * 2 + fov = torch.deg2rad(torch.tensor(30)).cuda() + extrinsics = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda()) + intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + exts.append(extrinsics) + ints.append(intrinsics) + + images = {k: [] for k in self.layout} + + # Build each representation + x = x.cuda() + for i in range(x.shape[0]): + rep = Voxel( + origin=[-0.5, -0.5, -0.5], + voxel_size=1/self.resolution, + coords=x[i].coords[:, 1:].contiguous(), + attrs=None, + layout={ + 'color': slice(0, 3), + } + ) + for k in self.layout: + image = torch.zeros(3, 1024, 1024).cuda() + tile = [2, 2] + for j, (ext, intr) in enumerate(zip(exts, ints)): + attr = x[i].feats[:, self.layout[k]].expand(-1, 3) + res = renderer.render(rep, ext, intr, colors_overwrite=attr) + image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['color'] + images[k].append(image) + + for k in self.layout: + images[k] = torch.stack(images[k]) + + return images + + +class SparseVoxelPbrDataset(SparseVoxelPbrVisMixin, StandardDatasetBase): + """ + Sparse Voxel PBR dataset. + + Args: + roots (str): path to the dataset + resolution (int): resolution of the voxel grid + min_aesthetic_score (float): minimum aesthetic score of the instances to be included in the dataset + """ + + def __init__( + self, + roots, + resolution: int = 1024, + max_active_voxels: int = 1000000, + max_num_faces: int = None, + min_aesthetic_score: float = 5.0, + attrs: list[str] = ['base_color', 'metallic', 'roughness', 'emissive', 'alpha'], + with_mesh: bool = True, + ): + self.resolution = resolution + self.min_aesthetic_score = min_aesthetic_score + self.max_active_voxels = max_active_voxels + self.max_num_faces = max_num_faces + self.with_mesh = with_mesh + self.value_range = (-1, 1) + self.channels = { + 'base_color': 3, + 'metallic': 1, + 'roughness': 1, + 'emissive': 3, + 'alpha': 1, + } + self.layout = {} + start = 0 + for attr in attrs: + self.layout[attr] = slice(start, start + self.channels[attr]) + start += self.channels[attr] + + super().__init__(roots) + + self.loads = [self.metadata.loc[sha256, f'num_pbr_voxels'] for _, sha256 in self.instances] + + def __str__(self): + lines = [ + super().__str__(), + f' - Resolution: {self.resolution}', + f' - Attributes: {list(self.layout.keys())}', + ] + return '\n'.join(lines) + + def filter_metadata(self, metadata): + stats = {} + metadata = metadata[metadata['pbr_voxelized'] == True] + stats['PBR Voxelized'] = len(metadata) + if self.min_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score] + stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata) + metadata = metadata[metadata['num_pbr_voxels'] <= self.max_active_voxels] + stats[f'Active voxels <= {self.max_active_voxels}'] = len(metadata) + if self.max_num_faces is not None: + metadata = metadata[metadata['num_faces'] <= self.max_num_faces] + stats[f'Faces <= {self.max_num_faces}'] = len(metadata) + return metadata, stats + + @staticmethod + def _texture_from_dump(pack) -> Texture: + png_bytes = pack['image'] + image = Image.open(io.BytesIO(png_bytes)) + if image.width != image.height or not is_power_of_two(image.width): + size = nearest_power_of_two(max(image.width, image.height)) + image = image.resize((size, size), Image.LANCZOS) + texture = torch.tensor(np.array(image) / 255.0, dtype=torch.float32).reshape(image.height, image.width, -1) + filter_mode = { + 'Linear': TextureFilterMode.LINEAR, + 'Closest': TextureFilterMode.CLOSEST, + 'Cubic': TextureFilterMode.LINEAR, + 'Smart': TextureFilterMode.LINEAR, + }[pack['interpolation']] + wrap_mode = { + 'REPEAT': TextureWrapMode.REPEAT, + 'EXTEND': TextureWrapMode.CLAMP_TO_EDGE, + 'CLIP': TextureWrapMode.CLAMP_TO_EDGE, + 'MIRROR': TextureWrapMode.MIRRORED_REPEAT, + }[pack['extension']] + return Texture(texture, filter_mode=filter_mode, wrap_mode=wrap_mode) + + def read_mesh_with_texture(self, root, instance): + with open(os.path.join(root, f'{instance}.pickle'), 'rb') as f: + dump = pickle.load(f) + + # Fix dump alpha map + for mat in dump['materials']: + if mat['alphaTexture'] is not None and mat['alphaMode'] == 'OPAQUE': + mat['alphaMode'] = 'BLEND' + + # process material + materials = [] + for mat in dump['materials']: + materials.append(PbrMaterial( + base_color_texture=self._texture_from_dump(mat['baseColorTexture']) if mat['baseColorTexture'] is not None else None, + base_color_factor=mat['baseColorFactor'], + metallic_texture=self._texture_from_dump(mat['metallicTexture']) if mat['metallicTexture'] is not None else None, + metallic_factor=mat['metallicFactor'], + roughness_texture=self._texture_from_dump(mat['roughnessTexture']) if mat['roughnessTexture'] is not None else None, + roughness_factor=mat['roughnessFactor'], + alpha_texture=self._texture_from_dump(mat['alphaTexture']) if mat['alphaTexture'] is not None else None, + alpha_factor=mat['alphaFactor'], + alpha_mode={ + 'OPAQUE': AlphaMode.OPAQUE, + 'MASK': AlphaMode.MASK, + 'BLEND': AlphaMode.BLEND, + }[mat['alphaMode']], + alpha_cutoff=mat['alphaCutoff'], + )) + materials.append(PbrMaterial( + base_color_factor=[0.8, 0.8, 0.8], + alpha_factor=1.0, + metallic_factor=0.0, + roughness_factor=0.5, + alpha_mode=AlphaMode.OPAQUE, + alpha_cutoff=0.5, + )) # append default material + + # process mesh + start = 0 + vertices = [] + faces = [] + material_ids = [] + uv_coords = [] + for obj in dump['objects']: + if obj['vertices'].size == 0 or obj['faces'].size == 0: + continue + vertices.append(obj['vertices']) + faces.append(obj['faces'] + start) + obj['mat_ids'][obj['mat_ids'] == -1] = len(materials) - 1 + material_ids.append(obj['mat_ids']) + uv_coords.append(obj['uvs'] if obj['uvs'] is not None else np.zeros((obj['faces'].shape[0], 3, 2), dtype=np.float32)) + start += len(obj['vertices']) + + vertices = torch.from_numpy(np.concatenate(vertices, axis=0)).float() + faces = torch.from_numpy(np.concatenate(faces, axis=0)).long() + material_ids = torch.from_numpy(np.concatenate(material_ids, axis=0)).long() + uv_coords = torch.from_numpy(np.concatenate(uv_coords, axis=0)).float() + + # Normalize vertices + vertices_min = vertices.min(dim=0)[0] + vertices_max = vertices.max(dim=0)[0] + center = (vertices_min + vertices_max) / 2 + scale = 0.99999 / (vertices_max - vertices_min).max() + vertices = (vertices - center) * scale + assert torch.all(vertices >= -0.5) and torch.all(vertices <= 0.5), 'vertices out of range' + + return {'mesh': [MeshWithPbrMaterial( + vertices=vertices, + faces=faces, + material_ids=material_ids, + uv_coords=uv_coords, + materials=materials, + )]} + + def read_pbr_voxel(self, root, instance): + coords, attr = o_voxel.io.read_vxz(os.path.join(root, f'{instance}.vxz'), num_threads=4) + feats = torch.concat([attr[k] for k in self.layout], dim=-1) / 255.0 * 2 - 1 + x = sp.SparseTensor( + feats.float(), + torch.cat([torch.zeros_like(coords[:, 0:1]), coords], dim=-1), + ) + return {'x': x} + + def get_instance(self, root, instance): + if self.with_mesh: + mesh = self.read_mesh_with_texture(root['pbr_dump'], instance) + pbr_voxel = self.read_pbr_voxel(root['pbr_voxel'], instance) + return {**mesh, **pbr_voxel} + else: + return self.read_pbr_voxel(root['pbr_voxel'], instance) + + @staticmethod + def collate_fn(batch, split_size=None): + if split_size is None: + group_idx = [list(range(len(batch)))] + else: + group_idx = load_balanced_group_indices([b['x'].feats.shape[0] for b in batch], split_size) + packs = [] + for group in group_idx: + sub_batch = [batch[i] for i in group] + pack = {} + + keys = [k for k in sub_batch[0].keys()] + for k in keys: + if isinstance(sub_batch[0][k], torch.Tensor): + pack[k] = torch.stack([b[k] for b in sub_batch]) + elif isinstance(sub_batch[0][k], sp.SparseTensor): + pack[k] = sp.sparse_cat([b[k] for b in sub_batch], dim=0) + elif isinstance(sub_batch[0][k], list): + pack[k] = sum([b[k] for b in sub_batch], []) + else: + pack[k] = [b[k] for b in sub_batch] + + packs.append(pack) + + if split_size is None: + return packs[0] + return packs diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..2e18a275830cd331664f5e21bfcd5306d70079a1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent.py @@ -0,0 +1,210 @@ +import json +import os +from typing import * +import numpy as np +import torch +import utils3d.torch +from .components import StandardDatasetBase, ImageConditionedMixin +from ..modules.sparse.basic import SparseTensor +from .. import models +from ..utils.render_utils import get_renderer +from ..utils.data_utils import load_balanced_group_indices + + +class SLatVisMixin: + def __init__( + self, + *args, + pretrained_slat_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/slat_dec_gs_swin8_B_64l8gs32_fp16', + slat_dec_path: Optional[str] = None, + slat_dec_ckpt: Optional[str] = None, + **kwargs + ): + super().__init__(*args, **kwargs) + self.slat_dec = None + self.pretrained_slat_dec = pretrained_slat_dec + self.slat_dec_path = slat_dec_path + self.slat_dec_ckpt = slat_dec_ckpt + + def _loading_slat_dec(self): + if self.slat_dec is not None: + return + if self.slat_dec_path is not None: + cfg = json.load(open(os.path.join(self.slat_dec_path, 'config.json'), 'r')) + decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args']) + ckpt_path = os.path.join(self.slat_dec_path, 'ckpts', f'decoder_{self.slat_dec_ckpt}.pt') + decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True)) + else: + decoder = models.from_pretrained(self.pretrained_slat_dec) + self.slat_dec = decoder.cuda().eval() + + def _delete_slat_dec(self): + del self.slat_dec + self.slat_dec = None + + @torch.no_grad() + def decode_latent(self, z, batch_size=4): + self._loading_slat_dec() + reps = [] + if self.normalization is not None: + z = z * self.std.to(z.device) + self.mean.to(z.device) + for i in range(0, z.shape[0], batch_size): + reps.append(self.slat_dec(z[i:i+batch_size])) + reps = sum(reps, []) + self._delete_slat_dec() + return reps + + @torch.no_grad() + def visualize_sample(self, x_0: Union[SparseTensor, dict]): + x_0 = x_0 if isinstance(x_0, SparseTensor) else x_0['x_0'] + reps = self.decode_latent(x_0.cuda()) + + # Build camera + yaws = [0, np.pi / 2, np.pi, 3 * np.pi / 2] + yaws_offset = np.random.uniform(-np.pi / 4, np.pi / 4) + yaws = [y + yaws_offset for y in yaws] + pitch = [np.random.uniform(-np.pi / 4, np.pi / 4) for _ in range(4)] + + exts = [] + ints = [] + for yaw, pitch in zip(yaws, pitch): + orig = torch.tensor([ + np.sin(yaw) * np.cos(pitch), + np.cos(yaw) * np.cos(pitch), + np.sin(pitch), + ]).float().cuda() * 2 + fov = torch.deg2rad(torch.tensor(40)).cuda() + extrinsics = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda()) + intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + exts.append(extrinsics) + ints.append(intrinsics) + + renderer = get_renderer(reps[0]) + images = [] + for representation in reps: + image = torch.zeros(3, 1024, 1024).cuda() + tile = [2, 2] + for j, (ext, intr) in enumerate(zip(exts, ints)): + res = renderer.render(representation, ext, intr) + image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['color'] + images.append(image) + images = torch.stack(images) + + return images + + +class SLat(SLatVisMixin, StandardDatasetBase): + """ + structured latent V2 dataset + + Args: + roots (str): path to the dataset + min_aesthetic_score (float): minimum aesthetic score + max_tokens (int): maximum number of tokens + latent_key (str): key of the latent to be used + normalization (dict): normalization stats + pretrained_slat_dec (str): name of the pretrained slat decoder + slat_dec_path (str): path to the slat decoder, if given, will override the pretrained_slat_dec + slat_dec_ckpt (str): name of the slat decoder checkpoint + """ + def __init__(self, + roots: str, + *, + min_aesthetic_score: float = 5.0, + max_tokens: int = 32768, + latent_key: str = 'shape_latent', + normalization: Optional[dict] = None, + pretrained_slat_dec: str = 'JeffreyXiang/TRELLIS-image-large/ckpts/slat_dec_gs_swin8_B_64l8gs32_fp16', + slat_dec_path: Optional[str] = None, + slat_dec_ckpt: Optional[str] = None, + ): + self.normalization = normalization + self.min_aesthetic_score = min_aesthetic_score + self.max_tokens = max_tokens + self.latent_key = latent_key + self.value_range = (0, 1) + + super().__init__( + roots, + pretrained_slat_dec=pretrained_slat_dec, + slat_dec_path=slat_dec_path, + slat_dec_ckpt=slat_dec_ckpt, + ) + + self.loads = [self.metadata.loc[sha256, f'{latent_key}_tokens'] for _, sha256 in self.instances] + + if self.normalization is not None: + self.mean = torch.tensor(self.normalization['mean']).reshape(1, -1) + self.std = torch.tensor(self.normalization['std']).reshape(1, -1) + + def filter_metadata(self, metadata): + stats = {} + metadata = metadata[metadata[f'{self.latent_key}_encoded'] == True] + stats['With latent'] = len(metadata) + metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score] + stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata) + metadata = metadata[metadata[f'{self.latent_key}_tokens'] <= self.max_tokens] + stats[f'Num tokens <= {self.max_tokens}'] = len(metadata) + return metadata, stats + + def get_instance(self, root, instance): + data = np.load(os.path.join(root[self.latent_key], f'{instance}.npz')) + coords = torch.tensor(data['coords']).int() + feats = torch.tensor(data['feats']).float() + if self.normalization is not None: + feats = (feats - self.mean) / self.std + return { + 'coords': coords, + 'feats': feats, + } + + @staticmethod + def collate_fn(batch, split_size=None): + if split_size is None: + group_idx = [list(range(len(batch)))] + else: + group_idx = load_balanced_group_indices([b['coords'].shape[0] for b in batch], split_size) + packs = [] + for group in group_idx: + sub_batch = [batch[i] for i in group] + pack = {} + coords = [] + feats = [] + layout = [] + start = 0 + for i, b in enumerate(sub_batch): + coords.append(torch.cat([torch.full((b['coords'].shape[0], 1), i, dtype=torch.int32), b['coords']], dim=-1)) + feats.append(b['feats']) + layout.append(slice(start, start + b['coords'].shape[0])) + start += b['coords'].shape[0] + coords = torch.cat(coords) + feats = torch.cat(feats) + pack['x_0'] = SparseTensor( + coords=coords, + feats=feats, + ) + pack['x_0']._shape = torch.Size([len(group), *sub_batch[0]['feats'].shape[1:]]) + pack['x_0'].register_spatial_cache('layout', layout) + + # collate other data + keys = [k for k in sub_batch[0].keys() if k not in ['coords', 'feats']] + for k in keys: + if isinstance(sub_batch[0][k], torch.Tensor): + pack[k] = torch.stack([b[k] for b in sub_batch]) + elif isinstance(sub_batch[0][k], list): + pack[k] = sum([b[k] for b in sub_batch], []) + else: + pack[k] = [b[k] for b in sub_batch] + + packs.append(pack) + + if split_size is None: + return packs[0] + return packs + + +class ImageConditionedSLat(ImageConditionedMixin, SLat): + """ + Image conditioned structured latent dataset + """ + pass diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent_shape.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..c58611957b1dcb16b0d9c368a2fa7e88ddb63be5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent_shape.py @@ -0,0 +1,96 @@ +import os +import json +from typing import * +import numpy as np +import torch +from .. import models +from .components import ImageConditionedMixin +from ..modules.sparse import SparseTensor +from .structured_latent import SLatVisMixin, SLat +from ..utils.render_utils import get_renderer, yaw_pitch_r_fov_to_extrinsics_intrinsics + + +class SLatShapeVisMixin(SLatVisMixin): + def _loading_slat_dec(self): + if self.slat_dec is not None: + return + if self.slat_dec_path is not None: + cfg = json.load(open(os.path.join(self.slat_dec_path, 'config.json'), 'r')) + decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args']) + ckpt_path = os.path.join(self.slat_dec_path, 'ckpts', f'decoder_{self.slat_dec_ckpt}.pt') + decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True)) + else: + decoder = models.from_pretrained(self.pretrained_slat_dec) + decoder.set_resolution(self.resolution) + self.slat_dec = decoder.cuda().eval() + + @torch.no_grad() + def visualize_sample(self, x_0: Union[SparseTensor, dict]): + x_0 = x_0 if isinstance(x_0, SparseTensor) else x_0['x_0'] + reps = self.decode_latent(x_0.cuda()) + + # build camera + yaw = [0, np.pi/2, np.pi, 3*np.pi/2] + yaw_offset = -16 / 180 * np.pi + yaw = [y + yaw_offset for y in yaw] + pitch = [20 / 180 * np.pi for _ in range(4)] + exts, ints = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, 2, 30) + + # render + renderer = get_renderer(reps[0]) + images = [] + for representation in reps: + image = torch.zeros(3, 1024, 1024).cuda() + tile = [2, 2] + for j, (ext, intr) in enumerate(zip(exts, ints)): + res = renderer.render(representation, ext, intr) + image[:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = res['normal'] + images.append(image) + images = torch.stack(images) + return images + + +class SLatShape(SLatShapeVisMixin, SLat): + """ + structured latent for shape generation + + Args: + roots (str): path to the dataset + resolution (int): resolution of the shape + min_aesthetic_score (float): minimum aesthetic score + max_tokens (int): maximum number of tokens + latent_key (str): key of the latent to be used + normalization (dict): normalization stats + pretrained_slat_dec (str): name of the pretrained slat decoder + slat_dec_path (str): path to the slat decoder, if given, will override the pretrained_slat_dec + slat_dec_ckpt (str): name of the slat decoder checkpoint + """ + def __init__(self, + roots: str, + *, + resolution: int, + min_aesthetic_score: float = 5.0, + max_tokens: int = 32768, + normalization: Optional[dict] = None, + pretrained_slat_dec: str = 'microsoft/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16', + slat_dec_path: Optional[str] = None, + slat_dec_ckpt: Optional[str] = None, + ): + super().__init__( + roots, + min_aesthetic_score=min_aesthetic_score, + max_tokens=max_tokens, + latent_key='shape_latent', + normalization=normalization, + pretrained_slat_dec=pretrained_slat_dec, + slat_dec_path=slat_dec_path, + slat_dec_ckpt=slat_dec_ckpt, + ) + self.resolution = resolution + + +class ImageConditionedSLatShape(ImageConditionedMixin, SLatShape): + """ + Image conditioned structured latent for shape generation + """ + pass diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent_svpbr.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent_svpbr.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a43a87b65deee7091c1506cc3a6c4e24a0a4f8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/datasets/structured_latent_svpbr.py @@ -0,0 +1,290 @@ +import os +os.environ['OPENCV_IO_ENABLE_OPENEXR'] = '1' +import json +from typing import * +import numpy as np +import torch +import cv2 +from .. import models +from .components import StandardDatasetBase, ImageConditionedMixin +from ..modules.sparse import SparseTensor, sparse_cat +from ..representations import MeshWithVoxel +from ..renderers import PbrMeshRenderer, EnvMap +from ..utils.data_utils import load_balanced_group_indices +from ..utils.render_utils import yaw_pitch_r_fov_to_extrinsics_intrinsics + + +class SLatPbrVisMixin: + def __init__( + self, + *args, + pretrained_pbr_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/tex_dec_next_dc_f16c32_fp16', + pbr_slat_dec_path: Optional[str] = None, + pbr_slat_dec_ckpt: Optional[str] = None, + pretrained_shape_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16', + shape_slat_dec_path: Optional[str] = None, + shape_slat_dec_ckpt: Optional[str] = None, + **kwargs + ): + super().__init__(*args, **kwargs) + self.pbr_slat_dec = None + self.pretrained_pbr_slat_dec = pretrained_pbr_slat_dec + self.pbr_slat_dec_path = pbr_slat_dec_path + self.pbr_slat_dec_ckpt = pbr_slat_dec_ckpt + self.shape_slat_dec = None + self.pretrained_shape_slat_dec = pretrained_shape_slat_dec + self.shape_slat_dec_path = shape_slat_dec_path + self.shape_slat_dec_ckpt = shape_slat_dec_ckpt + + def _loading_slat_dec(self): + if self.pbr_slat_dec is not None and self.shape_slat_dec is not None: + return + if self.pbr_slat_dec_path is not None: + cfg = json.load(open(os.path.join(self.pbr_slat_dec_path, 'config.json'), 'r')) + decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args']) + ckpt_path = os.path.join(self.pbr_slat_dec_path, 'ckpts', f'decoder_{self.pbr_slat_dec_ckpt}.pt') + decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True)) + else: + decoder = models.from_pretrained(self.pretrained_pbr_slat_dec) + self.pbr_slat_dec = decoder.cuda().eval() + + if self.shape_slat_dec_path is not None: + cfg = json.load(open(os.path.join(self.shape_slat_dec_path, 'config.json'), 'r')) + decoder = getattr(models, cfg['models']['decoder']['name'])(**cfg['models']['decoder']['args']) + ckpt_path = os.path.join(self.shape_slat_dec_path, 'ckpts', f'decoder_{self.shape_slat_dec_ckpt}.pt') + decoder.load_state_dict(torch.load(ckpt_path, map_location='cpu', weights_only=True)) + else: + decoder = models.from_pretrained(self.pretrained_shape_slat_dec) + decoder.set_resolution(self.resolution) + self.shape_slat_dec = decoder.cuda().eval() + + def _delete_slat_dec(self): + del self.pbr_slat_dec + self.pbr_slat_dec = None + del self.shape_slat_dec + self.shape_slat_dec = None + + @torch.no_grad() + def decode_latent(self, z, shape_z, batch_size=4): + self._loading_slat_dec() + reps = [] + if self.shape_slat_normalization is not None: + shape_z = shape_z * self.shape_slat_std.to(z.device) + self.shape_slat_mean.to(z.device) + if self.pbr_slat_normalization is not None: + z = z * self.pbr_slat_std.to(z.device) + self.pbr_slat_mean.to(z.device) + for i in range(0, z.shape[0], batch_size): + mesh, subs = self.shape_slat_dec(shape_z[i:i+batch_size], return_subs=True) + vox = self.pbr_slat_dec(z[i:i+batch_size], guide_subs=subs) * 0.5 + 0.5 + reps.extend([ + MeshWithVoxel( + m.vertices, m.faces, + origin = [-0.5, -0.5, -0.5], + voxel_size = 1 / self.resolution, + coords = v.coords[:, 1:], + attrs = v.feats, + voxel_shape = torch.Size([*v.shape, *v.spatial_shape]), + layout = self.layout, + ) + for m, v in zip(mesh, vox) + ]) + self._delete_slat_dec() + return reps + + @torch.no_grad() + def visualize_sample(self, sample: dict): + shape_z = sample['concat_cond'].cuda() + z = sample['x_0'].cuda() + reps = self.decode_latent(z, shape_z) + + # build camera + yaw = [0, np.pi/2, np.pi, 3*np.pi/2] + yaw_offset = -16 / 180 * np.pi + yaw = [y + yaw_offset for y in yaw] + pitch = [20 / 180 * np.pi for _ in range(4)] + exts, ints = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, 2, 30) + + # render + renderer = PbrMeshRenderer() + renderer.rendering_options.resolution = 512 + renderer.rendering_options.near = 1 + renderer.rendering_options.far = 100 + renderer.rendering_options.ssaa = 2 + renderer.rendering_options.peel_layers = 8 + envmap = EnvMap(torch.tensor( + cv2.cvtColor(cv2.imread('assets/hdri/forest.exr', cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB), + dtype=torch.float32, device='cuda' + )) + + images = {} + for representation in reps: + image = {} + tile = [2, 2] + for j, (ext, intr) in enumerate(zip(exts, ints)): + res = renderer.render(representation, ext, intr, envmap=envmap) + for k, v in res.items(): + if k not in images: + images[k] = [] + if k not in image: + image[k] = torch.zeros(3, 1024, 1024).cuda() + image[k][:, 512 * (j // tile[1]):512 * (j // tile[1] + 1), 512 * (j % tile[1]):512 * (j % tile[1] + 1)] = v + for k in images.keys(): + images[k].append(image[k]) + for k in images.keys(): + images[k] = torch.stack(images[k], dim=0) + return images + + +class SLatPbr(SLatPbrVisMixin, StandardDatasetBase): + """ + structured latent for sparse voxel pbr dataset + + Args: + roots (str): path to the dataset + latent_key (str): key of the latent to be used + min_aesthetic_score (float): minimum aesthetic score + normalization (dict): normalization stats + resolution (int): resolution of decoded sparse voxel + attrs (list): attributes to be decoded + pretained_slat_dec (str): name of the pretrained slat decoder + slat_dec_path (str): path to the slat decoder, if given, will override the pretrained_slat_dec + slat_dec_ckpt (str): name of the slat decoder checkpoint + """ + def __init__(self, + roots: str, + *, + resolution: int, + min_aesthetic_score: float = 5.0, + max_tokens: int = 32768, + full_pbr: bool = False, + pbr_slat_normalization: Optional[dict] = None, + shape_slat_normalization: Optional[dict] = None, + attrs: list[str] = ['base_color', 'metallic', 'roughness', 'emissive', 'alpha'], + pretrained_pbr_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/tex_dec_next_dc_f16c32_fp16', + pbr_slat_dec_path: Optional[str] = None, + pbr_slat_dec_ckpt: Optional[str] = None, + pretrained_shape_slat_dec: str = 'JeffreyXiang/TRELLIS.2-4B/ckpts/shape_dec_next_dc_f16c32_fp16', + shape_slat_dec_path: Optional[str] = None, + shape_slat_dec_ckpt: Optional[str] = None, + **kwargs + ): + self.resolution = resolution + self.pbr_slat_normalization = pbr_slat_normalization + self.shape_slat_normalization = shape_slat_normalization + self.min_aesthetic_score = min_aesthetic_score + self.max_tokens = max_tokens + self.full_pbr = full_pbr + self.value_range = (0, 1) + + super().__init__( + roots, + pretrained_pbr_slat_dec=pretrained_pbr_slat_dec, + pbr_slat_dec_path=pbr_slat_dec_path, + pbr_slat_dec_ckpt=pbr_slat_dec_ckpt, + pretrained_shape_slat_dec=pretrained_shape_slat_dec, + shape_slat_dec_path=shape_slat_dec_path, + shape_slat_dec_ckpt=shape_slat_dec_ckpt, + **kwargs + ) + + self.loads = [self.metadata.loc[sha256, 'pbr_latent_tokens'] for _, sha256 in self.instances] + + if self.pbr_slat_normalization is not None: + self.pbr_slat_mean = torch.tensor(self.pbr_slat_normalization['mean']).reshape(1, -1) + self.pbr_slat_std = torch.tensor(self.pbr_slat_normalization['std']).reshape(1, -1) + + if self.shape_slat_normalization is not None: + self.shape_slat_mean = torch.tensor(self.shape_slat_normalization['mean']).reshape(1, -1) + self.shape_slat_std = torch.tensor(self.shape_slat_normalization['std']).reshape(1, -1) + + self.attrs = attrs + self.channels = { + 'base_color': 3, + 'metallic': 1, + 'roughness': 1, + 'emissive': 3, + 'alpha': 1, + } + self.layout = {} + start = 0 + for attr in attrs: + self.layout[attr] = slice(start, start + self.channels[attr]) + start += self.channels[attr] + + def filter_metadata(self, metadata): + stats = {} + metadata = metadata[metadata['pbr_latent_encoded'] == True] + stats['With PBR latent'] = len(metadata) + metadata = metadata[metadata['shape_latent_encoded'] == True] + stats['With shape latent'] = len(metadata) + metadata = metadata[metadata['aesthetic_score'] >= self.min_aesthetic_score] + stats[f'Aesthetic score >= {self.min_aesthetic_score}'] = len(metadata) + metadata = metadata[metadata['pbr_latent_tokens'] <= self.max_tokens] + stats[f'Num tokens <= {self.max_tokens}'] = len(metadata) + if self.full_pbr: + metadata = metadata[metadata['num_basecolor_tex'] > 0] + metadata = metadata[metadata['num_metallic_tex'] > 0] + metadata = metadata[metadata['num_roughness_tex'] > 0] + stats['Full PBR'] = len(metadata) + return metadata, stats + + def get_instance(self, root, instance): + # PBR latent + data = np.load(os.path.join(root['pbr_latent'], f'{instance}.npz')) + coords = torch.tensor(data['coords']).int() + coords = torch.cat([torch.zeros_like(coords)[:, :1], coords], dim=1) + feats = torch.tensor(data['feats']).float() + if self.pbr_slat_normalization is not None: + feats = (feats - self.pbr_slat_mean) / self.pbr_slat_std + pbr_z = SparseTensor(feats, coords) + + # Shape latent + data = np.load(os.path.join(root['shape_latent'], f'{instance}.npz')) + coords = torch.tensor(data['coords']).int() + coords = torch.cat([torch.zeros_like(coords)[:, :1], coords], dim=1) + feats = torch.tensor(data['feats']).float() + if self.shape_slat_normalization is not None: + feats = (feats - self.shape_slat_mean) / self.shape_slat_std + shape_z = SparseTensor(feats, coords) + + assert torch.equal(shape_z.coords, pbr_z.coords), \ + f"Shape latent and PBR latent have different coordinates: {shape_z.coords.shape} vs {pbr_z.coords.shape}" + + return { + 'x_0': pbr_z, + 'concat_cond': shape_z, + } + + @staticmethod + def collate_fn(batch, split_size=None): + if split_size is None: + group_idx = [list(range(len(batch)))] + else: + group_idx = load_balanced_group_indices([b['x_0'].feats.shape[0] for b in batch], split_size) + packs = [] + for group in group_idx: + sub_batch = [batch[i] for i in group] + pack = {} + + keys = [k for k in sub_batch[0].keys()] + for k in keys: + if isinstance(sub_batch[0][k], torch.Tensor): + pack[k] = torch.stack([b[k] for b in sub_batch]) + elif isinstance(sub_batch[0][k], SparseTensor): + pack[k] = sparse_cat([b[k] for b in sub_batch], dim=0) + elif isinstance(sub_batch[0][k], list): + pack[k] = sum([b[k] for b in sub_batch], []) + else: + pack[k] = [b[k] for b in sub_batch] + + packs.append(pack) + + if split_size is None: + return packs[0] + return packs + + +class ImageConditionedSLatPbr(ImageConditionedMixin, SLatPbr): + """ + Image conditioned structured latent dataset + """ + pass diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4fed035ed7c1f6352d93e9787f1aaed072876d5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/__init__.py @@ -0,0 +1,78 @@ +import importlib + +__attributes = { + # Sparse Structure + 'SparseStructureEncoder': 'sparse_structure_vae', + 'SparseStructureDecoder': 'sparse_structure_vae', + 'SparseStructureFlowModel': 'sparse_structure_flow', + + # SLat Generation + 'SLatFlowModel': 'structured_latent_flow', + 'ElasticSLatFlowModel': 'structured_latent_flow', + + # SC-VAEs + 'SparseUnetVaeEncoder': 'sc_vaes.sparse_unet_vae', + 'SparseUnetVaeDecoder': 'sc_vaes.sparse_unet_vae', + 'FlexiDualGridVaeEncoder': 'sc_vaes.fdg_vae', + 'FlexiDualGridVaeDecoder': 'sc_vaes.fdg_vae' +} + +__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), strict=False) + + return model + + +# For Pylance +if __name__ == '__main__': + from .sparse_structure_vae import SparseStructureEncoder, SparseStructureDecoder + from .sparse_structure_flow import SparseStructureFlowModel + from .structured_latent_flow import SLatFlowModel, ElasticSLatFlowModel + + from .sc_vaes.sparse_unet_vae import SparseUnetVaeEncoder, SparseUnetVaeDecoder + from .sc_vaes.fdg_vae import FlexiDualGridVaeEncoder, FlexiDualGridVaeDecoder diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sc_vaes/fdg_vae.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sc_vaes/fdg_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..0209e690ea6f4096dd42a4d137dbc0bee1f51367 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sc_vaes/fdg_vae.py @@ -0,0 +1,110 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from ...modules import sparse as sp +from .sparse_unet_vae import ( + SparseResBlock3d, + SparseConvNeXtBlock3d, + + SparseResBlockDownsample3d, + SparseResBlockUpsample3d, + SparseResBlockS2C3d, + SparseResBlockC2S3d, +) +from .sparse_unet_vae import ( + SparseUnetVaeEncoder, + SparseUnetVaeDecoder, +) +from ...representations import Mesh +from o_voxel.convert import flexible_dual_grid_to_mesh + + +class FlexiDualGridVaeEncoder(SparseUnetVaeEncoder): + def __init__( + self, + model_channels: List[int], + latent_channels: int, + num_blocks: List[int], + block_type: List[str], + down_block_type: List[str], + block_args: List[Dict[str, Any]], + use_fp16: bool = False, + ): + super().__init__( + 6, + model_channels, + latent_channels, + num_blocks, + block_type, + down_block_type, + block_args, + use_fp16, + ) + + def forward(self, vertices: sp.SparseTensor, intersected: sp.SparseTensor, sample_posterior=False, return_raw=False): + x = vertices.replace(torch.cat([ + vertices.feats - 0.5, + intersected.feats.float() - 0.5, + ], dim=1)) + return super().forward(x, sample_posterior, return_raw) + + +class FlexiDualGridVaeDecoder(SparseUnetVaeDecoder): + def __init__( + self, + resolution: int, + model_channels: List[int], + latent_channels: int, + num_blocks: List[int], + block_type: List[str], + up_block_type: List[str], + block_args: List[Dict[str, Any]], + voxel_margin: float = 0.5, + use_fp16: bool = False, + ): + self.resolution = resolution + self.voxel_margin = voxel_margin + + super().__init__( + 7, + model_channels, + latent_channels, + num_blocks, + block_type, + up_block_type, + block_args, + use_fp16, + ) + + def set_resolution(self, resolution: int) -> None: + self.resolution = resolution + + def forward(self, x: sp.SparseTensor, gt_intersected: sp.SparseTensor = None, **kwargs): + decoded = super().forward(x, **kwargs) + if self.training: + h, subs_gt, subs = decoded + vertices = h.replace((1 + 2 * self.voxel_margin) * F.sigmoid(h.feats[..., 0:3]) - self.voxel_margin) + intersected_logits = h.replace(h.feats[..., 3:6]) + quad_lerp = h.replace(F.softplus(h.feats[..., 6:7])) + mesh = [Mesh(*flexible_dual_grid_to_mesh( + v.coords[:, 1:], v.feats, i.feats, q.feats, + aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + grid_size=self.resolution, + train=True + )) for v, i, q in zip(vertices, gt_intersected, quad_lerp)] + return mesh, vertices, intersected_logits, subs_gt, subs + else: + out_list = list(decoded) if isinstance(decoded, tuple) else [decoded] + h = out_list[0] + vertices = h.replace((1 + 2 * self.voxel_margin) * F.sigmoid(h.feats[..., 0:3]) - self.voxel_margin) + intersected = h.replace(h.feats[..., 3:6] > 0) + quad_lerp = h.replace(F.softplus(h.feats[..., 6:7])) + mesh = [Mesh(*flexible_dual_grid_to_mesh( + v.coords[:, 1:], v.feats, i.feats, q.feats, + aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + grid_size=self.resolution, + train=False + )) for v, i, q in zip(vertices, intersected, quad_lerp)] + out_list[0] = mesh + return out_list[0] if len(out_list) == 1 else tuple(out_list) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sc_vaes/sparse_unet_vae.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sc_vaes/sparse_unet_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..b9902a155a8a85c5c616a4503be92f43f6fdde27 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sc_vaes/sparse_unet_vae.py @@ -0,0 +1,522 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint +from ...modules.utils import convert_module_to_f16, convert_module_to_f32, zero_module +from ...modules import sparse as sp +from ...modules.norm import LayerNorm32 + + +class SparseResBlock3d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + downsample: bool = False, + upsample: bool = False, + resample_mode: Literal['nearest', 'spatial2channel'] = 'nearest', + use_checkpoint: bool = False, + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.downsample = downsample + self.upsample = upsample + self.resample_mode = resample_mode + self.use_checkpoint = use_checkpoint + + 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) + if resample_mode == 'nearest': + self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3) + elif resample_mode =='spatial2channel' and not self.downsample: + self.conv1 = sp.SparseConv3d(channels, self.out_channels * 8, 3) + elif resample_mode =='spatial2channel' and self.downsample: + self.conv1 = sp.SparseConv3d(channels, self.out_channels // 8, 3) + self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3)) + if resample_mode == 'nearest': + self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity() + elif resample_mode =='spatial2channel' and self.downsample: + self.skip_connection = lambda x: x.replace(x.feats.reshape(x.feats.shape[0], out_channels, channels * 8 // out_channels).mean(dim=-1)) + elif resample_mode =='spatial2channel' and not self.downsample: + self.skip_connection = lambda x: x.replace(x.feats.repeat_interleave(out_channels // (channels // 8), dim=1)) + self.updown = None + if self.downsample: + if resample_mode == 'nearest': + self.updown = sp.SparseDownsample(2) + elif resample_mode =='spatial2channel': + self.updown = sp.SparseSpatial2Channel(2) + elif self.upsample: + self.to_subdiv = sp.SparseLinear(channels, 8) + if resample_mode == 'nearest': + self.updown = sp.SparseUpsample(2) + elif resample_mode =='spatial2channel': + self.updown = sp.SparseChannel2Spatial(2) + + def _updown(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor: + if self.downsample: + x = self.updown(x) + elif self.upsample: + x = self.updown(x, subdiv.replace(subdiv.feats > 0)) + return x + + def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + subdiv = None + if self.upsample: + subdiv = self.to_subdiv(x) + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + if self.resample_mode == 'spatial2channel': + h = self.conv1(h) + h = self._updown(h, subdiv) + x = self._updown(x, subdiv) + if self.resample_mode == 'nearest': + h = self.conv1(h) + h = h.replace(self.norm2(h.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + if self.upsample: + return h, subdiv + return h + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseResBlockDownsample3d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + use_checkpoint: bool = False, + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_checkpoint = use_checkpoint + + 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.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity() + self.updown = sp.SparseDownsample(2) + + def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + h = self.updown(h) + x = self.updown(x) + h = self.conv1(h) + h = h.replace(self.norm2(h.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + return h + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseResBlockUpsample3d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + use_checkpoint: bool = False, + pred_subdiv: bool = True, + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_checkpoint = use_checkpoint + self.pred_subdiv = pred_subdiv + + 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.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity() + if self.pred_subdiv: + self.to_subdiv = sp.SparseLinear(channels, 8) + self.updown = sp.SparseUpsample(2) + + def _forward(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor: + if self.pred_subdiv: + subdiv = self.to_subdiv(x) + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + subdiv_binarized = subdiv.replace(subdiv.feats > 0) if subdiv is not None else None + h = self.updown(h, subdiv_binarized) + x = self.updown(x, subdiv_binarized) + h = self.conv1(h) + h = h.replace(self.norm2(h.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + if self.pred_subdiv: + return h, subdiv + else: + return h + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseResBlockS2C3d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + use_checkpoint: bool = False, + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_checkpoint = use_checkpoint + + 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 // 8, 3) + self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3)) + self.skip_connection = lambda x: x.replace(x.feats.reshape(x.feats.shape[0], out_channels, channels * 8 // out_channels).mean(dim=-1)) + self.updown = sp.SparseSpatial2Channel(2) + + def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv1(h) + h = self.updown(h) + x = self.updown(x) + h = h.replace(self.norm2(h.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + return h + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseResBlockC2S3d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + use_checkpoint: bool = False, + pred_subdiv: bool = True, + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_checkpoint = use_checkpoint + self.pred_subdiv = pred_subdiv + + 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 * 8, 3) + self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3)) + self.skip_connection = lambda x: x.replace(x.feats.repeat_interleave(out_channels // (channels // 8), dim=1)) + if pred_subdiv: + self.to_subdiv = sp.SparseLinear(channels, 8) + self.updown = sp.SparseChannel2Spatial(2) + + def _forward(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor: + if self.pred_subdiv: + subdiv = self.to_subdiv(x) + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv1(h) + subdiv_binarized = subdiv.replace(subdiv.feats > 0) if subdiv is not None else None + h = self.updown(h, subdiv_binarized) + x = self.updown(x, subdiv_binarized) + h = h.replace(self.norm2(h.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + if self.pred_subdiv: + return h, subdiv + else: + return h + + def forward(self, x: sp.SparseTensor, subdiv: sp.SparseTensor = None) -> sp.SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, subdiv, use_reentrant=False) + else: + return self._forward(x, subdiv) + + +class SparseConvNeXtBlock3d(nn.Module): + def __init__( + self, + channels: int, + mlp_ratio: float = 4.0, + use_checkpoint: bool = False, + ): + super().__init__() + self.channels = channels + self.use_checkpoint = use_checkpoint + + self.norm = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.conv = sp.SparseConv3d(channels, channels, 3) + self.mlp = nn.Sequential( + nn.Linear(channels, int(channels * mlp_ratio)), + nn.SiLU(), + zero_module(nn.Linear(int(channels * mlp_ratio), channels)), + ) + + def _forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + h = self.conv(x) + h = h.replace(self.norm(h.feats)) + h = h.replace(self.mlp(h.feats)) + return h + x + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseUnetVaeEncoder(nn.Module): + """ + Sparse Swin Transformer Unet VAE model. + """ + def __init__( + self, + in_channels: int, + model_channels: List[int], + latent_channels: int, + num_blocks: List[int], + block_type: List[str], + down_block_type: List[str], + block_args: List[Dict[str, Any]], + use_fp16: bool = False, + ): + super().__init__() + self.in_channels = in_channels + self.model_channels = model_channels + self.num_blocks = num_blocks + self.dtype = torch.float16 if use_fp16 else torch.float32 + self.dtype = torch.float16 if use_fp16 else torch.float32 + + self.input_layer = sp.SparseLinear(in_channels, model_channels[0]) + self.to_latent = sp.SparseLinear(model_channels[-1], 2 * latent_channels) + + self.blocks = nn.ModuleList([]) + for i in range(len(num_blocks)): + self.blocks.append(nn.ModuleList([])) + for j in range(num_blocks[i]): + self.blocks[-1].append( + globals()[block_type[i]]( + model_channels[i], + **block_args[i], + ) + ) + if i < len(num_blocks) - 1: + self.blocks[-1].append( + globals()[down_block_type[i]]( + model_channels[i], + model_channels[i+1], + **block_args[i], + ) + ) + + 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) + + def forward(self, x: sp.SparseTensor, sample_posterior=False, return_raw=False): + h = self.input_layer(x) + h = h.type(self.dtype) + for i, res in enumerate(self.blocks): + for j, block in enumerate(res): + h = block(h) + h = h.type(x.dtype) + h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) + h = self.to_latent(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 SparseUnetVaeDecoder(nn.Module): + """ + Sparse Swin Transformer Unet VAE model. + """ + def __init__( + self, + out_channels: int, + model_channels: List[int], + latent_channels: int, + num_blocks: List[int], + block_type: List[str], + up_block_type: List[str], + block_args: List[Dict[str, Any]], + use_fp16: bool = False, + pred_subdiv: bool = True, + ): + super().__init__() + self.out_channels = out_channels + self.model_channels = model_channels + self.num_blocks = num_blocks + self.use_fp16 = use_fp16 + self.pred_subdiv = pred_subdiv + self.dtype = torch.float16 if use_fp16 else torch.float32 + self.low_vram = False + + self.output_layer = sp.SparseLinear(model_channels[-1], out_channels) + self.from_latent = sp.SparseLinear(latent_channels, model_channels[0]) + + self.blocks = nn.ModuleList([]) + for i in range(len(num_blocks)): + self.blocks.append(nn.ModuleList([])) + for j in range(num_blocks[i]): + self.blocks[-1].append( + globals()[block_type[i]]( + model_channels[i], + **block_args[i], + ) + ) + if i < len(num_blocks) - 1: + self.blocks[-1].append( + globals()[up_block_type[i]]( + model_channels[i], + model_channels[i+1], + pred_subdiv=pred_subdiv, + **block_args[i], + ) + ) + + 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) + + def forward(self, x: sp.SparseTensor, guide_subs: Optional[List[sp.SparseTensor]] = None, return_subs: bool = False) -> sp.SparseTensor: + assert guide_subs is None or self.pred_subdiv == False, "Only decoders with pred_subdiv=False can be used with guide_subs" + assert return_subs == False or self.pred_subdiv == True, "Only decoders with pred_subdiv=True can be used with return_subs" + + h = self.from_latent(x) + h = h.type(self.dtype) + subs_gt = [] + subs = [] + for i, res in enumerate(self.blocks): + for j, block in enumerate(res): + if i < len(self.blocks) - 1 and j == len(res) - 1: + if self.pred_subdiv: + if self.training: + subs_gt.append(h.get_spatial_cache('subdivision')) + h, sub = block(h) + subs.append(sub) + else: + h = block(h, subdiv=guide_subs[i] if guide_subs is not None else None) + else: + h = block(h) + h = h.type(x.dtype) + h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) + h = self.output_layer(h) + if self.training and self.pred_subdiv: + return h, subs_gt, subs + else: + if return_subs: + return h, subs + else: + return h + + def upsample(self, x: sp.SparseTensor, upsample_times: int) -> torch.Tensor: + assert self.pred_subdiv == True, "Only decoders with pred_subdiv=True can be used with upsampling" + + h = self.from_latent(x) + h = h.type(self.dtype) + for i, res in enumerate(self.blocks): + if i == upsample_times: + return h.coords + for j, block in enumerate(res): + if i < len(self.blocks) - 1 and j == len(res) - 1: + h, sub = block(h) + else: + h = block(h) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_elastic_mixin.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_elastic_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..66d204c89bedabc2afd1795cdfc6f5d58a6b1ac0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_elastic_mixin.py @@ -0,0 +1,24 @@ +from contextlib import contextmanager +from typing import * +import math +from ..modules import sparse as sp +from ..utils.elastic_utils import ElasticModuleMixin + + +class SparseTransformerElasticMixin(ElasticModuleMixin): + def _get_input_size(self, x: sp.SparseTensor, *args, **kwargs): + return x.feats.shape[0] + + @contextmanager + def with_mem_ratio(self, mem_ratio=1.0): + if mem_ratio == 1.0: + yield 1.0 + return + num_blocks = len(self.blocks) + num_checkpoint_blocks = min(math.ceil((1 - mem_ratio) * num_blocks) + 1, num_blocks) + exact_mem_ratio = 1 - (num_checkpoint_blocks - 1) / num_blocks + for i in range(num_blocks): + self.blocks[i].use_checkpoint = i < num_checkpoint_blocks + yield exact_mem_ratio + for i in range(num_blocks): + self.blocks[i].use_checkpoint = False diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_structure_flow.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_structure_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..6c976656e389ef31664d1c2327cf159ee6501633 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_structure_flow.py @@ -0,0 +1,247 @@ +from typing import * +from functools import partial +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from ..modules.utils import convert_module_to, manual_cast, str_to_dtype +from ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlock +from ..modules.attention import RotaryPositionEmbedder + + +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, + pe_mode: Literal["ape", "rope"] = "ape", + rope_freq: Tuple[float, float] = (1.0, 10000.0), + dtype: str = 'float32', + use_checkpoint: bool = False, + share_mod: bool = False, + initialization: str = 'vanilla', + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + **kwargs + ): + 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.pe_mode = pe_mode + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.initialization = initialization + self.qk_rms_norm = qk_rms_norm + self.qk_rms_norm_cross = qk_rms_norm_cross + self.dtype = str_to_dtype(dtype) + + 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] * 3], indexing='ij') + coords = torch.stack(coords, dim=-1).reshape(-1, 3) + pos_emb = pos_embedder(coords) + self.register_buffer("pos_emb", pos_emb) + elif pe_mode == "rope": + pos_embedder = RotaryPositionEmbedder(self.model_channels // self.num_heads, 3) + coords = torch.meshgrid(*[torch.arange(res, device=self.device) for res in [resolution] * 3], indexing='ij') + coords = torch.stack(coords, dim=-1).reshape(-1, 3) + rope_phases = pos_embedder(coords) + self.register_buffer("rope_phases", rope_phases) + + if pe_mode != "rope": + self.rope_phases = None + + self.input_layer = nn.Linear(in_channels, 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"), + rope_freq=rope_freq, + 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) + + self.initialize_weights() + self.convert_to(self.dtype) + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to(self, dtype: torch.dtype) -> None: + """ + Convert the torso of the model to the specified dtype. + """ + self.dtype = dtype + self.blocks.apply(partial(convert_module_to, dtype=dtype)) + + def initialize_weights(self) -> None: + if self.initialization == 'vanilla': + # 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) + + elif self.initialization == 'scaled': + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.normal_(module.weight, std=np.sqrt(2.0 / (5.0 * self.model_channels))) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + # Scaled init for to_out and ffn2 + def _scaled_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.normal_(module.weight, std=1.0 / np.sqrt(5 * self.num_blocks * self.model_channels)) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + for block in self.blocks: + block.self_attn.to_out.apply(_scaled_init) + block.cross_attn.to_out.apply(_scaled_init) + block.mlp.mlp[2].apply(_scaled_init) + + # Initialize input layer to make the initial representation have variance 1 + nn.init.normal_(self.input_layer.weight, std=1.0 / np.sqrt(self.in_channels)) + nn.init.zeros_(self.input_layer.bias) + + # 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 = x.view(*x.shape[:2], -1).permute(0, 2, 1).contiguous() + + h = self.input_layer(h) + if self.pe_mode == "ape": + 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 = manual_cast(t_emb, self.dtype) + h = manual_cast(h, self.dtype) + cond = manual_cast(cond, self.dtype) + for block in self.blocks: + h = block(h, t_emb, cond, self.rope_phases) + h = manual_cast(h, 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] * 3).contiguous() + + return h diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_structure_vae.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_structure_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..c3e09136cf294c4c1b47b0f09fa6ee57bad2166d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/sparse_structure_vae.py @@ -0,0 +1,306 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..modules.norm import GroupNorm32, ChannelLayerNorm32 +from ..modules.spatial import pixel_shuffle_3d +from ..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 h diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/structured_latent_flow.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/structured_latent_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..9378ff777033ae064d4f1fa5265de41c09c560d5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/models/structured_latent_flow.py @@ -0,0 +1,207 @@ +from typing import * +from functools import partial +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from ..modules.utils import convert_module_to, manual_cast, str_to_dtype +from ..modules.transformer import AbsolutePositionEmbedder +from ..modules import sparse as sp +from ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlock +from .sparse_structure_flow import TimestepEmbedder +from .sparse_elastic_mixin import SparseTransformerElasticMixin + + +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, + pe_mode: Literal["ape", "rope"] = "ape", + rope_freq: Tuple[float, float] = (1.0, 10000.0), + dtype: str = 'float32', + use_checkpoint: bool = False, + share_mod: bool = False, + initialization: str = 'vanilla', + 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.pe_mode = pe_mode + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.initialization = initialization + self.qk_rms_norm = qk_rms_norm + self.qk_rms_norm_cross = qk_rms_norm_cross + self.dtype = str_to_dtype(dtype) + + 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, model_channels) + + 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"), + rope_freq=rope_freq, + 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_layer = sp.SparseLinear(model_channels, out_channels) + + self.initialize_weights() + self.convert_to(self.dtype) + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to(self, dtype: torch.dtype) -> None: + """ + Convert the torso of the model to the specified dtype. + """ + self.dtype = dtype + self.blocks.apply(partial(convert_module_to, dtype=dtype)) + + def initialize_weights(self) -> None: + if self.initialization == 'vanilla': + # 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) + + elif self.initialization == 'scaled': + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.normal_(module.weight, std=np.sqrt(2.0 / (5.0 * self.model_channels))) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + # Scaled init for to_out and ffn2 + def _scaled_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.normal_(module.weight, std=1.0 / np.sqrt(5 * self.num_blocks * self.model_channels)) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + for block in self.blocks: + block.self_attn.to_out.apply(_scaled_init) + block.cross_attn.to_out.apply(_scaled_init) + block.mlp.mlp[2].apply(_scaled_init) + + # Initialize input layer to make the initial representation have variance 1 + nn.init.normal_(self.input_layer.weight, std=1.0 / np.sqrt(self.in_channels)) + nn.init.zeros_(self.input_layer.bias) + + # 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: Union[torch.Tensor, List[torch.Tensor]], + concat_cond: Optional[sp.SparseTensor] = None, + **kwargs + ) -> sp.SparseTensor: + if concat_cond is not None: + x = sp.sparse_cat([x, concat_cond], dim=-1) + if isinstance(cond, list): + cond = sp.VarLenTensor.from_tensor_list(cond) + + h = self.input_layer(x) + h = manual_cast(h, self.dtype) + t_emb = self.t_embedder(t) + if self.share_mod: + t_emb = self.adaLN_modulation(t_emb) + t_emb = manual_cast(t_emb, self.dtype) + cond = manual_cast(cond, self.dtype) + + if self.pe_mode == "ape": + pe = self.pos_embedder(h.coords[:, 1:]) + h = h + manual_cast(pe, self.dtype) + for block in self.blocks: + h = block(h, t_emb, cond) + + h = manual_cast(h, x.dtype) + h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) + h = self.out_layer(h) + return h + + +class ElasticSLatFlowModel(SparseTransformerElasticMixin, SLatFlowModel): + """ + SLat Flow Model with elastic memory management. + Used for training with low VRAM. + """ + pass diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e90e901f9b942e18aaa5022b3ea167784e52d42a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/__init__.py @@ -0,0 +1,3 @@ +from .full_attn import * +from .modules import * +from .rope import * diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/config.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d5180cfc92d0121aa9edd8b7f07f72c4f7ad9f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/config.py @@ -0,0 +1,32 @@ +from typing import * + +BACKEND = 'flash_attn' +DEBUG = False + +def __from_env(): + import os + + global BACKEND + global DEBUG + + env_attn_backend = os.environ.get('ATTN_BACKEND') + env_attn_debug = os.environ.get('ATTN_DEBUG') + + if env_attn_backend is not None and env_attn_backend in ['xformers', 'flash_attn', 'flash_attn_3', 'sdpa', 'naive']: + BACKEND = env_attn_backend + if env_attn_debug is not None: + DEBUG = env_attn_debug == '1' + + print(f"[ATTENTION] Using backend: {BACKEND}") + + +__from_env() + + +def set_backend(backend: Literal['xformers', 'flash_attn']): + global BACKEND + BACKEND = backend + +def set_debug(debug: bool): + global DEBUG + DEBUG = debug diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/full_attn.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/full_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f9b2af8dfb90f43298042f607c16258516df4c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/full_attn.py @@ -0,0 +1,145 @@ +from typing import * +import torch +import math +from . import config + + +__all__ = [ + 'scaled_dot_product_attention', +] + + +def _naive_sdpa(q, k, v): + """ + Naive implementation of scaled dot product attention. + """ + q = q.permute(0, 2, 1, 3) # [N, H, L, C] + k = k.permute(0, 2, 1, 3) # [N, H, L, C] + v = v.permute(0, 2, 1, 3) # [N, H, L, C] + scale_factor = 1 / math.sqrt(q.size(-1)) + attn_weight = q @ k.transpose(-2, -1) * scale_factor + attn_weight = torch.softmax(attn_weight, dim=-1) + out = attn_weight @ v + out = out.permute(0, 2, 1, 3) # [N, L, H, C] + return out + + +@overload +def scaled_dot_product_attention(qkv: torch.Tensor) -> torch.Tensor: + """ + Apply scaled dot product attention. + + Args: + qkv (torch.Tensor): A [N, L, 3, H, C] tensor containing Qs, Ks, and Vs. + """ + ... + +@overload +def scaled_dot_product_attention(q: torch.Tensor, kv: torch.Tensor) -> torch.Tensor: + """ + Apply scaled dot product attention. + + Args: + q (torch.Tensor): A [N, L, H, C] tensor containing Qs. + kv (torch.Tensor): A [N, L, 2, H, C] tensor containing Ks and Vs. + """ + ... + +@overload +def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: + """ + Apply scaled dot product attention. + + Args: + q (torch.Tensor): A [N, L, H, Ci] tensor containing Qs. + k (torch.Tensor): A [N, L, H, Ci] tensor containing Ks. + v (torch.Tensor): A [N, L, H, Co] tensor containing Vs. + + Note: + k and v are assumed to have the same coordinate map. + """ + ... + +def scaled_dot_product_attention(*args, **kwargs): + arg_names_dict = { + 1: ['qkv'], + 2: ['q', 'kv'], + 3: ['q', 'k', 'v'] + } + num_all_args = len(args) + len(kwargs) + assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3" + for key in arg_names_dict[num_all_args][len(args):]: + assert key in kwargs, f"Missing argument {key}" + + if num_all_args == 1: + qkv = args[0] if len(args) > 0 else kwargs['qkv'] + assert len(qkv.shape) == 5 and qkv.shape[2] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, L, 3, H, C]" + device = qkv.device + + elif num_all_args == 2: + q = args[0] if len(args) > 0 else kwargs['q'] + kv = args[1] if len(args) > 1 else kwargs['kv'] + assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}" + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]" + assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]" + device = q.device + + elif num_all_args == 3: + q = args[0] if len(args) > 0 else kwargs['q'] + k = args[1] if len(args) > 1 else kwargs['k'] + v = args[2] if len(args) > 2 else kwargs['v'] + 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]}" + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]" + assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]" + assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]" + device = q.device + + if config.BACKEND == 'xformers': + if 'xops' not in globals(): + import xformers.ops as xops + if num_all_args == 1: + q, k, v = qkv.unbind(dim=2) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + out = xops.memory_efficient_attention(q, k, v) + elif config.BACKEND == 'flash_attn': + if 'flash_attn' not in globals(): + import flash_attn + if num_all_args == 1: + out = flash_attn.flash_attn_qkvpacked_func(qkv) + elif num_all_args == 2: + out = flash_attn.flash_attn_kvpacked_func(q, kv) + elif num_all_args == 3: + out = flash_attn.flash_attn_func(q, k, v) + elif config.BACKEND == 'flash_attn_3': + if 'flash_attn_3' not in globals(): + import flash_attn_interface as flash_attn_3 + if num_all_args == 1: + out = flash_attn_3.flash_attn_qkvpacked_func(qkv) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + out = flash_attn_3.flash_attn_func(q, k, v) + elif num_all_args == 3: + out = flash_attn_3.flash_attn_func(q, k, v) + elif config.BACKEND == 'sdpa': + if 'sdpa' not in globals(): + from torch.nn.functional import scaled_dot_product_attention as sdpa + if num_all_args == 1: + q, k, v = qkv.unbind(dim=2) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + q = q.permute(0, 2, 1, 3) # [N, H, L, C] + k = k.permute(0, 2, 1, 3) # [N, H, L, C] + v = v.permute(0, 2, 1, 3) # [N, H, L, C] + out = sdpa(q, k, v) # [N, H, L, C] + out = out.permute(0, 2, 1, 3) # [N, L, H, C] + elif config.BACKEND == 'naive': + if num_all_args == 1: + q, k, v = qkv.unbind(dim=2) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + out = _naive_sdpa(q, k, v) + else: + raise ValueError(f"Unknown attention module: {config.BACKEND}") + + return out diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/modules.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..492784c7ba8f572c4820b604f51c924ed564ab00 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/modules.py @@ -0,0 +1,102 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from .full_attn import scaled_dot_product_attention +from .rope import RotaryPositionEmbedder + + +class MultiHeadRMSNorm(nn.Module): + def __init__(self, dim: int, heads: int): + super().__init__() + self.scale = dim ** 0.5 + self.gamma = nn.Parameter(torch.ones(heads, dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return (F.normalize(x.float(), dim = -1) * self.gamma * self.scale).to(x.dtype) + + +class MultiHeadAttention(nn.Module): + def __init__( + self, + channels: int, + num_heads: int, + ctx_channels: Optional[int]=None, + type: Literal["self", "cross"] = "self", + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + qkv_bias: bool = True, + use_rope: bool = False, + rope_freq: Tuple[float, float] = (1.0, 10000.0), + qk_rms_norm: bool = False, + ): + super().__init__() + assert channels % num_heads == 0 + assert type in ["self", "cross"], f"Invalid attention type: {type}" + assert attn_mode in ["full", "windowed"], f"Invalid attention mode: {attn_mode}" + assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention" + + if attn_mode == "windowed": + raise NotImplementedError("Windowed attention is not yet implemented") + + self.channels = channels + self.head_dim = channels // num_heads + self.ctx_channels = ctx_channels if ctx_channels is not None else channels + self.num_heads = num_heads + self._type = type + self.attn_mode = attn_mode + self.window_size = window_size + self.shift_window = shift_window + self.use_rope = use_rope + self.qk_rms_norm = qk_rms_norm + + if self._type == "self": + self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias) + else: + self.to_q = nn.Linear(channels, channels, bias=qkv_bias) + self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias) + + if self.qk_rms_norm: + self.q_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads) + self.k_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads) + + self.to_out = nn.Linear(channels, channels) + + def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + B, L, C = x.shape + if self._type == "self": + qkv = self.to_qkv(x) + qkv = qkv.reshape(B, L, 3, self.num_heads, -1) + + if self.attn_mode == "full": + if self.qk_rms_norm or self.use_rope: + q, k, v = qkv.unbind(dim=2) + if self.qk_rms_norm: + q = self.q_rms_norm(q) + k = self.k_rms_norm(k) + if self.use_rope: + assert phases is not None, "Phases must be provided for RoPE" + q = RotaryPositionEmbedder.apply_rotary_embedding(q, phases) + k = RotaryPositionEmbedder.apply_rotary_embedding(k, phases) + h = scaled_dot_product_attention(q, k, v) + else: + h = scaled_dot_product_attention(qkv) + elif self.attn_mode == "windowed": + raise NotImplementedError("Windowed attention is not yet implemented") + else: + Lkv = context.shape[1] + q = self.to_q(x) + kv = self.to_kv(context) + q = q.reshape(B, L, self.num_heads, -1) + kv = kv.reshape(B, Lkv, 2, self.num_heads, -1) + if self.qk_rms_norm: + q = self.q_rms_norm(q) + k, v = kv.unbind(dim=2) + k = self.k_rms_norm(k) + h = scaled_dot_product_attention(q, k, v) + else: + h = scaled_dot_product_attention(q, kv) + h = h.reshape(B, L, -1) + h = self.to_out(h) + return h diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/rope.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf6c5b321c2417443ffad3804df97ff5fbe6658 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/attention/rope.py @@ -0,0 +1,48 @@ +from typing import * +import torch +import torch.nn as nn + + +class RotaryPositionEmbedder(nn.Module): + def __init__( + self, + head_dim: int, + dim: int = 3, + rope_freq: Tuple[float, float] = (1.0, 10000.0) + ): + super().__init__() + assert head_dim % 2 == 0, "Head dim must be divisible by 2" + self.head_dim = head_dim + self.dim = dim + self.rope_freq = rope_freq + self.freq_dim = head_dim // 2 // dim + self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim + self.freqs = rope_freq[0] / (rope_freq[1] ** (self.freqs)) + + def _get_phases(self, indices: torch.Tensor) -> torch.Tensor: + self.freqs = self.freqs.to(indices.device) + phases = torch.outer(indices, self.freqs) + phases = torch.polar(torch.ones_like(phases), phases) + return phases + + @staticmethod + def apply_rotary_embedding(x: torch.Tensor, phases: torch.Tensor) -> torch.Tensor: + x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2)) + x_rotated = x_complex * phases.unsqueeze(-2) + x_embed = torch.view_as_real(x_rotated).reshape(*x_rotated.shape[:-1], -1).to(x.dtype) + return x_embed + + def forward(self, indices: torch.Tensor) -> torch.Tensor: + """ + Args: + indices (torch.Tensor): [..., N, C] tensor of spatial positions + """ + assert indices.shape[-1] == self.dim, f"Last dim of indices must be {self.dim}" + phases = self._get_phases(indices.reshape(-1)).reshape(*indices.shape[:-1], -1) + if phases.shape[-1] < self.head_dim // 2: + padn = self.head_dim // 2 - phases.shape[-1] + phases = torch.cat([phases, torch.polar( + torch.ones(*phases.shape[:-1], padn, device=phases.device), + torch.zeros(*phases.shape[:-1], padn, device=phases.device) + )], dim=-1) + return phases \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/image_feature_extractor.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/image_feature_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cb515ad1152752b09fef9999cc5ff44bd885f7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/image_feature_extractor.py @@ -0,0 +1,118 @@ +from typing import * +import torch +import torch.nn.functional as F +from torchvision import transforms +from transformers import DINOv3ViTModel +import numpy as np +from 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 features diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/norm.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..78675d0f850d2e34d3c90b5d6bc14db708e5b400 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/norm.py @@ -0,0 +1,32 @@ +import torch +import torch.nn as nn +from .utils import manual_cast + + +class LayerNorm32(nn.LayerNorm): + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_dtype = x.dtype + x = manual_cast(x, torch.float32) + o = super().forward(x) + return manual_cast(o, x_dtype) + + +class GroupNorm32(nn.GroupNorm): + """ + A GroupNorm layer that converts to float32 before the forward pass. + """ + def forward(self, x: torch.Tensor) -> torch.Tensor: + x_dtype = x.dtype + x = manual_cast(x, torch.float32) + o = super().forward(x) + return manual_cast(o, x_dtype) + + +class ChannelLayerNorm32(LayerNorm32): + def forward(self, x: torch.Tensor) -> torch.Tensor: + DIM = x.dim() + x = x.permute(0, *range(2, DIM), 1).contiguous() + x = super().forward(x) + x = x.permute(0, DIM-1, *range(1, DIM-1)).contiguous() + return x + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e73f232abc6f31cafeac4172a96150906ba20b7b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/__init__.py @@ -0,0 +1,69 @@ +from . import config +import importlib + +__attributes = { + 'VarLenTensor': 'basic', + 'varlen_cat': 'basic', + 'varlen_unbind': 'basic', + 'SparseTensor': 'basic', + 'sparse_cat': 'basic', + 'sparse_unbind': 'basic', + 'SparseGroupNorm': 'norm', + 'SparseLayerNorm': 'norm', + 'SparseGroupNorm32': 'norm', + 'SparseLayerNorm32': 'norm', + 'SparseReLU': 'nonlinearity', + 'SparseSiLU': 'nonlinearity', + 'SparseGELU': 'nonlinearity', + 'SparseActivation': 'nonlinearity', + 'SparseLinear': 'linear', + 'sparse_scaled_dot_product_attention': 'attention', + 'SerializeMode': 'attention', + 'sparse_serialized_scaled_dot_product_self_attention': 'attention', + 'sparse_windowed_scaled_dot_product_self_attention': 'attention', + 'sparse_windowed_scaled_dot_product_cross_attention': 'attention', + 'SparseRotaryPositionEmbedder': 'attention', + 'SparseMultiHeadAttention': 'attention', + 'SparseConv3d': 'conv', + 'SparseInverseConv3d': 'conv', + 'SparseDownsample': 'spatial', + 'SparseUpsample': 'spatial', + 'SparseSubdivide': 'spatial', + 'SparseSpatial2Channel': 'spatial', + 'SparseChannel2Spatial': 'spatial', + 'sparse_nearest_interpolate': 'spatial', + 'sparse_trilinear_interpolate': 'spatial', + 'encode_seq': 'serialize', + 'decode_seq': 'serialize', +} + +__submodules = ['transformer', 'conv'] + +__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] + + +# For Pylance +if __name__ == '__main__': + from .basic import * + from .norm import * + from .nonlinearity import * + from .linear import * + from .attention import * + from .conv import * + from .spatial import * + from .serialize import * + import transformer + import conv diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18ab3cc0a2c96b430009c3b709db3eb28ce7ccc0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/__init__.py @@ -0,0 +1,3 @@ +from .full_attn import * +from .windowed_attn import * +from .modules import * diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/full_attn.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/full_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb74d24c37c1951b579ecce5fabe97c4f0d02bf --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/full_attn.py @@ -0,0 +1,220 @@ +from typing import * +import torch +from .. import VarLenTensor +from .. import config + + +__all__ = [ + 'sparse_scaled_dot_product_attention', +] + + +@overload +def sparse_scaled_dot_product_attention(qkv: VarLenTensor) -> VarLenTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + qkv (VarLenTensor): A [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: VarLenTensor, kv: Union[VarLenTensor, torch.Tensor]) -> VarLenTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (VarLenTensor): A [N, *, H, C] sparse tensor containing Qs. + kv (VarLenTensor or torch.Tensor): A [N, *, 2, H, C] sparse tensor or a [N, L, 2, H, C] dense tensor containing Ks and Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: torch.Tensor, kv: VarLenTensor) -> torch.Tensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (torch.Tensor): A [N, L, H, C] dense tensor containing Qs. + kv (VarLenTensor): A [N, *, 2, H, C] sparse tensor containing Ks and Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: VarLenTensor, k: VarLenTensor, v: VarLenTensor) -> VarLenTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (VarLenTensor): A [N, *, H, Ci] sparse tensor containing Qs. + k (VarLenTensor): A [N, *, H, Ci] sparse tensor containing Ks. + v (VarLenTensor): A [N, *, H, Co] sparse tensor containing Vs. + + Note: + k and v are assumed to have the same coordinate map. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: VarLenTensor, k: torch.Tensor, v: torch.Tensor) -> VarLenTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (VarLenTensor): A [N, *, H, Ci] sparse tensor containing Qs. + k (torch.Tensor): A [N, L, H, Ci] dense tensor containing Ks. + v (torch.Tensor): A [N, L, H, Co] dense tensor containing Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: torch.Tensor, k: VarLenTensor, v: VarLenTensor) -> torch.Tensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (torch.Tensor): A [N, L, H, Ci] dense tensor containing Qs. + k (VarLenTensor): A [N, *, H, Ci] sparse tensor containing Ks. + v (VarLenTensor): A [N, *, H, Co] sparse tensor containing Vs. + """ + ... + +def sparse_scaled_dot_product_attention(*args, **kwargs): + arg_names_dict = { + 1: ['qkv'], + 2: ['q', 'kv'], + 3: ['q', 'k', 'v'] + } + num_all_args = len(args) + len(kwargs) + assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3" + for key in arg_names_dict[num_all_args][len(args):]: + assert key in kwargs, f"Missing argument {key}" + + if num_all_args == 1: + qkv = args[0] if len(args) > 0 else kwargs['qkv'] + assert isinstance(qkv, VarLenTensor), f"qkv must be a VarLenTensor, got {type(qkv)}" + assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]" + device = qkv.device + + s = qkv + q_seqlen = [qkv.layout[i].stop - qkv.layout[i].start for i in range(qkv.shape[0])] + kv_seqlen = q_seqlen + qkv = qkv.feats # [T, 3, H, C] + + elif num_all_args == 2: + q = args[0] if len(args) > 0 else kwargs['q'] + kv = args[1] if len(args) > 1 else kwargs['kv'] + assert isinstance(q, VarLenTensor) and isinstance(kv, (VarLenTensor, torch.Tensor)) or \ + isinstance(q, torch.Tensor) and isinstance(kv, VarLenTensor), \ + f"Invalid types, got {type(q)} and {type(kv)}" + assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}" + device = q.device + + if isinstance(q, VarLenTensor): + assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, C]" + s = q + q_seqlen = [q.layout[i].stop - q.layout[i].start for i in range(q.shape[0])] + q = q.feats # [T_Q, H, C] + else: + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]" + s = None + N, L, H, C = q.shape + q_seqlen = [L] * N + q = q.reshape(N * L, H, C) # [T_Q, H, C] + + if isinstance(kv, VarLenTensor): + assert len(kv.shape) == 4 and kv.shape[1] == 2, f"Invalid shape for kv, got {kv.shape}, expected [N, *, 2, H, C]" + kv_seqlen = [kv.layout[i].stop - kv.layout[i].start for i in range(kv.shape[0])] + kv = kv.feats # [T_KV, 2, H, C] + else: + assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]" + N, L, _, H, C = kv.shape + kv_seqlen = [L] * N + kv = kv.reshape(N * L, 2, H, C) # [T_KV, 2, H, C] + + elif num_all_args == 3: + q = args[0] if len(args) > 0 else kwargs['q'] + k = args[1] if len(args) > 1 else kwargs['k'] + v = args[2] if len(args) > 2 else kwargs['v'] + assert isinstance(q, VarLenTensor) and isinstance(k, (VarLenTensor, torch.Tensor)) and type(k) == type(v) or \ + isinstance(q, torch.Tensor) and isinstance(k, VarLenTensor) and isinstance(v, VarLenTensor), \ + f"Invalid types, got {type(q)}, {type(k)}, and {type(v)}" + 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]}" + device = q.device + + if isinstance(q, VarLenTensor): + assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, Ci]" + s = q + q_seqlen = [q.layout[i].stop - q.layout[i].start for i in range(q.shape[0])] + q = q.feats # [T_Q, H, Ci] + else: + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]" + s = None + N, L, H, CI = q.shape + q_seqlen = [L] * N + q = q.reshape(N * L, H, CI) # [T_Q, H, Ci] + + if isinstance(k, VarLenTensor): + assert len(k.shape) == 3, f"Invalid shape for k, got {k.shape}, expected [N, *, H, Ci]" + assert len(v.shape) == 3, f"Invalid shape for v, got {v.shape}, expected [N, *, H, Co]" + kv_seqlen = [k.layout[i].stop - k.layout[i].start for i in range(k.shape[0])] + k = k.feats # [T_KV, H, Ci] + v = v.feats # [T_KV, H, Co] + else: + assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]" + assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]" + N, L, H, CI, CO = *k.shape, v.shape[-1] + kv_seqlen = [L] * N + k = k.reshape(N * L, H, CI) # [T_KV, H, Ci] + v = v.reshape(N * L, H, CO) # [T_KV, H, Co] + + if config.ATTN == 'xformers': + if 'xops' not in globals(): + import xformers.ops as xops + if num_all_args == 1: + q, k, v = qkv.unbind(dim=1) + elif num_all_args == 2: + k, v = kv.unbind(dim=1) + q = q.unsqueeze(0) + k = k.unsqueeze(0) + v = v.unsqueeze(0) + mask = xops.fmha.BlockDiagonalMask.from_seqlens(q_seqlen, kv_seqlen) + out = xops.memory_efficient_attention(q, k, v, mask)[0] + elif config.ATTN == 'flash_attn': + if 'flash_attn' not in globals(): + import flash_attn + cu_seqlens_q = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(q_seqlen), dim=0)]).int().to(device) + if num_all_args in [2, 3]: + cu_seqlens_kv = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(kv_seqlen), dim=0)]).int().to(device) + if num_all_args == 1: + out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv, cu_seqlens_q, max(q_seqlen)) + elif num_all_args == 2: + out = flash_attn.flash_attn_varlen_kvpacked_func(q, kv, cu_seqlens_q, cu_seqlens_kv, max(q_seqlen), max(kv_seqlen)) + elif num_all_args == 3: + out = flash_attn.flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max(q_seqlen), max(kv_seqlen)) + elif config.ATTN == 'flash_attn_3': + if 'flash_attn_3' not in globals(): + import flash_attn_interface as flash_attn_3 + cu_seqlens_q = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(q_seqlen), dim=0)]).int().to(device) + if num_all_args == 1: + q, k, v = qkv.unbind(dim=1) + cu_seqlens_kv = cu_seqlens_q.clone() + max_q_seqlen = max_kv_seqlen = max(q_seqlen) + elif num_all_args == 2: + k, v = kv.unbind(dim=1) + cu_seqlens_kv = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(kv_seqlen), dim=0)]).int().to(device) + max_q_seqlen = max(q_seqlen) + max_kv_seqlen = max(kv_seqlen) + elif num_all_args == 3: + cu_seqlens_kv = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(kv_seqlen), dim=0)]).int().to(device) + max_q_seqlen = max(q_seqlen) + max_kv_seqlen = max(kv_seqlen) + out = flash_attn_3.flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_q_seqlen, max_kv_seqlen) + else: + raise ValueError(f"Unknown attention module: {config.ATTN}") + + if s is not None: + return s.replace(out) + else: + return out.reshape(N, L, H, -1) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/modules.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..d762b4b2e01335d26d856b3fe82eca31a2735123 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/modules.py @@ -0,0 +1,141 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from .. import VarLenTensor, SparseTensor +from .full_attn import sparse_scaled_dot_product_attention +from .windowed_attn import sparse_windowed_scaled_dot_product_self_attention +from .rope import SparseRotaryPositionEmbedder + + +class SparseMultiHeadRMSNorm(nn.Module): + def __init__(self, dim: int, heads: int): + super().__init__() + self.scale = dim ** 0.5 + self.gamma = nn.Parameter(torch.ones(heads, dim)) + + def forward(self, x: Union[VarLenTensor, torch.Tensor]) -> Union[VarLenTensor, torch.Tensor]: + x_type = x.dtype + x = x.float() + if isinstance(x, VarLenTensor): + x = x.replace(F.normalize(x.feats, dim=-1) * self.gamma * self.scale) + else: + x = F.normalize(x, dim=-1) * self.gamma * self.scale + return x.to(x_type) + + +class SparseMultiHeadAttention(nn.Module): + def __init__( + self, + channels: int, + num_heads: int, + ctx_channels: Optional[int] = None, + type: Literal["self", "cross"] = "self", + attn_mode: Literal["full", "windowed", "double_windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + qkv_bias: bool = True, + use_rope: bool = False, + rope_freq: Tuple[int, int] = (1.0, 10000.0), + qk_rms_norm: bool = False, + ): + super().__init__() + assert channels % num_heads == 0 + assert type in ["self", "cross"], f"Invalid attention type: {type}" + assert attn_mode in ["full", "windowed", "double_windowed"], f"Invalid attention mode: {attn_mode}" + assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention" + assert type == "self" or use_rope is False, "Rotary position embeddings only supported for self-attention" + if attn_mode == 'double_windowed': + assert window_size % 2 == 0, "Window size must be even for double windowed attention" + assert num_heads % 2 == 0, "Number of heads must be even for double windowed attention" + self.channels = channels + self.head_dim = channels // num_heads + self.ctx_channels = ctx_channels if ctx_channels is not None else channels + self.num_heads = num_heads + self._type = type + self.attn_mode = attn_mode + self.window_size = window_size + self.shift_window = shift_window + self.use_rope = use_rope + self.qk_rms_norm = qk_rms_norm + + if self._type == "self": + self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias) + else: + self.to_q = nn.Linear(channels, channels, bias=qkv_bias) + self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias) + + if self.qk_rms_norm: + self.q_rms_norm = SparseMultiHeadRMSNorm(self.head_dim, num_heads) + self.k_rms_norm = SparseMultiHeadRMSNorm(self.head_dim, num_heads) + + self.to_out = nn.Linear(channels, channels) + + if use_rope: + self.rope = SparseRotaryPositionEmbedder(self.head_dim, rope_freq=rope_freq) + + @staticmethod + def _linear(module: nn.Linear, x: Union[VarLenTensor, torch.Tensor]) -> Union[VarLenTensor, torch.Tensor]: + if isinstance(x, VarLenTensor): + return x.replace(module(x.feats)) + else: + return module(x) + + @staticmethod + def _reshape_chs(x: Union[VarLenTensor, torch.Tensor], shape: Tuple[int, ...]) -> Union[VarLenTensor, torch.Tensor]: + if isinstance(x, VarLenTensor): + return x.reshape(*shape) + else: + return x.reshape(*x.shape[:2], *shape) + + def _fused_pre(self, x: Union[VarLenTensor, torch.Tensor], num_fused: int) -> Union[VarLenTensor, torch.Tensor]: + if isinstance(x, VarLenTensor): + x_feats = x.feats.unsqueeze(0) + else: + x_feats = x + x_feats = x_feats.reshape(*x_feats.shape[:2], num_fused, self.num_heads, -1) + return x.replace(x_feats.squeeze(0)) if isinstance(x, VarLenTensor) else x_feats + + def forward(self, x: SparseTensor, context: Optional[Union[VarLenTensor, torch.Tensor]] = None) -> SparseTensor: + if self._type == "self": + qkv = self._linear(self.to_qkv, x) + qkv = self._fused_pre(qkv, num_fused=3) + if self.qk_rms_norm or self.use_rope: + q, k, v = qkv.unbind(dim=-3) + if self.qk_rms_norm: + q = self.q_rms_norm(q) + k = self.k_rms_norm(k) + if self.use_rope: + q, k = self.rope(q, k) + qkv = qkv.replace(torch.stack([q.feats, k.feats, v.feats], dim=1)) + if self.attn_mode == "full": + h = sparse_scaled_dot_product_attention(qkv) + elif self.attn_mode == "windowed": + h = sparse_windowed_scaled_dot_product_self_attention( + qkv, self.window_size, shift_window=self.shift_window + ) + elif self.attn_mode == "double_windowed": + qkv0 = qkv.replace(qkv.feats[:, :, self.num_heads//2:]) + qkv1 = qkv.replace(qkv.feats[:, :, :self.num_heads//2]) + h0 = sparse_windowed_scaled_dot_product_self_attention( + qkv0, self.window_size, shift_window=(0, 0, 0) + ) + h1 = sparse_windowed_scaled_dot_product_self_attention( + qkv1, self.window_size, shift_window=tuple([self.window_size//2] * 3) + ) + h = qkv.replace(torch.cat([h0.feats, h1.feats], dim=1)) + else: + q = self._linear(self.to_q, x) + q = self._reshape_chs(q, (self.num_heads, -1)) + kv = self._linear(self.to_kv, context) + kv = self._fused_pre(kv, num_fused=2) + if self.qk_rms_norm: + q = self.q_rms_norm(q) + k, v = kv.unbind(dim=-3) + k = self.k_rms_norm(k) + h = sparse_scaled_dot_product_attention(q, k, v) + else: + h = sparse_scaled_dot_product_attention(q, kv) + h = self._reshape_chs(h, (-1,)) + h = self._linear(self.to_out, h) + return h diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/rope.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..fb877291f3430f2cff4329a67b3592e0e3c3f137 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/rope.py @@ -0,0 +1,58 @@ +from typing import * +import torch +import torch.nn as nn +from ..basic import SparseTensor + + +class SparseRotaryPositionEmbedder(nn.Module): + def __init__( + self, + head_dim: int, + dim: int = 3, + rope_freq: Tuple[float, float] = (1.0, 10000.0) + ): + super().__init__() + assert head_dim % 2 == 0, "Head dim must be divisible by 2" + self.head_dim = head_dim + self.dim = dim + self.rope_freq = rope_freq + self.freq_dim = head_dim // 2 // dim + self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim + self.freqs = rope_freq[0] / (rope_freq[1] ** (self.freqs)) + + def _get_phases(self, indices: torch.Tensor) -> torch.Tensor: + self.freqs = self.freqs.to(indices.device) + phases = torch.outer(indices, self.freqs) + phases = torch.polar(torch.ones_like(phases), phases) + return phases + + def _rotary_embedding(self, x: torch.Tensor, phases: torch.Tensor) -> torch.Tensor: + x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2)) + x_rotated = x_complex * phases.unsqueeze(-2) + x_embed = torch.view_as_real(x_rotated).reshape(*x_rotated.shape[:-1], -1).to(x.dtype) + return x_embed + + def forward(self, q: SparseTensor, k: Optional[SparseTensor] = None) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + q (SparseTensor): [..., N, H, D] tensor of queries + k (SparseTensor): [..., N, H, D] tensor of keys + """ + assert q.coords.shape[-1] == self.dim + 1, "Last dimension of coords must be equal to dim+1" + phases_cache_name = f'rope_phase_{self.dim}d_freq{self.rope_freq[0]}-{self.rope_freq[1]}_hd{self.head_dim}' + phases = q.get_spatial_cache(phases_cache_name) + if phases is None: + coords = q.coords[..., 1:] + phases = self._get_phases(coords.reshape(-1)).reshape(*coords.shape[:-1], -1) + if phases.shape[-1] < self.head_dim // 2: + padn = self.head_dim // 2 - phases.shape[-1] + phases = torch.cat([phases, torch.polar( + torch.ones(*phases.shape[:-1], padn, device=phases.device), + torch.zeros(*phases.shape[:-1], padn, device=phases.device) + )], dim=-1) + q.register_spatial_cache(phases_cache_name, phases) + q_embed = q.replace(self._rotary_embedding(q.feats, phases)) + if k is None: + return q_embed + k_embed = k.replace(self._rotary_embedding(k.feats, phases)) + return q_embed, k_embed \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/windowed_attn.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/windowed_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..043078899833e52ebf29d3ba1898cbd90e03f1d4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/attention/windowed_attn.py @@ -0,0 +1,190 @@ +from typing import * +import torch +import math +from .. import SparseTensor +from .. import config + + +__all__ = [ + 'sparse_windowed_scaled_dot_product_self_attention', + 'sparse_windowed_scaled_dot_product_cross_attention', +] + + +def calc_window_partition( + tensor: SparseTensor, + window_size: Union[int, Tuple[int, ...]], + shift_window: Union[int, Tuple[int, ...]] = 0, +) -> Tuple[torch.Tensor, torch.Tensor, List[int], List[int]]: + """ + Calculate serialization and partitioning for a set of coordinates. + + Args: + tensor (SparseTensor): The input tensor. + window_size (int): The window size to use. + shift_window (Tuple[int, ...]): The shift of serialized coordinates. + + Returns: + (torch.Tensor): Forwards indices. + (torch.Tensor): Backwards indices. + (torch.Tensor): Sequence lengths. + (dict): Attn func args. + """ + DIM = tensor.coords.shape[1] - 1 + shift_window = (shift_window,) * DIM if isinstance(shift_window, int) else shift_window + window_size = (window_size,) * DIM if isinstance(window_size, int) else window_size + shifted_coords = tensor.coords.clone().detach() + shifted_coords[:, 1:] += torch.tensor(shift_window, device=tensor.device, dtype=torch.int32).unsqueeze(0) + + MAX_COORDS = [i + j for i, j in zip(tensor.spatial_shape, shift_window)] + NUM_WINDOWS = [math.ceil((mc + 1) / ws) for mc, ws in zip(MAX_COORDS, window_size)] + OFFSET = torch.cumprod(torch.tensor([1] + NUM_WINDOWS[::-1]), dim=0).tolist()[::-1] + + shifted_coords[:, 1:] //= torch.tensor(window_size, device=tensor.device, dtype=torch.int32).unsqueeze(0) + shifted_indices = (shifted_coords * torch.tensor(OFFSET, device=tensor.device, dtype=torch.int32).unsqueeze(0)).sum(dim=1) + fwd_indices = torch.argsort(shifted_indices) + bwd_indices = torch.empty_like(fwd_indices) + bwd_indices[fwd_indices] = torch.arange(fwd_indices.shape[0], device=tensor.device) + seq_lens = torch.bincount(shifted_indices) + mask = seq_lens != 0 + seq_lens = seq_lens[mask] + + if config.ATTN == 'xformers': + if 'xops' not in globals(): + import xformers.ops as xops + attn_func_args = { + 'attn_bias': xops.fmha.BlockDiagonalMask.from_seqlens(seq_lens) + } + elif config.ATTN == 'flash_attn': + attn_func_args = { + 'cu_seqlens': torch.cat([torch.tensor([0], device=tensor.device), torch.cumsum(seq_lens, dim=0)], dim=0).int(), + 'max_seqlen': torch.max(seq_lens) + } + + return fwd_indices, bwd_indices, seq_lens, attn_func_args + + +def sparse_windowed_scaled_dot_product_self_attention( + qkv: SparseTensor, + window_size: int, + shift_window: Tuple[int, int, int] = (0, 0, 0) +) -> SparseTensor: + """ + Apply windowed scaled dot product self attention to a sparse tensor. + + Args: + qkv (SparseTensor): [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs. + window_size (int): The window size to use. + shift_window (Tuple[int, int, int]): The shift of serialized coordinates. + + Returns: + (SparseTensor): [N, *, H, C] sparse tensor containing the output features. + """ + assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]" + + serialization_spatial_cache_name = f'windowed_attention_{window_size}_{shift_window}' + serialization_spatial_cache = qkv.get_spatial_cache(serialization_spatial_cache_name) + if serialization_spatial_cache is None: + fwd_indices, bwd_indices, seq_lens, attn_func_args = calc_window_partition(qkv, window_size, shift_window) + qkv.register_spatial_cache(serialization_spatial_cache_name, (fwd_indices, bwd_indices, seq_lens, attn_func_args)) + else: + fwd_indices, bwd_indices, seq_lens, attn_func_args = serialization_spatial_cache + + qkv_feats = qkv.feats[fwd_indices] # [M, 3, H, C] + + if config.DEBUG: + start = 0 + qkv_coords = qkv.coords[fwd_indices] + for i in range(len(seq_lens)): + seq_coords = qkv_coords[start:start+seq_lens[i]] + assert (seq_coords[:, 1:].max(dim=0).values - seq_coords[:, 1:].min(dim=0).values < window_size).all(), \ + f"SparseWindowedScaledDotProductSelfAttention: window size exceeded" + start += seq_lens[i] + + if config.ATTN == 'xformers': + if 'xops' not in globals(): + import xformers.ops as xops + q, k, v = qkv_feats.unbind(dim=1) # [M, H, C] + q = q.unsqueeze(0) # [1, M, H, C] + k = k.unsqueeze(0) # [1, M, H, C] + v = v.unsqueeze(0) # [1, M, H, C] + out = xops.memory_efficient_attention(q, k, v, **attn_func_args)[0] # [M, H, C] + elif config.ATTN == 'flash_attn': + if 'flash_attn' not in globals(): + import flash_attn + out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv_feats, **attn_func_args) # [M, H, C] + + out = out[bwd_indices] # [T, H, C] + + if config.DEBUG: + qkv_coords = qkv_coords[bwd_indices] + assert torch.equal(qkv_coords, qkv.coords), "SparseWindowedScaledDotProductSelfAttention: coordinate mismatch" + + return qkv.replace(out) + + +def sparse_windowed_scaled_dot_product_cross_attention( + q: SparseTensor, + kv: SparseTensor, + q_window_size: int, + kv_window_size: int, + q_shift_window: Tuple[int, int, int] = (0, 0, 0), + kv_shift_window: Tuple[int, int, int] = (0, 0, 0), +) -> SparseTensor: + """ + Apply windowed scaled dot product cross attention to two sparse tensors. + + Args: + q (SparseTensor): [N, *, H, C] sparse tensor containing Qs. + kv (SparseTensor): [N, *, 2, H, C] sparse tensor containing Ks and Vs. + q_window_size (int): The window size to use for Qs. + kv_window_size (int): The window size to use for Ks and Vs. + q_shift_window (Tuple[int, int, int]): The shift of serialized coordinates for Qs. + kv_shift_window (Tuple[int, int, int]): The shift of serialized coordinates for Ks and Vs. + + Returns: + (SparseTensor): [N, *, H, C] sparse tensor containing the output features. + """ + assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, C]" + assert len(kv.shape) == 4 and kv.shape[1] == 2, f"Invalid shape for kv, got {kv.shape}, expected [N, *, 2, H, C]" + + q_serialization_spatial_cache_name = f'windowed_attention_{q_window_size}_{q_shift_window}' + q_serialization_spatial_cache = q.get_spatial_cache(q_serialization_spatial_cache_name) + if q_serialization_spatial_cache is None: + q_fwd_indices, q_bwd_indices, q_seq_lens, q_attn_func_args = calc_window_partition(q, q_window_size, q_shift_window) + q.register_spatial_cache(q_serialization_spatial_cache_name, (q_fwd_indices, q_bwd_indices, q_seq_lens, q_attn_func_args)) + else: + q_fwd_indices, q_bwd_indices, q_seq_lens, q_attn_func_args = q_serialization_spatial_cache + kv_serialization_spatial_cache_name = f'windowed_attention_{kv_window_size}_{kv_shift_window}' + kv_serialization_spatial_cache = kv.get_spatial_cache(kv_serialization_spatial_cache_name) + if kv_serialization_spatial_cache is None: + kv_fwd_indices, kv_bwd_indices, kv_seq_lens, kv_attn_func_args = calc_window_partition(kv, kv_window_size, kv_shift_window) + kv.register_spatial_cache(kv_serialization_spatial_cache_name, (kv_fwd_indices, kv_bwd_indices, kv_seq_lens, kv_attn_func_args)) + else: + kv_fwd_indices, kv_bwd_indices, kv_seq_lens, kv_attn_func_args = kv_serialization_spatial_cache + + assert len(q_seq_lens) == len(kv_seq_lens), "Number of sequences in q and kv must match" + + q_feats = q.feats[q_fwd_indices] # [M, H, C] + kv_feats = kv.feats[kv_fwd_indices] # [M, 2, H, C] + + if config.ATTN == 'xformers': + if 'xops' not in globals(): + import xformers.ops as xops + k, v = kv_feats.unbind(dim=1) # [M, H, C] + q = q.unsqueeze(0) # [1, M, H, C] + k = k.unsqueeze(0) # [1, M, H, C] + v = v.unsqueeze(0) # [1, M, H, C] + mask = xops.fmha.BlockDiagonalMask.from_seqlens(q_seq_lens, kv_seq_lens) + out = xops.memory_efficient_attention(q, k, v, attn_bias=mask)[0] # [M, H, C] + elif config.ATTN == 'flash_attn': + if 'flash_attn' not in globals(): + import flash_attn + out = flash_attn.flash_attn_varlen_kvpacked_func(q_feats, kv_feats, + cu_seqlens_q=q_attn_func_args['cu_seqlens'], cu_seqlens_k=kv_attn_func_args['cu_seqlens'], + max_seqlen_q=q_attn_func_args['max_seqlen'], max_seqlen_k=kv_attn_func_args['max_seqlen'], + ) # [M, H, C] + + out = out[q_bwd_indices] # [T, H, C] + + return q.replace(out) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/basic.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..880973b8dd6bdafcfca4ca7c529308d2ef2ad266 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/basic.py @@ -0,0 +1,836 @@ +from typing import * +from fractions import Fraction +import torch +from . import config + + +__all__ = [ + 'VarLenTensor', + 'varlen_cat', + 'varlen_unbind', + 'SparseTensor', + 'sparse_cat', + 'sparse_unbind', +] + + +class VarLenTensor: + """ + Sequential tensor with variable length. + + Args: + feats (torch.Tensor): Features of the varlen tensor. + layout (List[slice]): Layout of the varlen tensor for each batch + """ + def __init__(self, feats: torch.Tensor, layout: List[slice]=None): + self.feats = feats + self.layout = layout if layout is not None else [slice(0, feats.shape[0])] + self._cache = {} + + @staticmethod + def layout_from_seqlen(seqlen: list) -> List[slice]: + """ + Create a layout from a tensor of sequence lengths. + """ + layout = [] + start = 0 + for l in seqlen: + layout.append(slice(start, start + l)) + start += l + return layout + + @staticmethod + def from_tensor_list(tensor_list: List[torch.Tensor]) -> 'VarLenTensor': + """ + Create a VarLenTensor from a list of tensors. + """ + feats = torch.cat(tensor_list, dim=0) + layout = [] + start = 0 + for tensor in tensor_list: + layout.append(slice(start, start + tensor.shape[0])) + start += tensor.shape[0] + return VarLenTensor(feats, layout) + + def to_tensor_list(self) -> List[torch.Tensor]: + """ + Convert a VarLenTensor to a list of tensors. + """ + tensor_list = [] + for s in self.layout: + tensor_list.append(self.feats[s]) + return tensor_list + + def __len__(self) -> int: + return len(self.layout) + + @property + def shape(self) -> torch.Size: + return torch.Size([len(self.layout), *self.feats.shape[1:]]) + + def dim(self) -> int: + return len(self.shape) + + @property + def ndim(self) -> int: + return self.dim() + + @property + def dtype(self): + return self.feats.dtype + + @property + def device(self): + return self.feats.device + + @property + def seqlen(self) -> torch.LongTensor: + if 'seqlen' not in self._cache: + self._cache['seqlen'] = torch.tensor([l.stop - l.start for l in self.layout], dtype=torch.long, device=self.device) + return self._cache['seqlen'] + + @property + def cum_seqlen(self) -> torch.LongTensor: + if 'cum_seqlen' not in self._cache: + self._cache['cum_seqlen'] = torch.cat([ + torch.tensor([0], dtype=torch.long, device=self.device), + self.seqlen.cumsum(dim=0) + ], dim=0) + return self._cache['cum_seqlen'] + + @property + def batch_boardcast_map(self) -> torch.LongTensor: + """ + Get the broadcast map for the varlen tensor. + """ + if 'batch_boardcast_map' not in self._cache: + self._cache['batch_boardcast_map'] = torch.repeat_interleave( + torch.arange(len(self.layout), device=self.device), + self.seqlen, + ) + return self._cache['batch_boardcast_map'] + + @overload + def to(self, dtype: torch.dtype, *, non_blocking: bool = False, copy: bool = False) -> 'VarLenTensor': ... + + @overload + def to(self, device: Optional[Union[str, torch.device]] = None, dtype: Optional[torch.dtype] = None, *, non_blocking: bool = False, copy: bool = False) -> 'VarLenTensor': ... + + def to(self, *args, **kwargs) -> 'VarLenTensor': + device = None + dtype = None + if len(args) == 2: + device, dtype = args + elif len(args) == 1: + if isinstance(args[0], torch.dtype): + dtype = args[0] + else: + device = args[0] + if 'dtype' in kwargs: + assert dtype is None, "to() received multiple values for argument 'dtype'" + dtype = kwargs['dtype'] + if 'device' in kwargs: + assert device is None, "to() received multiple values for argument 'device'" + device = kwargs['device'] + non_blocking = kwargs.get('non_blocking', False) + copy = kwargs.get('copy', False) + + new_feats = self.feats.to(device=device, dtype=dtype, non_blocking=non_blocking, copy=copy) + return self.replace(new_feats) + + def type(self, dtype): + new_feats = self.feats.type(dtype) + return self.replace(new_feats) + + def cpu(self) -> 'VarLenTensor': + new_feats = self.feats.cpu() + return self.replace(new_feats) + + def cuda(self) -> 'VarLenTensor': + new_feats = self.feats.cuda() + return self.replace(new_feats) + + def half(self) -> 'VarLenTensor': + new_feats = self.feats.half() + return self.replace(new_feats) + + def float(self) -> 'VarLenTensor': + new_feats = self.feats.float() + return self.replace(new_feats) + + def detach(self) -> 'VarLenTensor': + new_feats = self.feats.detach() + return self.replace(new_feats) + + def reshape(self, *shape) -> 'VarLenTensor': + new_feats = self.feats.reshape(self.feats.shape[0], *shape) + return self.replace(new_feats) + + def unbind(self, dim: int) -> List['VarLenTensor']: + return varlen_unbind(self, dim) + + def replace(self, feats: torch.Tensor) -> 'VarLenTensor': + new_tensor = VarLenTensor( + feats=feats, + layout=self.layout, + ) + new_tensor._cache = self._cache + return new_tensor + + def to_dense(self, max_length=None) -> torch.Tensor: + """ + Convert a VarLenTensor to a dense representation without for-loop. + + Returns: + dense (torch.Tensor): (N, L, C) dense tensor + mask (torch.BoolTensor): (N, L) mask indicating valid positions + """ + N = len(self) + L = max_length or self.seqlen.max().item() + spatial = self.feats.shape[1:] + idx = torch.arange(L, device=self.device).unsqueeze(0).expand(N, L) + mask = (idx < self.seqlen.unsqueeze(1)) + mapping = mask.reshape(-1).cumsum(dim=0) - 1 + dense = self.feats[mapping] + dense = dense.reshape(N, L, *spatial) + return dense, mask + + def __neg__(self) -> 'VarLenTensor': + return self.replace(-self.feats) + + def __elemwise__(self, other: Union[torch.Tensor, 'VarLenTensor'], op: callable) -> 'VarLenTensor': + if isinstance(other, torch.Tensor): + try: + other = torch.broadcast_to(other, self.shape) + other = other[self.batch_boardcast_map] + except: + pass + if isinstance(other, VarLenTensor): + other = other.feats + new_feats = op(self.feats, other) + new_tensor = self.replace(new_feats) + return new_tensor + + def __add__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, torch.add) + + def __radd__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, torch.add) + + def __sub__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, torch.sub) + + def __rsub__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, lambda x, y: torch.sub(y, x)) + + def __mul__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, torch.mul) + + def __rmul__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, torch.mul) + + def __truediv__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, torch.div) + + def __rtruediv__(self, other: Union[torch.Tensor, 'VarLenTensor', float]) -> 'VarLenTensor': + return self.__elemwise__(other, lambda x, y: torch.div(y, x)) + + def __getitem__(self, idx): + if isinstance(idx, int): + idx = [idx] + elif isinstance(idx, slice): + idx = range(*idx.indices(self.shape[0])) + elif isinstance(idx, list): + assert all(isinstance(i, int) for i in idx), f"Only integer indices are supported: {idx}" + elif isinstance(idx, torch.Tensor): + if idx.dtype == torch.bool: + assert idx.shape == (self.shape[0],), f"Invalid index shape: {idx.shape}" + idx = idx.nonzero().squeeze(1) + elif idx.dtype in [torch.int32, torch.int64]: + assert len(idx.shape) == 1, f"Invalid index shape: {idx.shape}" + else: + raise ValueError(f"Unknown index type: {idx.dtype}") + else: + raise ValueError(f"Unknown index type: {type(idx)}") + + new_feats = [] + new_layout = [] + start = 0 + for new_idx, old_idx in enumerate(idx): + new_feats.append(self.feats[self.layout[old_idx]]) + new_layout.append(slice(start, start + len(new_feats[-1]))) + start += len(new_feats[-1]) + new_feats = torch.cat(new_feats, dim=0).contiguous() + new_tensor = VarLenTensor(feats=new_feats, layout=new_layout) + return new_tensor + + def reduce(self, op: str, dim: Optional[Union[int, Tuple[int,...]]] = None, keepdim: bool = False) -> torch.Tensor: + if isinstance(dim, int): + dim = (dim,) + + if op =='mean': + red = self.feats.mean(dim=dim, keepdim=keepdim) + elif op =='sum': + red = self.feats.sum(dim=dim, keepdim=keepdim) + elif op == 'prod': + red = self.feats.prod(dim=dim, keepdim=keepdim) + else: + raise ValueError(f"Unsupported reduce operation: {op}") + + if dim is None or 0 in dim: + return red + + red = torch.segment_reduce(red, reduce=op, lengths=self.seqlen) + return red + + def mean(self, dim: Optional[Union[int, Tuple[int,...]]] = None, keepdim: bool = False) -> torch.Tensor: + return self.reduce(op='mean', dim=dim, keepdim=keepdim) + + def sum(self, dim: Optional[Union[int, Tuple[int,...]]] = None, keepdim: bool = False) -> torch.Tensor: + return self.reduce(op='sum', dim=dim, keepdim=keepdim) + + def prod(self, dim: Optional[Union[int, Tuple[int,...]]] = None, keepdim: bool = False) -> torch.Tensor: + return self.reduce(op='prod', dim=dim, keepdim=keepdim) + + def std(self, dim: Optional[Union[int, Tuple[int,...]]] = None, keepdim: bool = False) -> torch.Tensor: + mean = self.mean(dim=dim, keepdim=True) + mean2 = self.replace(self.feats ** 2).mean(dim=dim, keepdim=True) + std = (mean2 - mean ** 2).sqrt() + return std + + def __repr__(self) -> str: + return f"VarLenTensor(shape={self.shape}, dtype={self.dtype}, device={self.device})" + + +def varlen_cat(inputs: List[VarLenTensor], dim: int = 0) -> VarLenTensor: + """ + Concatenate a list of varlen tensors. + + Args: + inputs (List[VarLenTensor]): List of varlen tensors to concatenate. + """ + if dim == 0: + new_feats = torch.cat([input.feats for input in inputs], dim=0) + start = 0 + new_layout = [] + for input in inputs: + for l in input.layout: + new_layout.append(slice(start, start + l.stop - l.start)) + start += l.stop - l.start + output = VarLenTensor(feats=new_feats, layout=new_layout) + else: + feats = torch.cat([input.feats for input in inputs], dim=dim) + output = inputs[0].replace(feats) + + return output + + +def varlen_unbind(input: VarLenTensor, dim: int) -> Union[List[VarLenTensor]]: + """ + Unbind a varlen tensor along a dimension. + + Args: + input (VarLenTensor): Varlen tensor to unbind. + dim (int): Dimension to unbind. + """ + if dim == 0: + return [input[i] for i in range(len(input))] + else: + feats = input.feats.unbind(dim) + return [input.replace(f) for f in feats] + + +class SparseTensor(VarLenTensor): + """ + Sparse tensor with support for both torchsparse and spconv backends. + + Parameters: + - feats (torch.Tensor): Features of the sparse tensor. + - coords (torch.Tensor): Coordinates of the sparse tensor. + - shape (torch.Size): Shape of the sparse tensor. + - layout (List[slice]): Layout of the sparse tensor for each batch + - data (SparseTensorData): Sparse tensor data used for convolusion + + NOTE: + - Data corresponding to a same batch should be contiguous. + - Coords should be in [0, 1023] + """ + SparseTensorData = None + + @overload + def __init__(self, feats: torch.Tensor, coords: torch.Tensor, shape: Optional[torch.Size] = None, **kwargs): ... + + @overload + def __init__(self, data, shape: Optional[torch.Size] = None, **kwargs): ... + + def __init__(self, *args, **kwargs): + # Lazy import of sparse tensor backend + if self.SparseTensorData is None: + import importlib + if config.CONV == 'torchsparse': + self.SparseTensorData = importlib.import_module('torchsparse').SparseTensor + elif config.CONV == 'spconv': + self.SparseTensorData = importlib.import_module('spconv.pytorch').SparseConvTensor + + method_id = 0 + if len(args) != 0: + method_id = 0 if isinstance(args[0], torch.Tensor) else 1 + else: + method_id = 1 if 'data' in kwargs else 0 + + if method_id == 0: + feats, coords, shape = args + (None,) * (3 - len(args)) + if 'feats' in kwargs: + feats = kwargs['feats'] + del kwargs['feats'] + if 'coords' in kwargs: + coords = kwargs['coords'] + del kwargs['coords'] + if 'shape' in kwargs: + shape = kwargs['shape'] + del kwargs['shape'] + + if config.CONV == 'torchsparse': + self.data = self.SparseTensorData(feats, coords, **kwargs) + elif config.CONV == 'spconv': + spatial_shape = list(coords.max(0)[0] + 1) + self.data = self.SparseTensorData(feats.reshape(feats.shape[0], -1), coords, spatial_shape[1:], spatial_shape[0], **kwargs) + self.data._features = feats + else: + self.data = { + 'feats': feats, + 'coords': coords, + } + elif method_id == 1: + data, shape = args + (None,) * (2 - len(args)) + if 'data' in kwargs: + data = kwargs['data'] + del kwargs['data'] + if 'shape' in kwargs: + shape = kwargs['shape'] + del kwargs['shape'] + + self.data = data + + self._shape = shape + self._scale = kwargs.get('scale', (Fraction(1, 1), Fraction(1, 1), Fraction(1, 1))) + self._spatial_cache = kwargs.get('spatial_cache', {}) + + if config.DEBUG: + try: + assert self.feats.shape[0] == self.coords.shape[0], f"Invalid feats shape: {self.feats.shape}, coords shape: {self.coords.shape}" + assert self.shape == self.__cal_shape(self.feats, self.coords), f"Invalid shape: {self.shape}" + assert self.layout == self.__cal_layout(self.coords, self.shape[0]), f"Invalid layout: {self.layout}" + for i in range(self.shape[0]): + assert torch.all(self.coords[self.layout[i], 0] == i), f"The data of batch {i} is not contiguous" + except Exception as e: + print('Debugging information:') + print(f"- Shape: {self.shape}") + print(f"- Layout: {self.layout}") + print(f"- Scale: {self._scale}") + print(f"- Coords: {self.coords}") + raise e + + @staticmethod + def from_tensor_list(feats_list: List[torch.Tensor], coords_list: List[torch.Tensor]) -> 'SparseTensor': + """ + Create a SparseTensor from a list of tensors. + """ + feats = torch.cat(feats_list, dim=0) + coords = [] + for i, coord in enumerate(coords_list): + coord = torch.cat([torch.full_like(coord[:, :1], i), coord[:, 1:]], dim=1) + coords.append(coord) + coords = torch.cat(coords, dim=0) + return SparseTensor(feats, coords) + + def to_tensor_list(self) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: + """ + Convert a SparseTensor to list of tensors. + """ + feats_list = [] + coords_list = [] + for s in self.layout: + feats_list.append(self.feats[s]) + coords_list.append(self.coords[s]) + return feats_list, coords_list + + def __len__(self) -> int: + return len(self.layout) + + def __cal_shape(self, feats, coords): + shape = [] + shape.append(coords[:, 0].max().item() + 1) + shape.extend([*feats.shape[1:]]) + return torch.Size(shape) + + def __cal_layout(self, coords, batch_size): + seq_len = torch.bincount(coords[:, 0], minlength=batch_size) + offset = torch.cumsum(seq_len, dim=0) + layout = [slice((offset[i] - seq_len[i]).item(), offset[i].item()) for i in range(batch_size)] + return layout + + def __cal_spatial_shape(self, coords): + return torch.Size((coords[:, 1:].max(0)[0] + 1).tolist()) + + @property + def shape(self) -> torch.Size: + if self._shape is None: + self._shape = self.__cal_shape(self.feats, self.coords) + return self._shape + + @property + def layout(self) -> List[slice]: + layout = self.get_spatial_cache('layout') + if layout is None: + layout = self.__cal_layout(self.coords, self.shape[0]) + self.register_spatial_cache('layout', layout) + return layout + + @property + def spatial_shape(self) -> torch.Size: + spatial_shape = self.get_spatial_cache('shape') + if spatial_shape is None: + spatial_shape = self.__cal_spatial_shape(self.coords) + self.register_spatial_cache('shape', spatial_shape) + return spatial_shape + + @property + def feats(self) -> torch.Tensor: + if config.CONV == 'torchsparse': + return self.data.F + elif config.CONV == 'spconv': + return self.data.features + else: + return self.data['feats'] + + @feats.setter + def feats(self, value: torch.Tensor): + if config.CONV == 'torchsparse': + self.data.F = value + elif config.CONV == 'spconv': + self.data.features = value + else: + self.data['feats'] = value + + @property + def coords(self) -> torch.Tensor: + if config.CONV == 'torchsparse': + return self.data.C + elif config.CONV == 'spconv': + return self.data.indices + else: + return self.data['coords'] + + @coords.setter + def coords(self, value: torch.Tensor): + if config.CONV == 'torchsparse': + self.data.C = value + elif config.CONV == 'spconv': + self.data.indices = value + else: + self.data['coords'] = value + + @property + def dtype(self): + return self.feats.dtype + + @property + def device(self): + return self.feats.device + + @property + def seqlen(self) -> torch.LongTensor: + seqlen = self.get_spatial_cache('seqlen') + if seqlen is None: + seqlen = torch.tensor([l.stop - l.start for l in self.layout], dtype=torch.long, device=self.device) + self.register_spatial_cache('seqlen', seqlen) + return seqlen + + @property + def cum_seqlen(self) -> torch.LongTensor: + cum_seqlen = self.get_spatial_cache('cum_seqlen') + if cum_seqlen is None: + cum_seqlen = torch.cat([ + torch.tensor([0], dtype=torch.long, device=self.device), + self.seqlen.cumsum(dim=0) + ], dim=0) + self.register_spatial_cache('cum_seqlen', cum_seqlen) + return cum_seqlen + + @property + def batch_boardcast_map(self) -> torch.LongTensor: + """ + Get the broadcast map for the varlen tensor. + """ + batch_boardcast_map = self.get_spatial_cache('batch_boardcast_map') + if batch_boardcast_map is None: + batch_boardcast_map = torch.repeat_interleave( + torch.arange(len(self.layout), device=self.device), + self.seqlen, + ) + self.register_spatial_cache('batch_boardcast_map', batch_boardcast_map) + return batch_boardcast_map + + @overload + def to(self, dtype: torch.dtype, *, non_blocking: bool = False, copy: bool = False) -> 'SparseTensor': ... + + @overload + def to(self, device: Optional[Union[str, torch.device]] = None, dtype: Optional[torch.dtype] = None, *, non_blocking: bool = False, copy: bool = False) -> 'SparseTensor': ... + + def to(self, *args, **kwargs) -> 'SparseTensor': + device = None + dtype = None + if len(args) == 2: + device, dtype = args + elif len(args) == 1: + if isinstance(args[0], torch.dtype): + dtype = args[0] + else: + device = args[0] + if 'dtype' in kwargs: + assert dtype is None, "to() received multiple values for argument 'dtype'" + dtype = kwargs['dtype'] + if 'device' in kwargs: + assert device is None, "to() received multiple values for argument 'device'" + device = kwargs['device'] + non_blocking = kwargs.get('non_blocking', False) + copy = kwargs.get('copy', False) + + new_feats = self.feats.to(device=device, dtype=dtype, non_blocking=non_blocking, copy=copy) + new_coords = self.coords.to(device=device, non_blocking=non_blocking, copy=copy) + return self.replace(new_feats, new_coords) + + def type(self, dtype): + new_feats = self.feats.type(dtype) + return self.replace(new_feats) + + def cpu(self) -> 'SparseTensor': + new_feats = self.feats.cpu() + new_coords = self.coords.cpu() + return self.replace(new_feats, new_coords) + + def cuda(self) -> 'SparseTensor': + new_feats = self.feats.cuda() + new_coords = self.coords.cuda() + return self.replace(new_feats, new_coords) + + def half(self) -> 'SparseTensor': + new_feats = self.feats.half() + return self.replace(new_feats) + + def float(self) -> 'SparseTensor': + new_feats = self.feats.float() + return self.replace(new_feats) + + def detach(self) -> 'SparseTensor': + new_coords = self.coords.detach() + new_feats = self.feats.detach() + return self.replace(new_feats, new_coords) + + def reshape(self, *shape) -> 'SparseTensor': + new_feats = self.feats.reshape(self.feats.shape[0], *shape) + return self.replace(new_feats) + + def unbind(self, dim: int) -> List['SparseTensor']: + return sparse_unbind(self, dim) + + def replace(self, feats: torch.Tensor, coords: Optional[torch.Tensor] = None) -> 'SparseTensor': + if config.CONV == 'torchsparse': + new_data = self.SparseTensorData( + feats=feats, + coords=self.data.coords if coords is None else coords, + stride=self.data.stride, + spatial_range=self.data.spatial_range, + ) + new_data._caches = self.data._caches + elif config.CONV == 'spconv': + new_data = self.SparseTensorData( + self.data.features.reshape(self.data.features.shape[0], -1), + self.data.indices, + self.data.spatial_shape, + self.data.batch_size, + self.data.grid, + self.data.voxel_num, + self.data.indice_dict + ) + new_data._features = feats + new_data.benchmark = self.data.benchmark + new_data.benchmark_record = self.data.benchmark_record + new_data.thrust_allocator = self.data.thrust_allocator + new_data._timer = self.data._timer + new_data.force_algo = self.data.force_algo + new_data.int8_scale = self.data.int8_scale + if coords is not None: + new_data.indices = coords + else: + new_data = { + 'feats': feats, + 'coords': self.data['coords'] if coords is None else coords, + } + new_tensor = SparseTensor( + new_data, + shape=torch.Size([self._shape[0]] + list(feats.shape[1:])) if self._shape is not None else None, + scale=self._scale, + spatial_cache=self._spatial_cache + ) + return new_tensor + + def to_dense(self) -> torch.Tensor: + if config.CONV == 'torchsparse': + return self.data.dense() + elif config.CONV == 'spconv': + return self.data.dense() + else: + spatial_shape = self.spatial_shape + ret = torch.zeros(*self.shape, *spatial_shape, dtype=self.dtype, device=self.device) + idx = [self.coords[:, 0], slice(None)] + self.coords[:, 1:].unbind(1) + ret[tuple(idx)] = self.feats + return ret + + @staticmethod + def full(aabb, dim, value, dtype=torch.float32, device=None) -> 'SparseTensor': + N, C = dim + x = torch.arange(aabb[0], aabb[3] + 1) + y = torch.arange(aabb[1], aabb[4] + 1) + z = torch.arange(aabb[2], aabb[5] + 1) + coords = torch.stack(torch.meshgrid(x, y, z, indexing='ij'), dim=-1).reshape(-1, 3) + coords = torch.cat([ + torch.arange(N).view(-1, 1).repeat(1, coords.shape[0]).view(-1, 1), + coords.repeat(N, 1), + ], dim=1).to(dtype=torch.int32, device=device) + feats = torch.full((coords.shape[0], C), value, dtype=dtype, device=device) + return SparseTensor(feats=feats, coords=coords) + + def __merge_sparse_cache(self, other: 'SparseTensor') -> dict: + new_cache = {} + for k in set(list(self._spatial_cache.keys()) + list(other._spatial_cache.keys())): + if k in self._spatial_cache: + new_cache[k] = self._spatial_cache[k] + if k in other._spatial_cache: + if k not in new_cache: + new_cache[k] = other._spatial_cache[k] + else: + new_cache[k].update(other._spatial_cache[k]) + return new_cache + + def __elemwise__(self, other: Union[torch.Tensor, VarLenTensor], op: callable) -> 'SparseTensor': + if isinstance(other, torch.Tensor): + try: + other = torch.broadcast_to(other, self.shape) + other = other[self.batch_boardcast_map] + except: + pass + if isinstance(other, VarLenTensor): + other = other.feats + new_feats = op(self.feats, other) + new_tensor = self.replace(new_feats) + if isinstance(other, SparseTensor): + new_tensor._spatial_cache = self.__merge_sparse_cache(other) + return new_tensor + + def __getitem__(self, idx): + if isinstance(idx, int): + idx = [idx] + elif isinstance(idx, slice): + idx = range(*idx.indices(self.shape[0])) + elif isinstance(idx, list): + assert all(isinstance(i, int) for i in idx), f"Only integer indices are supported: {idx}" + elif isinstance(idx, torch.Tensor): + if idx.dtype == torch.bool: + assert idx.shape == (self.shape[0],), f"Invalid index shape: {idx.shape}" + idx = idx.nonzero().squeeze(1) + elif idx.dtype in [torch.int32, torch.int64]: + assert len(idx.shape) == 1, f"Invalid index shape: {idx.shape}" + else: + raise ValueError(f"Unknown index type: {idx.dtype}") + else: + raise ValueError(f"Unknown index type: {type(idx)}") + + new_coords = [] + new_feats = [] + new_layout = [] + new_shape = torch.Size([len(idx)] + list(self.shape[1:])) + start = 0 + for new_idx, old_idx in enumerate(idx): + new_coords.append(self.coords[self.layout[old_idx]].clone()) + new_coords[-1][:, 0] = new_idx + new_feats.append(self.feats[self.layout[old_idx]]) + new_layout.append(slice(start, start + len(new_coords[-1]))) + start += len(new_coords[-1]) + new_coords = torch.cat(new_coords, dim=0).contiguous() + new_feats = torch.cat(new_feats, dim=0).contiguous() + new_tensor = SparseTensor(feats=new_feats, coords=new_coords, shape=new_shape) + new_tensor.register_spatial_cache('layout', new_layout) + return new_tensor + + def clear_spatial_cache(self) -> None: + """ + Clear all spatial caches. + """ + self._spatial_cache = {} + + def register_spatial_cache(self, key, value) -> None: + """ + Register a spatial cache. + The spatial cache can be any thing you want to cache. + The registery and retrieval of the cache is based on current scale. + """ + scale_key = str(self._scale) + if scale_key not in self._spatial_cache: + self._spatial_cache[scale_key] = {} + self._spatial_cache[scale_key][key] = value + + def get_spatial_cache(self, key=None): + """ + Get a spatial cache. + """ + scale_key = str(self._scale) + cur_scale_cache = self._spatial_cache.get(scale_key, {}) + if key is None: + return cur_scale_cache + return cur_scale_cache.get(key, None) + + def __repr__(self) -> str: + return f"SparseTensor(shape={self.shape}, dtype={self.dtype}, device={self.device})" + +def sparse_cat(inputs: List[SparseTensor], dim: int = 0) -> SparseTensor: + """ + Concatenate a list of sparse tensors. + + Args: + inputs (List[SparseTensor]): List of sparse tensors to concatenate. + """ + if dim == 0: + start = 0 + coords = [] + for input in inputs: + coords.append(input.coords.clone()) + coords[-1][:, 0] += start + start += input.shape[0] + coords = torch.cat(coords, dim=0) + feats = torch.cat([input.feats for input in inputs], dim=0) + output = SparseTensor( + coords=coords, + feats=feats, + ) + else: + feats = torch.cat([input.feats for input in inputs], dim=dim) + output = inputs[0].replace(feats) + + return output + + +def sparse_unbind(input: SparseTensor, dim: int) -> List[SparseTensor]: + """ + Unbind a sparse tensor along a dimension. + + Args: + input (SparseTensor): Sparse tensor to unbind. + dim (int): Dimension to unbind. + """ + if dim == 0: + return [input[i] for i in range(input.shape[0])] + else: + feats = input.feats.unbind(dim) + return [input.replace(f) for f in feats] diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/config.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f4d532316efcf989ab70b9b5218ba962bafe07 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/config.py @@ -0,0 +1,43 @@ +from typing import * + +CONV = 'flex_gemm' +DEBUG = False +ATTN = 'flash_attn' + +def __from_env(): + import os + + global CONV + global DEBUG + global ATTN + + env_sparse_conv_backend = os.environ.get('SPARSE_CONV_BACKEND') + env_sparse_debug = os.environ.get('SPARSE_DEBUG') + env_sparse_attn_backend = os.environ.get('SPARSE_ATTN_BACKEND') + if env_sparse_attn_backend is None: + env_sparse_attn_backend = os.environ.get('ATTN_BACKEND') + + if env_sparse_conv_backend is not None and env_sparse_conv_backend in ['none', 'spconv', 'torchsparse', 'flex_gemm']: + CONV = env_sparse_conv_backend + if env_sparse_debug is not None: + DEBUG = env_sparse_debug == '1' + if env_sparse_attn_backend is not None and env_sparse_attn_backend in ['xformers', 'flash_attn', 'flash_attn_3']: + ATTN = env_sparse_attn_backend + + print(f"[SPARSE] Conv backend: {CONV}; Attention backend: {ATTN}") + + +__from_env() + + +def set_conv_backend(backend: Literal['none', 'spconv', 'torchsparse', 'flex_gemm']): + global CONV + CONV = backend + +def set_debug(debug: bool): + global DEBUG + DEBUG = debug + +def set_attn_backend(backend: Literal['xformers', 'flash_attn']): + global ATTN + ATTN = backend diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f5911f2cb266f93e52cfcdea9f63f39be172c6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/__init__.py @@ -0,0 +1,2 @@ +from .conv import SparseConv3d, SparseInverseConv3d +from . import config diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/config.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/config.py new file mode 100644 index 0000000000000000000000000000000000000000..ac0848906703e7811300235e32d14e50ad5aac51 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/config.py @@ -0,0 +1,3 @@ +SPCONV_ALGO = 'auto' # 'auto', 'implicit_gemm', 'native' +FLEX_GEMM_ALGO = 'masked_implicit_gemm_splitk' # 'explicit_gemm', 'implicit_gemm', 'implicit_gemm_splitk', 'masked_implicit_gemm', 'masked_implicit_gemm_splitk' +FLEX_GEMM_HASHMAP_RATIO = 2.0 # Ratio of hashmap size to input size diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7d40707a24e26ba2a11a90c41dbc9eb11e7ab2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv.py @@ -0,0 +1,30 @@ +from .. import config +import importlib +import torch +import torch.nn as nn +from .. import SparseTensor + + +_backends = {} + + +class SparseConv3d(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, padding=None, bias=True, indice_key=None): + super(SparseConv3d, self).__init__() + if config.CONV not in _backends: + _backends[config.CONV] = importlib.import_module(f'..conv_{config.CONV}', __name__) + _backends[config.CONV].sparse_conv3d_init(self, in_channels, out_channels, kernel_size, stride, dilation, padding, bias, indice_key) + + def forward(self, x: SparseTensor) -> SparseTensor: + return _backends[config.CONV].sparse_conv3d_forward(self, x) + + +class SparseInverseConv3d(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, indice_key=None): + super(SparseInverseConv3d, self).__init__() + if config.CONV not in _backends: + _backends[config.CONV] = importlib.import_module(f'..conv_{config.CONV}', __name__) + _backends[config.CONV].sparse_inverse_conv3d_init(self, in_channels, out_channels, kernel_size, stride, dilation, bias, indice_key) + + def forward(self, x: SparseTensor) -> SparseTensor: + return _backends[config.CONV].sparse_inverse_conv3d_forward(self, x) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_flex_gemm.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_flex_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..d25619475e4bf39307f97d47b3828b19c48cd7da --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_flex_gemm.py @@ -0,0 +1,68 @@ +import math +import torch +import torch.nn as nn +from .. import SparseTensor +from . import config +import flex_gemm +from flex_gemm.ops.spconv import sparse_submanifold_conv3d + + +def sparse_conv3d_init(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, padding=None, bias=True, indice_key=None): + assert stride == 1 and (padding is None), 'Currently flex_gemm implementation only support submanifold sparse convolution (stride=1, padding=None)' + + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = tuple(kernel_size) if isinstance(kernel_size, (list, tuple)) else (kernel_size, ) * 3 + self.stride = tuple(stride) if isinstance(stride, (list, tuple)) else (stride, ) * 3 + self.dilation = tuple(dilation) if isinstance(dilation, (list, tuple)) else (dilation, ) * 3 + + self.weight = nn.Parameter(torch.empty((out_channels, in_channels, *self.kernel_size))) + if bias: + self.bias = nn.Parameter(torch.empty(out_channels)) + else: + self.register_parameter("bias", None) + + # initialize parameters + torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) + if self.bias is not None: + fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight) + if fan_in != 0: + bound = 1 / math.sqrt(fan_in) + torch.nn.init.uniform_(self.bias, -bound, bound) + + # Permute weight (Co, Ci, Kd, Kh, Kw) -> (Co, Kd, Kh, Kw, Ci) + self.weight = nn.Parameter(self.weight.permute(0, 2, 3, 4, 1).contiguous()) + + +def sparse_conv3d_forward(self, x: SparseTensor) -> SparseTensor: + flex_gemm.ops.spconv.set_algorithm(config.FLEX_GEMM_ALGO) + flex_gemm.ops.spconv.set_hashmap_ratio(config.FLEX_GEMM_HASHMAP_RATIO) + + # check if neighbor map is already computed + Co, Kd, Kh, Kw, Ci = self.weight.shape + neighbor_cache_key = f'SubMConv3d_neighbor_cache_{Kw}x{Kh}x{Kd}_dilation{self.dilation}' + neighbor_cache = x.get_spatial_cache(neighbor_cache_key) + + out, neighbor_cache_ = sparse_submanifold_conv3d( + x.feats, + x.coords, + torch.Size([*x.shape, *x.spatial_shape]), + self.weight, + self.bias, + neighbor_cache, + self.dilation + ) + + if neighbor_cache is None: + x.register_spatial_cache(neighbor_cache_key, neighbor_cache_) + + out = x.replace(out) + return out + + +def sparse_inverse_conv3d_init(self, *args, **kwargs): + raise NotImplementedError('SparseInverseConv3d with flex_gemm is not implemented yet') + + +def sparse_inverse_conv3d_forward(self, x: SparseTensor) -> SparseTensor: + raise NotImplementedError('SparseInverseConv3d with flex_gemm is not implemented yet') diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_spconv.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_spconv.py new file mode 100644 index 0000000000000000000000000000000000000000..f709708d4f8ee3bb98930c68b28e7f3b897fc591 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_spconv.py @@ -0,0 +1,73 @@ +import torch +import torch.nn as nn +from .. import SparseTensor +from . import config +import spconv.pytorch as spconv + + +def sparse_conv3d_init(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, padding=None, bias=True, indice_key=None): + algo = None + if config.SPCONV_ALGO == 'native': + algo = spconv.ConvAlgo.Native + elif config.SPCONV_ALGO == 'implicit_gemm': + algo = spconv.ConvAlgo.MaskImplicitGemm + if stride == 1 and (padding is None): + self.conv = spconv.SubMConv3d(in_channels, out_channels, kernel_size, dilation=dilation, bias=bias, indice_key=indice_key, algo=algo) + else: + self.conv = spconv.SparseConv3d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, padding=padding, bias=bias, indice_key=indice_key, algo=algo) + self.stride = tuple(stride) if isinstance(stride, (list, tuple)) else (stride, stride, stride) + self.padding = padding + + +def sparse_conv3d_forward(self, x: SparseTensor) -> SparseTensor: + spatial_changed = any(s != 1 for s in self.stride) or (self.padding is not None) + new_data = self.conv(x.data) + new_shape = [x.shape[0], self.conv.out_channels] + new_layout = None if spatial_changed else x.layout + + if spatial_changed and (x.shape[0] != 1): + # spconv was non-1 stride will break the contiguous of the output tensor, sort by the coords + fwd = new_data.indices[:, 0].argsort() + bwd = torch.zeros_like(fwd).scatter_(0, fwd, torch.arange(fwd.shape[0], device=fwd.device)) + sorted_feats = new_data.features[fwd] + sorted_coords = new_data.indices[fwd] + unsorted_data = new_data + new_data = spconv.SparseConvTensor(sorted_feats, sorted_coords, unsorted_data.spatial_shape, unsorted_data.batch_size) # type: ignore + + out = SparseTensor( + new_data, shape=torch.Size(new_shape), layout=new_layout, + scale=tuple([s * stride for s, stride in zip(x._scale, self.stride)]), + spatial_cache=x._spatial_cache, + ) + + if spatial_changed and (x.shape[0] != 1): + out.register_spatial_cache(f'conv_{self.stride}_unsorted_data', unsorted_data) + out.register_spatial_cache(f'conv_{self.stride}_sort_bwd', bwd) + + return out + + +def sparse_inverse_conv3d_init(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, indice_key=None): + self.conv = spconv.SparseInverseConv3d(in_channels, out_channels, kernel_size, bias=bias, indice_key=indice_key) + self.stride = tuple(stride) if isinstance(stride, (list, tuple)) else (stride, stride, stride) + + +def sparse_inverse_conv3d_forward(self, x: SparseTensor) -> SparseTensor: + spatial_changed = any(s != 1 for s in self.stride) + if spatial_changed: + # recover the original spconv order + data = x.get_spatial_cache(f'conv_{self.stride}_unsorted_data') + bwd = x.get_spatial_cache(f'conv_{self.stride}_sort_bwd') + data = data.replace_feature(x.feats[bwd]) + else: + data = x.data + + new_data = self.conv(data) + new_shape = [x.shape[0], self.conv.out_channels] + new_layout = None if spatial_changed else x.layout + out = SparseTensor( + new_data, shape=torch.Size(new_shape), layout=new_layout, + scale=tuple([s // stride for s, stride in zip(x._scale, self.stride)]), + spatial_cache=x._spatial_cache, + ) + return out diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_torchsparse.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_torchsparse.py new file mode 100644 index 0000000000000000000000000000000000000000..5234bd15553aa8d71df280672475a898ffe56af7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/conv/conv_torchsparse.py @@ -0,0 +1,30 @@ +import torch +import torch.nn as nn +from .. import SparseTensor +import torchsparse + + +def sparse_conv3d_init(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, padding=None, bias=True, indice_key=None): + self.conv = torchsparse.nn.Conv3d(in_channels, out_channels, kernel_size, stride, 0, dilation, bias) + + +def sparse_conv3d_forward(self, x: SparseTensor) -> SparseTensor: + out = self.conv(x.data) + new_shape = [x.shape[0], self.conv.out_channels] + out = SparseTensor(out, shape=torch.Size(new_shape), layout=x.layout if all(s == 1 for s in self.conv.stride) else None) + out._spatial_cache = x._spatial_cache + out._scale = tuple([s * stride for s, stride in zip(x._scale, self.conv.stride)]) + return out + + +def sparse_inverse_conv3d_init(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, indice_key=None): + self.conv = torchsparse.nn.Conv3d(in_channels, out_channels, kernel_size, stride, 0, dilation, bias, transposed=True) + + +def sparse_inverse_conv3d_forward(self, x: SparseTensor) -> SparseTensor: + out = self.conv(x.data) + new_shape = [x.shape[0], self.conv.out_channels] + out = SparseTensor(out, shape=torch.Size(new_shape), layout=x.layout if all(s == 1 for s in self.conv.stride) else None) + out._spatial_cache = x._spatial_cache + out._scale = tuple([s / stride for s, stride in zip(x._scale, self.conv.stride)]) + return out diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/linear.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..44317709ab16b17fa0132fd48e48519ea0ef9ea9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/linear.py @@ -0,0 +1,15 @@ +import torch +import torch.nn as nn +from . import VarLenTensor + +__all__ = [ + 'SparseLinear' +] + + +class SparseLinear(nn.Linear): + def __init__(self, in_features, out_features, bias=True): + super(SparseLinear, self).__init__(in_features, out_features, bias) + + def forward(self, input: VarLenTensor) -> VarLenTensor: + return input.replace(super().forward(input.feats)) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/nonlinearity.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/nonlinearity.py new file mode 100644 index 0000000000000000000000000000000000000000..950e5c03c997905162e39fec701db49a2640700c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/nonlinearity.py @@ -0,0 +1,35 @@ +import torch +import torch.nn as nn +from . import VarLenTensor + +__all__ = [ + 'SparseReLU', + 'SparseSiLU', + 'SparseGELU', + 'SparseActivation' +] + + +class SparseReLU(nn.ReLU): + def forward(self, input: VarLenTensor) -> VarLenTensor: + return input.replace(super().forward(input.feats)) + + +class SparseSiLU(nn.SiLU): + def forward(self, input: VarLenTensor) -> VarLenTensor: + return input.replace(super().forward(input.feats)) + + +class SparseGELU(nn.GELU): + def forward(self, input: VarLenTensor) -> VarLenTensor: + return input.replace(super().forward(input.feats)) + + +class SparseActivation(nn.Module): + def __init__(self, activation: nn.Module): + super().__init__() + self.activation = activation + + def forward(self, input: VarLenTensor) -> VarLenTensor: + return input.replace(self.activation(input.feats)) + diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/norm.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..95711203f0adbae1c7ea845e2500a3823997d652 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/norm.py @@ -0,0 +1,64 @@ +import torch +import torch.nn as nn +from ..utils import manual_cast +from . import VarLenTensor +from . import config + +__all__ = [ + 'SparseGroupNorm', + 'SparseLayerNorm', + 'SparseGroupNorm32', + 'SparseLayerNorm32', +] + + +class SparseGroupNorm(nn.GroupNorm): + def __init__(self, num_groups, num_channels, eps=1e-5, affine=True): + super(SparseGroupNorm, self).__init__(num_groups, num_channels, eps, affine) + + def forward(self, input: VarLenTensor) -> VarLenTensor: + nfeats = torch.zeros_like(input.feats) + for k in range(input.shape[0]): + bfeats = input.feats[input.layout[k]] + bfeats = bfeats.permute(1, 0).reshape(1, input.shape[1], -1) + bfeats = super().forward(bfeats) + bfeats = bfeats.reshape(input.shape[1], -1).permute(1, 0) + nfeats[input.layout[k]] = bfeats + return input.replace(nfeats) + + +class SparseLayerNorm(nn.LayerNorm): + def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True): + super(SparseLayerNorm, self).__init__(normalized_shape, eps, elementwise_affine) + + def forward(self, input: VarLenTensor) -> VarLenTensor: + nfeats = torch.zeros_like(input.feats) + for k in range(input.shape[0]): + bfeats = input.feats[input.layout[k]] + bfeats = bfeats.permute(1, 0).reshape(1, input.shape[1], -1) + bfeats = super().forward(bfeats) + bfeats = bfeats.reshape(input.shape[1], -1).permute(1, 0) + nfeats[input.layout[k]] = bfeats + return input.replace(nfeats) + + +class SparseGroupNorm32(SparseGroupNorm): + """ + A GroupNorm layer that converts to float32 before the forward pass. + """ + def forward(self, x: VarLenTensor) -> VarLenTensor: + x_dtype = x.dtype + x = manual_cast(x, torch.float32) + o = super().forward(x) + return manual_cast(o, x_dtype) + + +class SparseLayerNorm32(SparseLayerNorm): + """ + A LayerNorm layer that converts to float32 before the forward pass. + """ + def forward(self, x: VarLenTensor) -> VarLenTensor: + x_dtype = x.dtype + x = manual_cast(x, torch.float32) + o = super().forward(x) + return manual_cast(o, x_dtype) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e27425f165d271fd16a2c6f7b7684d4a81202ebd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/__init__.py @@ -0,0 +1,2 @@ +from .basic import * +from .spatial2channel import * diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/basic.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..eaeb8afefd889d8a94812c579383e528b8b56699 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/basic.py @@ -0,0 +1,109 @@ +from typing import * +import torch +import torch.nn as nn +from .. import SparseTensor + +__all__ = [ + 'SparseDownsample', + 'SparseUpsample', +] + + +class SparseDownsample(nn.Module): + """ + Downsample a sparse tensor by a factor of `factor`. + Implemented as average pooling. + """ + def __init__(self, factor: int, mode: Literal['mean', 'max'] = 'mean'): + super(SparseDownsample, self).__init__() + self.factor = factor + self.mode = mode + assert self.mode in ['mean', 'max'], f'Invalid mode: {self.mode}' + + def forward(self, x: SparseTensor) -> SparseTensor: + cache = x.get_spatial_cache(f'downsample_{self.factor}') + if cache is None: + DIM = x.coords.shape[-1] - 1 + + coord = list(x.coords.unbind(dim=-1)) + for i in range(DIM): + coord[i+1] = coord[i+1] // self.factor + + MAX = [(s + self.factor - 1) // self.factor for s in x.spatial_shape] + OFFSET = torch.cumprod(torch.tensor(MAX[::-1]), 0).tolist()[::-1] + [1] + code = sum([c * o for c, o in zip(coord, OFFSET)]) + code, idx = code.unique(return_inverse=True) + + new_coords = torch.stack( + [code // OFFSET[0]] + + [(code // OFFSET[i+1]) % MAX[i] for i in range(DIM)], + dim=-1 + ) + else: + new_coords, idx = cache + + new_feats = torch.scatter_reduce( + torch.zeros(new_coords.shape[0], x.feats.shape[1], device=x.feats.device, dtype=x.feats.dtype), + dim=0, + index=idx.unsqueeze(1).expand(-1, x.feats.shape[1]), + src=x.feats, + reduce=self.mode, + include_self=False, + ) + out = SparseTensor(new_feats, new_coords, x._shape) + out._scale = tuple([s * self.factor for s in x._scale]) + out._spatial_cache = x._spatial_cache + + if cache is None: + x.register_spatial_cache(f'downsample_{self.factor}', (new_coords, idx)) + out.register_spatial_cache(f'upsample_{self.factor}', (x.coords, idx)) + out.register_spatial_cache(f'shape', torch.Size(MAX)) + if self.training: + subidx = x.coords[:, 1:] % self.factor + subidx = sum([subidx[..., i] * self.factor ** i for i in range(DIM)]) + subdivision = torch.zeros((new_coords.shape[0], self.factor ** DIM), device=x.device, dtype=torch.bool) + subdivision[idx, subidx] = True + out.register_spatial_cache(f'subdivision', subdivision) + + return out + + +class SparseUpsample(nn.Module): + """ + Upsample a sparse tensor by a factor of `factor`. + Implemented as nearest neighbor interpolation. + """ + def __init__( + self, factor: int + ): + super(SparseUpsample, self).__init__() + self.factor = factor + + def forward(self, x: SparseTensor, subdivision: Optional[SparseTensor] = None) -> SparseTensor: + DIM = x.coords.shape[-1] - 1 + + cache = x.get_spatial_cache(f'upsample_{self.factor}') + if cache is None: + if subdivision is None: + raise ValueError('Cache not found. Provide subdivision tensor or pair SparseUpsample with SparseDownsample.') + else: + sub = subdivision.feats + N_leaf = sub.sum(dim=-1) + subidx = sub.nonzero()[:, -1] + new_coords = x.coords.clone().detach() + new_coords[:, 1:] *= self.factor + new_coords = torch.repeat_interleave(new_coords, N_leaf, dim=0, output_size=subidx.shape[0]) + for i in range(DIM): + new_coords[:, i+1] += subidx // self.factor ** i % self.factor + idx = torch.repeat_interleave(torch.arange(x.coords.shape[0], device=x.device), N_leaf, dim=0, output_size=subidx.shape[0]) + else: + new_coords, idx = cache + + new_feats = x.feats[idx] + out = SparseTensor(new_feats, new_coords, x._shape) + out._scale = tuple([s / self.factor for s in x._scale]) + if cache is not None: # only keep cache when subdiv following it + out._spatial_cache = x._spatial_cache + + return out + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/spatial2channel.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/spatial2channel.py new file mode 100644 index 0000000000000000000000000000000000000000..577f36d208726f64422f8774c3556a1d643f1e2d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/spatial/spatial2channel.py @@ -0,0 +1,93 @@ +from typing import * +import torch +import torch.nn as nn +from .. import SparseTensor + + +class SparseSpatial2Channel(nn.Module): + """ + Downsample a sparse tensor by a factor of `factor`. + Implemented as rearranging its features from spatial to channel. + """ + def __init__(self, factor: int = 2): + super(SparseSpatial2Channel, self).__init__() + self.factor = factor + + def forward(self, x: SparseTensor) -> SparseTensor: + DIM = x.coords.shape[-1] - 1 + cache = x.get_spatial_cache(f'spatial2channel_{self.factor}') + if cache is None: + coord = list(x.coords.unbind(dim=-1)) + for i in range(DIM): + coord[i+1] = coord[i+1] // self.factor + subidx = x.coords[:, 1:] % self.factor + subidx = sum([subidx[..., i] * self.factor ** i for i in range(DIM)]) + + MAX = [(s + self.factor - 1) // self.factor for s in x.spatial_shape] + OFFSET = torch.cumprod(torch.tensor(MAX[::-1]), 0).tolist()[::-1] + [1] + code = sum([c * o for c, o in zip(coord, OFFSET)]) + code, idx = code.unique(return_inverse=True) + + new_coords = torch.stack( + [code // OFFSET[0]] + + [(code // OFFSET[i+1]) % MAX[i] for i in range(DIM)], + dim=-1 + ) + else: + new_coords, idx, subidx = cache + + new_feats = torch.zeros(new_coords.shape[0] * self.factor ** DIM, x.feats.shape[1], device=x.feats.device, dtype=x.feats.dtype) + new_feats[idx * self.factor ** DIM + subidx] = x.feats + + out = SparseTensor(new_feats.reshape(new_coords.shape[0], -1), new_coords, None if x._shape is None else torch.Size([x._shape[0], x._shape[1] * self.factor ** DIM])) + out._scale = tuple([s * self.factor for s in x._scale]) + out._spatial_cache = x._spatial_cache + + if cache is None: + x.register_spatial_cache(f'spatial2channel_{self.factor}', (new_coords, idx, subidx)) + out.register_spatial_cache(f'channel2spatial_{self.factor}', (x.coords, idx, subidx)) + out.register_spatial_cache(f'shape', torch.Size(MAX)) + if self.training: + subdivision = torch.zeros((new_coords.shape[0], self.factor ** DIM), device=x.device, dtype=torch.bool) + subdivision[idx, subidx] = True + out.register_spatial_cache(f'subdivision', subdivision) + + return out + + +class SparseChannel2Spatial(nn.Module): + """ + Upsample a sparse tensor by a factor of `factor`. + Implemented as rearranging its features from channel to spatial. + """ + def __init__(self, factor: int = 2): + super(SparseChannel2Spatial, self).__init__() + self.factor = factor + + def forward(self, x: SparseTensor, subdivision: Optional[SparseTensor] = None) -> SparseTensor: + DIM = x.coords.shape[-1] - 1 + + cache = x.get_spatial_cache(f'channel2spatial_{self.factor}') + if cache is None: + if subdivision is None: + raise ValueError('Cache not found. Provide subdivision tensor or pair SparseChannel2Spatial with SparseSpatial2Channel.') + else: + sub = subdivision.feats # [N, self.factor ** DIM] + N_leaf = sub.sum(dim=-1) # [N] + subidx = sub.nonzero()[:, -1] + new_coords = x.coords.clone().detach() + new_coords[:, 1:] *= self.factor + new_coords = torch.repeat_interleave(new_coords, N_leaf, dim=0, output_size=subidx.shape[0]) + for i in range(DIM): + new_coords[:, i+1] += subidx // self.factor ** i % self.factor + idx = torch.repeat_interleave(torch.arange(x.coords.shape[0], device=x.device), N_leaf, dim=0, output_size=subidx.shape[0]) + else: + new_coords, idx, subidx = cache + + x_feats = x.feats.reshape(x.feats.shape[0] * self.factor ** DIM, -1) + new_feats = x_feats[idx * self.factor ** DIM + subidx] + out = SparseTensor(new_feats, new_coords, None if x._shape is None else torch.Size([x._shape[0], x._shape[1] // self.factor ** DIM])) + out._scale = tuple([s / self.factor for s in x._scale]) + if cache is not None: # only keep cache when subdiv following it + out._spatial_cache = x._spatial_cache + return out diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b08b0d4e5bc24060a2cdc8df75d06dce122972bd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/__init__.py @@ -0,0 +1,2 @@ +from .blocks import * +from .modulated import * \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/blocks.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1ec600404fba490894872109d44be6b6477186 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/blocks.py @@ -0,0 +1,145 @@ +from typing import * +import torch +import torch.nn as nn +from ..basic import VarLenTensor, SparseTensor +from ..linear import SparseLinear +from ..nonlinearity import SparseGELU +from ..attention import SparseMultiHeadAttention +from ...norm import LayerNorm32 + + +class SparseFeedForwardNet(nn.Module): + def __init__(self, channels: int, mlp_ratio: float = 4.0): + super().__init__() + self.mlp = nn.Sequential( + SparseLinear(channels, int(channels * mlp_ratio)), + SparseGELU(approximate="tanh"), + SparseLinear(int(channels * mlp_ratio), channels), + ) + + def forward(self, x: VarLenTensor) -> VarLenTensor: + return self.mlp(x) + + +class SparseTransformerBlock(nn.Module): + """ + Sparse Transformer block (MSA + FFN). + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "swin"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[int, int] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: SparseTensor) -> SparseTensor: + h = x.replace(self.norm1(x.feats)) + h = self.attn(h) + x = x + h + h = x.replace(self.norm2(x.feats)) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: SparseTensor) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseTransformerCrossBlock(nn.Module): + """ + Sparse Transformer cross-attention block (MSA + MCA + FFN). + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "swin"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.self_attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = SparseMultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: SparseTensor, context: Union[torch.Tensor, VarLenTensor]) -> SparseTensor: + h = x.replace(self.norm1(x.feats)) + h = self.self_attn(h) + x = x + h + h = x.replace(self.norm2(x.feats)) + h = self.cross_attn(h, context) + x = x + h + h = x.replace(self.norm3(x.feats)) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: SparseTensor, context: Union[torch.Tensor, VarLenTensor]) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, context, use_reentrant=False) + else: + return self._forward(x, context) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/modulated.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/modulated.py new file mode 100644 index 0000000000000000000000000000000000000000..e616932ef7714f0ec8ae3add655411971978eb54 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/sparse/transformer/modulated.py @@ -0,0 +1,166 @@ +from typing import * +import torch +import torch.nn as nn +from ..basic import VarLenTensor, SparseTensor +from ..attention import SparseMultiHeadAttention +from ...norm import LayerNorm32 +from .blocks import SparseFeedForwardNet + + +class ModulatedSparseTransformerBlock(nn.Module): + """ + Sparse Transformer block (MSA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "swin"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[float, float] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + else: + self.modulation = nn.Parameter(torch.randn(6 * channels) / channels ** 0.5) + + def _forward(self, x: SparseTensor, mod: torch.Tensor) -> SparseTensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.modulation + mod).type(mod.dtype).chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = x.replace(self.norm1(x.feats)) + h = h * (1 + scale_msa) + shift_msa + h = self.attn(h) + h = h * gate_msa + x = x + h + h = x.replace(self.norm2(x.feats)) + h = h * (1 + scale_mlp) + shift_mlp + h = self.mlp(h) + h = h * gate_mlp + x = x + h + return x + + def forward(self, x: SparseTensor, mod: torch.Tensor) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, use_reentrant=False) + else: + return self._forward(x, mod) + + +class ModulatedSparseTransformerCrossBlock(nn.Module): + """ + Sparse Transformer cross-attention block (MSA + MCA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "swin"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[float, float] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.self_attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = SparseMultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + else: + self.modulation = nn.Parameter(torch.randn(6 * channels) / channels ** 0.5) + + def _forward(self, x: SparseTensor, mod: torch.Tensor, context: Union[torch.Tensor, VarLenTensor]) -> SparseTensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.modulation + mod).type(mod.dtype).chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = x.replace(self.norm1(x.feats)) + h = h * (1 + scale_msa) + shift_msa + h = self.self_attn(h) + h = h * gate_msa + x = x + h + h = x.replace(self.norm2(x.feats)) + h = self.cross_attn(h, context) + x = x + h + h = x.replace(self.norm3(x.feats)) + h = h * (1 + scale_mlp) + shift_mlp + h = self.mlp(h) + h = h * gate_mlp + x = x + h + return x + + def forward(self, x: SparseTensor, mod: torch.Tensor, context: Union[torch.Tensor, VarLenTensor]) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, context, use_reentrant=False) + else: + return self._forward(x, mod, context) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/spatial.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/spatial.py new file mode 100644 index 0000000000000000000000000000000000000000..79e268d36c2ba49b0275744022a1a1e19983dae3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/spatial.py @@ -0,0 +1,48 @@ +import torch + + +def pixel_shuffle_3d(x: torch.Tensor, scale_factor: int) -> torch.Tensor: + """ + 3D pixel shuffle. + """ + B, C, H, W, D = x.shape + C_ = C // scale_factor**3 + x = x.reshape(B, C_, scale_factor, scale_factor, scale_factor, H, W, D) + x = x.permute(0, 1, 5, 2, 6, 3, 7, 4) + x = x.reshape(B, C_, H*scale_factor, W*scale_factor, D*scale_factor) + return x + + +def patchify(x: torch.Tensor, patch_size: int): + """ + Patchify a tensor. + + Args: + x (torch.Tensor): (N, C, *spatial) tensor + patch_size (int): Patch size + """ + DIM = x.dim() - 2 + for d in range(2, DIM + 2): + assert x.shape[d] % patch_size == 0, f"Dimension {d} of input tensor must be divisible by patch size, got {x.shape[d]} and {patch_size}" + + x = x.reshape(*x.shape[:2], *sum([[x.shape[d] // patch_size, patch_size] for d in range(2, DIM + 2)], [])) + x = x.permute(0, 1, *([2 * i + 3 for i in range(DIM)] + [2 * i + 2 for i in range(DIM)])) + x = x.reshape(x.shape[0], x.shape[1] * (patch_size ** DIM), *(x.shape[-DIM:])) + return x + + +def unpatchify(x: torch.Tensor, patch_size: int): + """ + Unpatchify a tensor. + + Args: + x (torch.Tensor): (N, C, *spatial) tensor + patch_size (int): Patch size + """ + DIM = x.dim() - 2 + assert x.shape[1] % (patch_size ** DIM) == 0, f"Second dimension of input tensor must be divisible by patch size to unpatchify, got {x.shape[1]} and {patch_size ** DIM}" + + x = x.reshape(x.shape[0], x.shape[1] // (patch_size ** DIM), *([patch_size] * DIM), *(x.shape[-DIM:])) + x = x.permute(0, 1, *(sum([[2 + DIM + i, 2 + i] for i in range(DIM)], []))) + x = x.reshape(x.shape[0], x.shape[1], *[x.shape[2 + 2 * i] * patch_size for i in range(DIM)]) + return x diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b08b0d4e5bc24060a2cdc8df75d06dce122972bd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/__init__.py @@ -0,0 +1,2 @@ +from .blocks import * +from .modulated import * \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/blocks.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..fb6f5eb5462fec62aa5edc062104f643fca03bfa --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/blocks.py @@ -0,0 +1,186 @@ +from typing import * +import torch +import torch.nn as nn +from ..attention import MultiHeadAttention +from ..norm import LayerNorm32 + + +class AbsolutePositionEmbedder(nn.Module): + """ + Embeds spatial positions into vector representations. + """ + def __init__(self, channels: int, in_channels: int = 3): + super().__init__() + self.channels = channels + self.in_channels = in_channels + self.freq_dim = channels // in_channels // 2 + self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim + self.freqs = 1.0 / (10000 ** self.freqs) + + def _sin_cos_embedding(self, x: torch.Tensor) -> torch.Tensor: + """ + Create sinusoidal position embeddings. + + Args: + x: a 1-D Tensor of N indices + + Returns: + an (N, D) Tensor of positional embeddings. + """ + self.freqs = self.freqs.to(x.device) + out = torch.outer(x, self.freqs) + out = torch.cat([torch.sin(out), torch.cos(out)], dim=-1) + return out + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x (torch.Tensor): (N, D) tensor of spatial positions + """ + N, D = x.shape + assert D == self.in_channels, "Input dimension must match number of input channels" + embed = self._sin_cos_embedding(x.reshape(-1)) + embed = embed.reshape(N, -1) + if embed.shape[1] < self.channels: + embed = torch.cat([embed, torch.zeros(N, self.channels - embed.shape[1], device=embed.device)], dim=-1) + return embed + + +class FeedForwardNet(nn.Module): + def __init__(self, channels: int, mlp_ratio: float = 4.0): + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(channels, int(channels * mlp_ratio)), + nn.GELU(approximate="tanh"), + nn.Linear(int(channels * mlp_ratio), channels), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.mlp(x) + + +class TransformerBlock(nn.Module): + """ + Transformer block (MSA + FFN). + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[int] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[int, int] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qkv_bias: bool = True, + ln_affine: bool = True, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.attn = MultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + h = self.norm1(x) + h = self.attn(h, phases=phases) + x = x + h + h = self.norm2(x) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, phases, use_reentrant=False) + else: + return self._forward(x, phases) + + +class TransformerCrossBlock(nn.Module): + """ + Transformer cross-attention block (MSA + MCA + FFN). + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[int, int] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.self_attn = MultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = MultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: torch.Tensor, context: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + h = self.norm1(x) + h = self.self_attn(h, phases=phases) + x = x + h + h = self.norm2(x) + h = self.cross_attn(h, context) + x = x + h + h = self.norm3(x) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: torch.Tensor, context: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, context, phases, use_reentrant=False) + else: + return self._forward(x, context, phases) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/modulated.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/modulated.py new file mode 100644 index 0000000000000000000000000000000000000000..0d71e584a4e137e88010023981271b2906efa30f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/transformer/modulated.py @@ -0,0 +1,165 @@ +from typing import * +import torch +import torch.nn as nn +from ..attention import MultiHeadAttention +from ..norm import LayerNorm32 +from .blocks import FeedForwardNet + + +class ModulatedTransformerBlock(nn.Module): + """ + Transformer block (MSA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[int, int] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.attn = MultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + else: + self.modulation = nn.Parameter(torch.randn(6 * channels) / channels ** 0.5) + + def _forward(self, x: torch.Tensor, mod: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.modulation + mod).type(mod.dtype).chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = self.norm1(x) + h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1) + h = self.attn(h, phases=phases) + h = h * gate_msa.unsqueeze(1) + x = x + h + h = self.norm2(x) + h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1) + h = self.mlp(h) + h = h * gate_mlp.unsqueeze(1) + x = x + h + return x + + def forward(self, x: torch.Tensor, mod: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, phases, use_reentrant=False) + else: + return self._forward(x, mod, phases) + + +class ModulatedTransformerCrossBlock(nn.Module): + """ + Transformer cross-attention block (MSA + MCA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + rope_freq: Tuple[int, int] = (1.0, 10000.0), + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.self_attn = MultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + rope_freq=rope_freq, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = MultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + else: + self.modulation = nn.Parameter(torch.randn(6 * channels) / channels ** 0.5) + + def _forward(self, x: torch.Tensor, mod: torch.Tensor, context: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.modulation + mod).type(mod.dtype).chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = self.norm1(x) + h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1) + h = self.self_attn(h, phases=phases) + h = h * gate_msa.unsqueeze(1) + x = x + h + h = self.norm2(x) + h = self.cross_attn(h, context) + x = x + h + h = self.norm3(x) + h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1) + h = self.mlp(h) + h = h * gate_mlp.unsqueeze(1) + x = x + h + return x + + def forward(self, x: torch.Tensor, mod: torch.Tensor, context: torch.Tensor, phases: Optional[torch.Tensor] = None) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, context, phases, use_reentrant=False) + else: + return self._forward(x, mod, context, phases) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5d92d7d5b0ab07972fb6e0397c9c8e525e196211 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/modules/utils.py @@ -0,0 +1,87 @@ +import torch +import torch.nn as nn +from ..modules import sparse as sp + +MIX_PRECISION_MODULES = ( + nn.Conv1d, + nn.Conv2d, + nn.Conv3d, + nn.ConvTranspose1d, + nn.ConvTranspose2d, + nn.ConvTranspose3d, + nn.Linear, + sp.SparseConv3d, + sp.SparseInverseConv3d, + sp.SparseLinear, +) + + +def convert_module_to_f16(l): + """ + Convert primitive modules to float16. + """ + if isinstance(l, MIX_PRECISION_MODULES): + for p in l.parameters(): + p.data = p.data.half() + + +def convert_module_to_f32(l): + """ + Convert primitive modules to float32, undoing convert_module_to_f16(). + """ + if isinstance(l, MIX_PRECISION_MODULES): + for p in l.parameters(): + p.data = p.data.float() + + +def convert_module_to(l, dtype): + """ + Convert primitive modules to the given dtype. + """ + if isinstance(l, MIX_PRECISION_MODULES): + for p in l.parameters(): + p.data = p.data.to(dtype) + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def scale_module(module, scale): + """ + Scale the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().mul_(scale) + return module + + +def modulate(x, shift, scale): + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + +def manual_cast(tensor, dtype): + """ + Cast if autocast is not enabled. + """ + if not torch.is_autocast_enabled(): + return tensor.type(dtype) + return tensor + + +def str_to_dtype(dtype_str: str): + return { + 'f16': torch.float16, + 'fp16': torch.float16, + 'float16': torch.float16, + 'bf16': torch.bfloat16, + 'bfloat16': torch.bfloat16, + 'f32': torch.float32, + 'fp32': torch.float32, + 'float32': torch.float32, + }[dtype_str] diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb68352304f064cf21feb22b2aa9e39b1db396d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/__init__.py @@ -0,0 +1,52 @@ +import importlib + +__attributes = { + "Trellis2ImageTo3DPipeline": "trellis2_image_to_3d", + "Trellis2TexturingPipeline": "trellis2_texturing", +} + +__submodules = ['samplers', 'rembg'] + +__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): + """ + Load a pipeline from a model folder or a Hugging Face model hub. + + Args: + path: The path to the model. Can be either local path or a Hugging Face model name. + """ + import os + import json + is_local = os.path.exists(f"{path}/pipeline.json") + + if is_local: + config_file = f"{path}/pipeline.json" + else: + from huggingface_hub import hf_hub_download + config_file = hf_hub_download(path, "pipeline.json") + + with open(config_file, 'r') as f: + config = json.load(f) + return globals()[config['name']].from_pretrained(path) + + +# For PyLance +if __name__ == '__main__': + from . import samplers, rembg + from .trellis2_image_to_3d import Trellis2ImageTo3DPipeline + from .trellis2_texturing import Trellis2TexturingPipeline diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/base.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/base.py new file mode 100644 index 0000000000000000000000000000000000000000..331e1ed979b47b23ef1d45c8851658df5d49fb69 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/base.py @@ -0,0 +1,72 @@ +from typing import * +import torch +import torch.nn as nn +from .. import models + + +class Pipeline: + """ + A base class for pipelines. + """ + def __init__( + self, + models: dict[str, nn.Module] = None, + ): + if models is None: + return + self.models = models + for model in self.models.values(): + model.eval() + + @classmethod + def from_pretrained(cls, path: str, config_file: str = "pipeline.json") -> "Pipeline": + """ + Load a pretrained model. + """ + import os + import json + is_local = os.path.exists(f"{path}/{config_file}") + + if is_local: + config_file = f"{path}/{config_file}" + else: + from huggingface_hub import hf_hub_download + config_file = hf_hub_download(path, config_file) + + with open(config_file, 'r') as f: + args = json.load(f)['args'] + + _models = {} + for k, v in args['models'].items(): + if hasattr(cls, 'model_names_to_load') and k not in cls.model_names_to_load: + continue + try: + _models[k] = models.from_pretrained(f"{path}/{v}") + except Exception as e: + _models[k] = models.from_pretrained(v) + + new_pipeline = cls(_models) + new_pipeline._pretrained_args = args + return new_pipeline + + @property + def device(self) -> torch.device: + if hasattr(self, '_device'): + return self._device + for model in self.models.values(): + if hasattr(model, 'device'): + return model.device + for model in self.models.values(): + if hasattr(model, 'parameters'): + return next(model.parameters()).device + raise RuntimeError("No device found.") + + def to(self, device: torch.device) -> None: + for model in self.models.values(): + model.to(device) + + def cuda(self) -> None: + self.to(torch.device("cuda")) + + def cpu(self) -> None: + self.to(torch.device("cpu")) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/rembg/BiRefNet.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/rembg/BiRefNet.py new file mode 100644 index 0000000000000000000000000000000000000000..c71a99274823aefe6f18ab921a5beb074177de18 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/rembg/BiRefNet.py @@ -0,0 +1,42 @@ +from typing import * +from transformers import AutoModelForImageSegmentation +import torch +from torchvision import transforms +from PIL import Image + + +class BiRefNet: + def __init__(self, model_name: str = "ZhengPeng7/BiRefNet"): + self.model = AutoModelForImageSegmentation.from_pretrained( + model_name, trust_remote_code=True + ) + self.model.eval() + self.transform_image = transforms.Compose( + [ + transforms.Resize((1024, 1024)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ] + ) + + def to(self, device: str): + self.model.to(device) + + def cuda(self): + self.model.cuda() + + def cpu(self): + self.model.cpu() + + def __call__(self, image: Image.Image) -> Image.Image: + image_size = image.size + input_images = self.transform_image(image).unsqueeze(0).to("cuda") + # Prediction + with torch.no_grad(): + preds = self.model(input_images)[-1].sigmoid().cpu() + pred = preds[0].squeeze() + pred_pil = transforms.ToPILImage()(pred) + mask = pred_pil.resize(image_size) + image.putalpha(mask) + return image + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/rembg/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/rembg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1eed1ba0c962478fc48132432f2e649fe03411 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/rembg/__init__.py @@ -0,0 +1 @@ +from .BiRefNet import * diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a69b95e5963c6d3a837518ed9c3cf6972235d60 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/__init__.py @@ -0,0 +1,6 @@ +from .base import Sampler +from .flow_euler import ( + FlowEulerSampler, + FlowEulerCfgSampler, + FlowEulerGuidanceIntervalSampler, +) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/base.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1966ce787009a5ee0c1ed06dce491525ff1dbcbf --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/base.py @@ -0,0 +1,20 @@ +from typing import * +from abc import ABC, abstractmethod + + +class Sampler(ABC): + """ + A base class for samplers. + """ + + @abstractmethod + def sample( + self, + model, + **kwargs + ): + """ + Sample from a model. + """ + pass + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/classifier_free_guidance_mixin.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/classifier_free_guidance_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7a4da4c1324bed5319f89916b532a159471d84 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/classifier_free_guidance_mixin.py @@ -0,0 +1,29 @@ +from typing import * + + +class ClassifierFreeGuidanceSamplerMixin: + """ + A mixin class for samplers that apply classifier-free guidance. + """ + + def _inference_model(self, model, x_t, t, cond, neg_cond, guidance_strength, guidance_rescale=0.0, **kwargs): + if guidance_strength == 1: + return super()._inference_model(model, x_t, t, cond, **kwargs) + elif guidance_strength == 0: + return super()._inference_model(model, x_t, t, neg_cond, **kwargs) + else: + pred_pos = super()._inference_model(model, x_t, t, cond, **kwargs) + pred_neg = super()._inference_model(model, x_t, t, neg_cond, **kwargs) + pred = guidance_strength * pred_pos + (1 - guidance_strength) * pred_neg + + # CFG rescale + if guidance_rescale > 0: + x_0_pos = self._pred_to_xstart(x_t, t, pred_pos) + x_0_cfg = self._pred_to_xstart(x_t, t, pred) + std_pos = x_0_pos.std(dim=list(range(1, x_0_pos.ndim)), keepdim=True) + std_cfg = x_0_cfg.std(dim=list(range(1, x_0_cfg.ndim)), keepdim=True) + x_0_rescaled = x_0_cfg * (std_pos / std_cfg) + x_0 = guidance_rescale * x_0_rescaled + (1 - guidance_rescale) * x_0_cfg + pred = self._xstart_to_pred(x_t, t, x_0) + + return pred diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/flow_euler.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/flow_euler.py new file mode 100644 index 0000000000000000000000000000000000000000..5ff72b84221f210f6cb06684bdf13aedc6cf20c3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/flow_euler.py @@ -0,0 +1,208 @@ +from typing import * +import torch +import numpy as np +from tqdm import tqdm +from easydict import EasyDict as edict +from .base import Sampler +from .classifier_free_guidance_mixin import ClassifierFreeGuidanceSamplerMixin +from .guidance_interval_mixin import GuidanceIntervalSamplerMixin + + +class FlowEulerSampler(Sampler): + """ + Generate samples from a flow-matching model using Euler sampling. + + Args: + sigma_min: The minimum scale of noise in flow. + """ + def __init__( + self, + sigma_min: float, + ): + self.sigma_min = sigma_min + + def _eps_to_xstart(self, x_t, t, eps): + assert x_t.shape == eps.shape + return (x_t - (self.sigma_min + (1 - self.sigma_min) * t) * eps) / (1 - t) + + def _xstart_to_eps(self, x_t, t, x_0): + assert x_t.shape == x_0.shape + return (x_t - (1 - t) * x_0) / (self.sigma_min + (1 - self.sigma_min) * t) + + def _v_to_xstart_eps(self, x_t, t, v): + assert x_t.shape == v.shape + eps = (1 - t) * v + x_t + x_0 = (1 - self.sigma_min) * x_t - (self.sigma_min + (1 - self.sigma_min) * t) * v + return x_0, eps + + def _pred_to_xstart(self, x_t, t, pred): + return (1 - self.sigma_min) * x_t - (self.sigma_min + (1 - self.sigma_min) * t) * pred + + def _xstart_to_pred(self, x_t, t, x_0): + return ((1 - self.sigma_min) * x_t - x_0) / (self.sigma_min + (1 - self.sigma_min) * t) + + def _inference_model(self, model, x_t, t, cond=None, **kwargs): + t = torch.tensor([1000 * t] * x_t.shape[0], device=x_t.device, dtype=torch.float32) + return model(x_t, t, cond, **kwargs) + + def _get_model_prediction(self, model, x_t, t, cond=None, **kwargs): + pred_v = self._inference_model(model, x_t, t, cond, **kwargs) + pred_x_0, pred_eps = self._v_to_xstart_eps(x_t=x_t, t=t, v=pred_v) + return pred_x_0, pred_eps, pred_v + + @torch.no_grad() + def sample_once( + self, + model, + x_t, + t: float, + t_prev: float, + cond: Optional[Any] = None, + **kwargs + ): + """ + Sample x_{t-1} from the model using Euler method. + + Args: + model: The model to sample from. + x_t: The [N x C x ...] tensor of noisy inputs at time t. + t: The current timestep. + t_prev: The previous timestep. + cond: conditional information. + **kwargs: Additional arguments for model inference. + + Returns: + a dict containing the following + - 'pred_x_prev': x_{t-1}. + - 'pred_x_0': a prediction of x_0. + """ + pred_x_0, pred_eps, pred_v = self._get_model_prediction(model, x_t, t, cond, **kwargs) + pred_x_prev = x_t - (t - t_prev) * pred_v + return edict({"pred_x_prev": pred_x_prev, "pred_x_0": pred_x_0}) + + @torch.no_grad() + def sample( + self, + model, + noise, + cond: Optional[Any] = None, + steps: int = 50, + rescale_t: float = 1.0, + verbose: bool = True, + tqdm_desc: str = "Sampling", + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + verbose: If True, show a progress bar. + tqdm_desc: A customized tqdm desc. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + sample = noise + t_seq = np.linspace(1, 0, steps + 1) + t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq) + t_seq = t_seq.tolist() + t_pairs = list((t_seq[i], t_seq[i + 1]) for i in range(steps)) + ret = edict({"samples": None, "pred_x_t": [], "pred_x_0": []}) + for t, t_prev in tqdm(t_pairs, desc=tqdm_desc, disable=not verbose): + out = self.sample_once(model, sample, t, t_prev, cond, **kwargs) + sample = out.pred_x_prev + ret.pred_x_t.append(out.pred_x_prev) + ret.pred_x_0.append(out.pred_x_0) + ret.samples = sample + return ret + + +class FlowEulerCfgSampler(ClassifierFreeGuidanceSamplerMixin, FlowEulerSampler): + """ + Generate samples from a flow-matching model using Euler sampling with classifier-free guidance. + """ + @torch.no_grad() + def sample( + self, + model, + noise, + cond, + neg_cond, + steps: int = 50, + rescale_t: float = 1.0, + guidance_strength: float = 3.0, + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + neg_cond: negative conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + guidance_strength: The strength of classifier-free guidance. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + return super().sample(model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, guidance_strength=guidance_strength, **kwargs) + + +class FlowEulerGuidanceIntervalSampler(GuidanceIntervalSamplerMixin, ClassifierFreeGuidanceSamplerMixin, FlowEulerSampler): + """ + Generate samples from a flow-matching model using Euler sampling with classifier-free guidance and interval. + """ + @torch.no_grad() + def sample( + self, + model, + noise, + cond, + neg_cond, + steps: int = 50, + rescale_t: float = 1.0, + guidance_strength: float = 3.0, + guidance_interval: Tuple[float, float] = (0.0, 1.0), + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + neg_cond: negative conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + guidance_strength: The strength of classifier-free guidance. + guidance_interval: The interval for classifier-free guidance. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + return super().sample(model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, guidance_strength=guidance_strength, guidance_interval=guidance_interval, **kwargs) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/guidance_interval_mixin.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/guidance_interval_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..3f57869a17d1626f5b2c58eb3c477127bf464abf --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/samplers/guidance_interval_mixin.py @@ -0,0 +1,13 @@ +from typing import * + + +class GuidanceIntervalSamplerMixin: + """ + A mixin class for samplers that apply classifier-free guidance with interval. + """ + + def _inference_model(self, model, x_t, t, cond, guidance_strength, guidance_interval, **kwargs): + if guidance_interval[0] <= t <= guidance_interval[1]: + return super()._inference_model(model, x_t, t, cond, guidance_strength=guidance_strength, **kwargs) + else: + return super()._inference_model(model, x_t, t, cond, guidance_strength=1, **kwargs) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/trellis2_image_to_3d.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/trellis2_image_to_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..a7b84b988f996875d895432c27848dfa0ad08a6c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/trellis2_image_to_3d.py @@ -0,0 +1,595 @@ +from typing import * +import torch +import torch.nn as nn +import numpy as np +from PIL import Image +from .base import Pipeline +from . import samplers, rembg +from ..modules.sparse import SparseTensor +from ..modules import image_feature_extractor +from ..representations import Mesh, MeshWithVoxel + + +class Trellis2ImageTo3DPipeline(Pipeline): + """ + Pipeline for inferring Trellis2 image-to-3D models. + + Args: + models (dict[str, nn.Module]): The models to use in the pipeline. + sparse_structure_sampler (samplers.Sampler): The sampler for the sparse structure. + shape_slat_sampler (samplers.Sampler): The sampler for the structured latent. + tex_slat_sampler (samplers.Sampler): The sampler for the texture latent. + sparse_structure_sampler_params (dict): The parameters for the sparse structure sampler. + shape_slat_sampler_params (dict): The parameters for the structured latent sampler. + tex_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. + """ + model_names_to_load = [ + 'sparse_structure_flow_model', + 'sparse_structure_decoder', + 'shape_slat_flow_model_512', + 'shape_slat_flow_model_1024', + 'shape_slat_decoder', + 'tex_slat_flow_model_512', + 'tex_slat_flow_model_1024', + 'tex_slat_decoder', + ] + + def __init__( + self, + models: dict[str, nn.Module] = None, + sparse_structure_sampler: samplers.Sampler = None, + shape_slat_sampler: samplers.Sampler = None, + tex_slat_sampler: samplers.Sampler = None, + sparse_structure_sampler_params: dict = None, + shape_slat_sampler_params: dict = None, + tex_slat_sampler_params: dict = None, + shape_slat_normalization: dict = None, + tex_slat_normalization: dict = None, + image_cond_model: Callable = None, + rembg_model: Callable = None, + low_vram: bool = True, + default_pipeline_type: str = '1024_cascade', + ): + if models is None: + return + super().__init__(models) + self.sparse_structure_sampler = sparse_structure_sampler + self.shape_slat_sampler = shape_slat_sampler + self.tex_slat_sampler = tex_slat_sampler + self.sparse_structure_sampler_params = sparse_structure_sampler_params + self.shape_slat_sampler_params = shape_slat_sampler_params + self.tex_slat_sampler_params = tex_slat_sampler_params + self.shape_slat_normalization = shape_slat_normalization + self.tex_slat_normalization = tex_slat_normalization + self.image_cond_model = image_cond_model + self.rembg_model = rembg_model + self.low_vram = low_vram + self.default_pipeline_type = default_pipeline_type + self.pbr_attr_layout = { + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + self._device = 'cpu' + + @classmethod + def from_pretrained(cls, path: str, config_file: str = "pipeline.json") -> "Trellis2ImageTo3DPipeline": + """ + Load a pretrained model. + + Args: + path (str): The path to the model. Can be either local path or a Hugging Face repository. + """ + pipeline = super().from_pretrained(path, config_file) + args = pipeline._pretrained_args + + pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args']) + pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params'] + + pipeline.shape_slat_sampler = getattr(samplers, args['shape_slat_sampler']['name'])(**args['shape_slat_sampler']['args']) + pipeline.shape_slat_sampler_params = args['shape_slat_sampler']['params'] + + pipeline.tex_slat_sampler = getattr(samplers, args['tex_slat_sampler']['name'])(**args['tex_slat_sampler']['args']) + pipeline.tex_slat_sampler_params = args['tex_slat_sampler']['params'] + + pipeline.shape_slat_normalization = args['shape_slat_normalization'] + pipeline.tex_slat_normalization = args['tex_slat_normalization'] + + pipeline.image_cond_model = getattr(image_feature_extractor, args['image_cond_model']['name'])(**args['image_cond_model']['args']) + pipeline.rembg_model = getattr(rembg, args['rembg_model']['name'])(**args['rembg_model']['args']) + + pipeline.low_vram = args.get('low_vram', True) + pipeline.default_pipeline_type = args.get('default_pipeline_type', '1024_cascade') + pipeline.pbr_attr_layout = { + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + pipeline._device = 'cpu' + + return pipeline + + def to(self, device: torch.device) -> None: + self._device = device + if not self.low_vram: + super().to(device) + self.image_cond_model.to(device) + if self.rembg_model is not None: + self.rembg_model.to(device) + + def preprocess_image(self, input: Image.Image) -> Image.Image: + """ + Preprocess the input image. + """ + # if has alpha channel, use it directly; otherwise, remove background + has_alpha = False + if input.mode == 'RGBA': + alpha = np.array(input)[:, :, 3] + if not np.all(alpha == 255): + has_alpha = True + max_size = max(input.size) + scale = min(1, 1024 / max_size) + if scale < 1: + input = input.resize((int(input.width * scale), int(input.height * scale)), Image.Resampling.LANCZOS) + if has_alpha: + output = input + else: + input = input.convert('RGB') + if self.low_vram: + self.rembg_model.to(self.device) + output = self.rembg_model(input) + if self.low_vram: + self.rembg_model.cpu() + output_np = np.array(output) + alpha = output_np[:, :, 3] + bbox = np.argwhere(alpha > 0.8 * 255) + bbox = np.min(bbox[:, 1]), np.min(bbox[:, 0]), np.max(bbox[:, 1]), np.max(bbox[:, 0]) + center = (bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2 + size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) + size = int(size * 1) + bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2 + output = output.crop(bbox) # type: ignore + output = np.array(output).astype(np.float32) / 255 + output = output[:, :, :3] * output[:, :, 3:4] + output = Image.fromarray((output * 255).astype(np.uint8)) + return output + + def get_cond(self, image: Union[torch.Tensor, list[Image.Image]], resolution: int, include_neg_cond: bool = True) -> dict: + """ + Get the conditioning information for the model. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image prompts. + + Returns: + dict: The conditioning information + """ + self.image_cond_model.image_size = resolution + if self.low_vram: + self.image_cond_model.to(self.device) + cond = self.image_cond_model(image) + if self.low_vram: + self.image_cond_model.cpu() + if not include_neg_cond: + return {'cond': cond} + neg_cond = torch.zeros_like(cond) + return { + 'cond': cond, + 'neg_cond': neg_cond, + } + + def sample_sparse_structure( + self, + cond: dict, + resolution: int, + num_samples: int = 1, + sampler_params: dict = {}, + ) -> torch.Tensor: + """ + Sample sparse structures with the given conditioning. + + Args: + cond (dict): The conditioning information. + resolution (int): The resolution of the sparse structure. + num_samples (int): The number of samples to generate. + sampler_params (dict): Additional parameters for the sampler. + """ + # Sample sparse structure latent + flow_model = self.models['sparse_structure_flow_model'] + reso = flow_model.resolution + in_channels = flow_model.in_channels + noise = torch.randn(num_samples, in_channels, reso, reso, reso).to(self.device) + sampler_params = {**self.sparse_structure_sampler_params, **sampler_params} + if self.low_vram: + flow_model.to(self.device) + z_s = self.sparse_structure_sampler.sample( + flow_model, + noise, + **cond, + **sampler_params, + verbose=True, + tqdm_desc="Sampling sparse structure", + ).samples + if self.low_vram: + flow_model.cpu() + + # Decode sparse structure latent + decoder = self.models['sparse_structure_decoder'] + if self.low_vram: + decoder.to(self.device) + decoded = decoder(z_s)>0 + if self.low_vram: + decoder.cpu() + if resolution != decoded.shape[2]: + ratio = decoded.shape[2] // resolution + decoded = torch.nn.functional.max_pool3d(decoded.float(), ratio, ratio, 0) > 0.5 + coords = torch.argwhere(decoded)[:, [0, 2, 3, 4]].int() + + return coords + + def sample_shape_slat( + self, + cond: dict, + flow_model, + coords: torch.Tensor, + sampler_params: dict = {}, + ) -> SparseTensor: + """ + Sample structured latent with the given conditioning. + + Args: + cond (dict): The conditioning information. + coords (torch.Tensor): The coordinates of the sparse structure. + sampler_params (dict): Additional parameters for the sampler. + """ + # Sample structured latent + noise = SparseTensor( + feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device), + coords=coords, + ) + sampler_params = {**self.shape_slat_sampler_params, **sampler_params} + if self.low_vram: + flow_model.to(self.device) + slat = self.shape_slat_sampler.sample( + flow_model, + noise, + **cond, + **sampler_params, + verbose=True, + tqdm_desc="Sampling shape SLat", + ).samples + if self.low_vram: + flow_model.cpu() + + std = torch.tensor(self.shape_slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.shape_slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + + return slat + + def sample_shape_slat_cascade( + self, + lr_cond: dict, + cond: dict, + flow_model_lr, + flow_model, + lr_resolution: int, + resolution: int, + coords: torch.Tensor, + sampler_params: dict = {}, + max_num_tokens: int = 49152, + ) -> SparseTensor: + """ + Sample structured latent with the given conditioning. + + Args: + cond (dict): The conditioning information. + coords (torch.Tensor): The coordinates of the sparse structure. + sampler_params (dict): Additional parameters for the sampler. + """ + # LR + noise = SparseTensor( + feats=torch.randn(coords.shape[0], flow_model_lr.in_channels).to(self.device), + coords=coords, + ) + sampler_params = {**self.shape_slat_sampler_params, **sampler_params} + if self.low_vram: + flow_model_lr.to(self.device) + slat = self.shape_slat_sampler.sample( + flow_model_lr, + noise, + **lr_cond, + **sampler_params, + verbose=True, + tqdm_desc="Sampling shape SLat", + ).samples + if self.low_vram: + flow_model_lr.cpu() + std = torch.tensor(self.shape_slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.shape_slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + + # Upsample + if self.low_vram: + self.models['shape_slat_decoder'].to(self.device) + self.models['shape_slat_decoder'].low_vram = True + hr_coords = self.models['shape_slat_decoder'].upsample(slat, upsample_times=4) + if self.low_vram: + self.models['shape_slat_decoder'].cpu() + self.models['shape_slat_decoder'].low_vram = False + hr_resolution = resolution + while True: + quant_coords = torch.cat([ + hr_coords[:, :1], + ((hr_coords[:, 1:] + 0.5) / lr_resolution * (hr_resolution // 16)).int(), + ], dim=1) + coords = quant_coords.unique(dim=0) + num_tokens = coords.shape[0] + if num_tokens < max_num_tokens or hr_resolution == 1024: + if hr_resolution != resolution: + print(f"Due to the limited number of tokens, the resolution is reduced to {hr_resolution}.") + break + hr_resolution -= 128 + + # Sample structured latent + noise = SparseTensor( + feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device), + coords=coords, + ) + sampler_params = {**self.shape_slat_sampler_params, **sampler_params} + if self.low_vram: + flow_model.to(self.device) + slat = self.shape_slat_sampler.sample( + flow_model, + noise, + **cond, + **sampler_params, + verbose=True, + tqdm_desc="Sampling shape SLat", + ).samples + if self.low_vram: + flow_model.cpu() + + std = torch.tensor(self.shape_slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.shape_slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + + return slat, hr_resolution + + def decode_shape_slat( + self, + slat: SparseTensor, + resolution: int, + ) -> Tuple[List[Mesh], List[SparseTensor]]: + """ + Decode the structured latent. + + Args: + slat (SparseTensor): The structured latent. + + Returns: + List[Mesh]: The decoded meshes. + List[SparseTensor]: The decoded substructures. + """ + self.models['shape_slat_decoder'].set_resolution(resolution) + if self.low_vram: + self.models['shape_slat_decoder'].to(self.device) + self.models['shape_slat_decoder'].low_vram = True + ret = self.models['shape_slat_decoder'](slat, return_subs=True) + if self.low_vram: + self.models['shape_slat_decoder'].cpu() + self.models['shape_slat_decoder'].low_vram = False + return ret + + def sample_tex_slat( + self, + 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 shape + sampler_params (dict): Additional parameters for the sampler. + """ + # Sample structured latent + std = torch.tensor(self.shape_slat_normalization['std'])[None].to(shape_slat.device) + mean = torch.tensor(self.shape_slat_normalization['mean'])[None].to(shape_slat.device) + shape_slat = (shape_slat - mean) / std + + in_channels = flow_model.in_channels if isinstance(flow_model, nn.Module) else flow_model[0].in_channels + noise = shape_slat.replace(feats=torch.randn(shape_slat.coords.shape[0], in_channels - shape_slat.feats.shape[1]).to(self.device)) + sampler_params = {**self.tex_slat_sampler_params, **sampler_params} + if self.low_vram: + flow_model.to(self.device) + slat = self.tex_slat_sampler.sample( + flow_model, + noise, + concat_cond=shape_slat, + **cond, + **sampler_params, + verbose=True, + tqdm_desc="Sampling texture SLat", + ).samples + if self.low_vram: + flow_model.cpu() + + std = torch.tensor(self.tex_slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.tex_slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + + return slat + + def decode_tex_slat( + self, + slat: SparseTensor, + subs: List[SparseTensor], + ) -> SparseTensor: + """ + Decode the structured latent. + + Args: + slat (SparseTensor): The structured latent. + + Returns: + SparseTensor: The decoded texture voxels + """ + if self.low_vram: + self.models['tex_slat_decoder'].to(self.device) + ret = self.models['tex_slat_decoder'](slat, guide_subs=subs) * 0.5 + 0.5 + if self.low_vram: + self.models['tex_slat_decoder'].cpu() + return ret + + @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) + tex_voxels = self.decode_tex_slat(tex_slat, subs) + out_mesh = [] + for m, v in zip(meshes, tex_voxels): + m.fill_holes() + out_mesh.append( + MeshWithVoxel( + m.vertices, m.faces, + origin = [-0.5, -0.5, -0.5], + voxel_size = 1 / resolution, + coords = v.coords[:, 1:], + attrs = v.feats, + voxel_shape = torch.Size([*v.shape, *v.spatial_shape]), + layout=self.pbr_attr_layout + ) + ) + return out_mesh + + @torch.no_grad() + def run( + self, + image: Image.Image, + num_samples: int = 1, + seed: int = 42, + sparse_structure_sampler_params: dict = {}, + shape_slat_sampler_params: dict = {}, + tex_slat_sampler_params: dict = {}, + preprocess_image: bool = True, + return_latent: bool = False, + pipeline_type: Optional[str] = None, + max_num_tokens: int = 49152, + ) -> List[MeshWithVoxel]: + """ + Run the pipeline. + + Args: + image (Image.Image): The image prompt. + num_samples (int): The number of samples to generate. + seed (int): The random seed. + sparse_structure_sampler_params (dict): Additional parameters for the sparse structure sampler. + shape_slat_sampler_params (dict): Additional parameters for the shape SLat sampler. + tex_slat_sampler_params (dict): Additional parameters for the texture SLat sampler. + preprocess_image (bool): Whether to preprocess the image. + return_latent (bool): Whether to return the latent codes. + pipeline_type (str): The type of the pipeline. Options: '512', '1024', '1024_cascade', '1536_cascade'. + max_num_tokens (int): The maximum number of tokens to use. + """ + # Check pipeline type + pipeline_type = pipeline_type or self.default_pipeline_type + if pipeline_type == '512': + assert 'shape_slat_flow_model_512' in self.models, "No 512 resolution shape SLat flow model found." + assert 'tex_slat_flow_model_512' in self.models, "No 512 resolution texture SLat flow model found." + elif pipeline_type == '1024': + assert 'shape_slat_flow_model_1024' in self.models, "No 1024 resolution shape SLat flow model found." + assert 'tex_slat_flow_model_1024' in self.models, "No 1024 resolution texture SLat flow model found." + elif pipeline_type == '1024_cascade': + assert 'shape_slat_flow_model_512' in self.models, "No 512 resolution shape SLat flow model found." + assert 'shape_slat_flow_model_1024' in self.models, "No 1024 resolution shape SLat flow model found." + assert 'tex_slat_flow_model_1024' in self.models, "No 1024 resolution texture SLat flow model found." + elif pipeline_type == '1536_cascade': + assert 'shape_slat_flow_model_512' in self.models, "No 512 resolution shape SLat flow model found." + assert 'shape_slat_flow_model_1024' in self.models, "No 1024 resolution shape SLat flow model found." + assert 'tex_slat_flow_model_1024' in self.models, "No 1024 resolution texture SLat flow model found." + else: + raise ValueError(f"Invalid pipeline type: {pipeline_type}") + + if preprocess_image: + image = self.preprocess_image(image) + torch.manual_seed(seed) + cond_512 = self.get_cond([image], 512) + cond_1024 = self.get_cond([image], 1024) if pipeline_type != '512' else None + ss_res = {'512': 32, '1024': 64, '1024_cascade': 32, '1536_cascade': 32}[pipeline_type] + coords = self.sample_sparse_structure( + cond_512, ss_res, + num_samples, sparse_structure_sampler_params + ) + if pipeline_type == '512': + shape_slat = self.sample_shape_slat( + cond_512, self.models['shape_slat_flow_model_512'], + coords, shape_slat_sampler_params + ) + tex_slat = self.sample_tex_slat( + cond_512, self.models['tex_slat_flow_model_512'], + shape_slat, tex_slat_sampler_params + ) + res = 512 + elif pipeline_type == '1024': + shape_slat = self.sample_shape_slat( + cond_1024, self.models['shape_slat_flow_model_1024'], + coords, shape_slat_sampler_params + ) + tex_slat = self.sample_tex_slat( + cond_1024, self.models['tex_slat_flow_model_1024'], + shape_slat, tex_slat_sampler_params + ) + res = 1024 + elif pipeline_type == '1024_cascade': + shape_slat, res = self.sample_shape_slat_cascade( + cond_512, cond_1024, + self.models['shape_slat_flow_model_512'], self.models['shape_slat_flow_model_1024'], + 512, 1024, + coords, shape_slat_sampler_params, + max_num_tokens + ) + tex_slat = self.sample_tex_slat( + cond_1024, self.models['tex_slat_flow_model_1024'], + shape_slat, tex_slat_sampler_params + ) + elif pipeline_type == '1536_cascade': + shape_slat, res = self.sample_shape_slat_cascade( + cond_512, cond_1024, + self.models['shape_slat_flow_model_512'], self.models['shape_slat_flow_model_1024'], + 512, 1536, + coords, shape_slat_sampler_params, + max_num_tokens + ) + tex_slat = self.sample_tex_slat( + cond_1024, self.models['tex_slat_flow_model_1024'], + shape_slat, tex_slat_sampler_params + ) + torch.cuda.empty_cache() + out_mesh = self.decode_latent(shape_slat, tex_slat, res) + if return_latent: + return out_mesh, (shape_slat, tex_slat, res) + else: + return out_mesh diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/trellis2_texturing.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/trellis2_texturing.py new file mode 100644 index 0000000000000000000000000000000000000000..c184b5e73ab49d5f29256e16ff900abc92be73be --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/pipelines/trellis2_texturing.py @@ -0,0 +1,408 @@ +from typing import * +import torch +import torch.nn as nn +import numpy as np +from PIL import Image +import trimesh +from .base import Pipeline +from . import samplers, rembg +from ..modules.sparse import SparseTensor +from ..modules import image_feature_extractor +import o_voxel +import cumesh +import nvdiffrast.torch as dr +import cv2 +import flex_gemm + + +class Trellis2TexturingPipeline(Pipeline): + """ + Pipeline for inferring Trellis2 image-to-3D models. + + Args: + models (dict[str, nn.Module]): The models to use in the pipeline. + tex_slat_sampler (samplers.Sampler): The sampler for the texture latent. + tex_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. + """ + model_names_to_load = [ + 'shape_slat_encoder', + 'tex_slat_decoder', + 'tex_slat_flow_model_512', + 'tex_slat_flow_model_1024' + ] + + def __init__( + self, + models: dict[str, nn.Module] = None, + tex_slat_sampler: samplers.Sampler = None, + tex_slat_sampler_params: dict = None, + shape_slat_normalization: dict = None, + tex_slat_normalization: dict = None, + image_cond_model: Callable = None, + rembg_model: Callable = None, + low_vram: bool = True, + ): + if models is None: + return + super().__init__(models) + self.tex_slat_sampler = tex_slat_sampler + self.tex_slat_sampler_params = tex_slat_sampler_params + self.shape_slat_normalization = shape_slat_normalization + self.tex_slat_normalization = tex_slat_normalization + self.image_cond_model = image_cond_model + self.rembg_model = rembg_model + self.low_vram = low_vram + self.pbr_attr_layout = { + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + self._device = 'cpu' + + @classmethod + def from_pretrained(cls, path: str, config_file: str = "pipeline.json") -> "Trellis2TexturingPipeline": + """ + Load a pretrained model. + + Args: + path (str): The path to the model. Can be either local path or a Hugging Face repository. + """ + pipeline = super().from_pretrained(path, config_file) + args = pipeline._pretrained_args + + pipeline.tex_slat_sampler = getattr(samplers, args['tex_slat_sampler']['name'])(**args['tex_slat_sampler']['args']) + pipeline.tex_slat_sampler_params = args['tex_slat_sampler']['params'] + + pipeline.shape_slat_normalization = args['shape_slat_normalization'] + pipeline.tex_slat_normalization = args['tex_slat_normalization'] + + pipeline.image_cond_model = getattr(image_feature_extractor, args['image_cond_model']['name'])(**args['image_cond_model']['args']) + pipeline.rembg_model = getattr(rembg, args['rembg_model']['name'])(**args['rembg_model']['args']) + + pipeline.low_vram = args.get('low_vram', True) + pipeline.pbr_attr_layout = { + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + pipeline._device = 'cpu' + return pipeline + + def to(self, device: torch.device) -> None: + self._device = device + if not self.low_vram: + super().to(device) + self.image_cond_model.to(device) + if self.rembg_model is not None: + self.rembg_model.to(device) + + def preprocess_mesh(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """ + Preprocess the input mesh. + """ + vertices = mesh.vertices + vertices_min = vertices.min(axis=0) + vertices_max = vertices.max(axis=0) + center = (vertices_min + vertices_max) / 2 + scale = 0.99999 / (vertices_max - vertices_min).max() + vertices = (vertices - center) * scale + tmp = vertices[:, 1].copy() + vertices[:, 1] = -vertices[:, 2] + vertices[:, 2] = tmp + assert np.all(vertices >= -0.5) and np.all(vertices <= 0.5), 'vertices out of range' + return trimesh.Trimesh(vertices=vertices, faces=mesh.faces, process=False) + + def preprocess_image(self, input: Image.Image) -> Image.Image: + """ + Preprocess the input image. + """ + # if has alpha channel, use it directly; otherwise, remove background + has_alpha = False + if input.mode == 'RGBA': + alpha = np.array(input)[:, :, 3] + if not np.all(alpha == 255): + has_alpha = True + max_size = max(input.size) + scale = min(1, 1024 / max_size) + if scale < 1: + input = input.resize((int(input.width * scale), int(input.height * scale)), Image.Resampling.LANCZOS) + if has_alpha: + output = input + else: + input = input.convert('RGB') + if self.low_vram: + self.rembg_model.to(self.device) + output = self.rembg_model(input) + if self.low_vram: + self.rembg_model.cpu() + output_np = np.array(output) + alpha = output_np[:, :, 3] + bbox = np.argwhere(alpha > 0.8 * 255) + bbox = np.min(bbox[:, 1]), np.min(bbox[:, 0]), np.max(bbox[:, 1]), np.max(bbox[:, 0]) + center = (bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2 + size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) + size = int(size * 1) + bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2 + output = output.crop(bbox) # type: ignore + output = np.array(output).astype(np.float32) / 255 + output = output[:, :, :3] * output[:, :, 3:4] + output = Image.fromarray((output * 255).astype(np.uint8)) + return output + + def get_cond(self, image: Union[torch.Tensor, list[Image.Image]], resolution: int, include_neg_cond: bool = True) -> dict: + """ + Get the conditioning information for the model. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image prompts. + + Returns: + dict: The conditioning information + """ + self.image_cond_model.image_size = resolution + if self.low_vram: + self.image_cond_model.to(self.device) + cond = self.image_cond_model(image) + if self.low_vram: + self.image_cond_model.cpu() + if not include_neg_cond: + return {'cond': cond} + neg_cond = torch.zeros_like(cond) + return { + 'cond': cond, + 'neg_cond': neg_cond, + } + + def encode_shape_slat( + self, + mesh: trimesh.Trimesh, + resolution: int = 1024, + ) -> SparseTensor: + """ + Encode the meshes to structured latent. + + Args: + mesh (trimesh.Trimesh): The mesh to encode. + resolution (int): The resolution of mesh + + Returns: + SparseTensor: The encoded structured latent. + """ + vertices = torch.from_numpy(mesh.vertices).float() + faces = torch.from_numpy(mesh.faces).long() + + voxel_indices, dual_vertices, intersected = o_voxel.convert.mesh_to_flexible_dual_grid( + vertices.cpu(), faces.cpu(), + grid_size=resolution, + aabb=[[-0.5,-0.5,-0.5],[0.5,0.5,0.5]], + face_weight=1.0, + boundary_weight=0.2, + regularization_weight=1e-2, + timing=True, + ) + + vertices = SparseTensor( + feats=dual_vertices * resolution - voxel_indices, + coords=torch.cat([torch.zeros_like(voxel_indices[:, 0:1]), voxel_indices], dim=-1) + ).to(self.device) + intersected = vertices.replace(intersected).to(self.device) + + if self.low_vram: + self.models['shape_slat_encoder'].to(self.device) + shape_slat = self.models['shape_slat_encoder'](vertices, intersected) + if self.low_vram: + self.models['shape_slat_encoder'].cpu() + return shape_slat + + def sample_tex_slat( + self, + 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 shape + sampler_params (dict): Additional parameters for the sampler. + """ + # Sample structured latent + std = torch.tensor(self.shape_slat_normalization['std'])[None].to(shape_slat.device) + mean = torch.tensor(self.shape_slat_normalization['mean'])[None].to(shape_slat.device) + shape_slat = (shape_slat - mean) / std + + in_channels = flow_model.in_channels if isinstance(flow_model, nn.Module) else flow_model[0].in_channels + noise = shape_slat.replace(feats=torch.randn(shape_slat.coords.shape[0], in_channels - shape_slat.feats.shape[1]).to(self.device)) + sampler_params = {**self.tex_slat_sampler_params, **sampler_params} + if self.low_vram: + flow_model.to(self.device) + slat = self.tex_slat_sampler.sample( + flow_model, + noise, + concat_cond=shape_slat, + **cond, + **sampler_params, + verbose=True, + tqdm_desc="Sampling texture SLat", + ).samples + if self.low_vram: + flow_model.cpu() + + std = torch.tensor(self.tex_slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.tex_slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + + return slat + + def decode_tex_slat( + self, + slat: SparseTensor, + ) -> SparseTensor: + """ + Decode the structured latent. + + Args: + slat (SparseTensor): The structured latent. + + Returns: + SparseTensor: The decoded texture voxels + """ + if self.low_vram: + self.models['tex_slat_decoder'].to(self.device) + ret = self.models['tex_slat_decoder'](slat) * 0.5 + 0.5 + if self.low_vram: + self.models['tex_slat_decoder'].cpu() + return ret + + def postprocess_mesh( + self, + mesh: trimesh.Trimesh, + pbr_voxel: SparseTensor, + resolution: int = 1024, + texture_size: int = 1024, + ) -> trimesh.Trimesh: + vertices = mesh.vertices + faces = mesh.faces + normals = mesh.vertex_normals + vertices_torch = torch.from_numpy(vertices).float().cuda() + faces_torch = torch.from_numpy(faces).int().cuda() + if hasattr(mesh, 'visual') and hasattr(mesh.visual, 'uv') and mesh.visual.uv is not None: + uvs = mesh.visual.uv.copy() + uvs[:, 1] = 1 - uvs[:, 1] + uvs_torch = torch.from_numpy(uvs).float().cuda() + else: + _cumesh = cumesh.CuMesh() + _cumesh.init(vertices_torch, faces_torch) + vertices_torch, faces_torch, uvs_torch, vmap = _cumesh.uv_unwrap(return_vmaps=True) + vertices_torch = vertices_torch.cuda() + faces_torch = faces_torch.cuda() + uvs_torch = uvs_torch.cuda() + vertices = vertices_torch.cpu().numpy() + faces = faces_torch.cpu().numpy() + uvs = uvs_torch.cpu().numpy() + normals = normals[vmap.cpu().numpy()] + + # rasterize + ctx = dr.RasterizeCudaContext() + uvs_torch = torch.cat([uvs_torch * 2 - 1, torch.zeros_like(uvs_torch[:, :1]), torch.ones_like(uvs_torch[:, :1])], dim=-1).unsqueeze(0) + rast, _ = dr.rasterize( + ctx, uvs_torch, faces_torch, + resolution=[texture_size, texture_size], + ) + mask = rast[0, ..., 3] > 0 + pos = dr.interpolate(vertices_torch.unsqueeze(0), rast, faces_torch)[0][0] + + attrs = torch.zeros(texture_size, texture_size, pbr_voxel.shape[1], device=self.device) + attrs[mask] = flex_gemm.ops.grid_sample.grid_sample_3d( + pbr_voxel.feats, + pbr_voxel.coords, + shape=torch.Size([*pbr_voxel.shape, *pbr_voxel.spatial_shape]), + grid=((pos[mask] + 0.5) * resolution).reshape(1, -1, 3), + mode='trilinear', + ) + + # construct mesh + mask = mask.cpu().numpy() + base_color = np.clip(attrs[..., self.pbr_attr_layout['base_color']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + metallic = np.clip(attrs[..., self.pbr_attr_layout['metallic']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + roughness = np.clip(attrs[..., self.pbr_attr_layout['roughness']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + alpha = np.clip(attrs[..., self.pbr_attr_layout['alpha']].cpu().numpy() * 255, 0, 255).astype(np.uint8) + + # extend + mask = (~mask).astype(np.uint8) + base_color = cv2.inpaint(base_color, mask, 3, cv2.INPAINT_TELEA) + metallic = cv2.inpaint(metallic, mask, 1, cv2.INPAINT_TELEA)[..., None] + roughness = cv2.inpaint(roughness, mask, 1, cv2.INPAINT_TELEA)[..., None] + alpha = cv2.inpaint(alpha, mask, 1, cv2.INPAINT_TELEA)[..., None] + + material = trimesh.visual.material.PBRMaterial( + baseColorTexture=Image.fromarray(np.concatenate([base_color, alpha], axis=-1)), + baseColorFactor=np.array([255, 255, 255, 255], dtype=np.uint8), + metallicRoughnessTexture=Image.fromarray(np.concatenate([np.zeros_like(metallic), roughness, metallic], axis=-1)), + metallicFactor=1.0, + roughnessFactor=1.0, + alphaMode='OPAQUE', + doubleSided=True, + ) + + # Swap Y and Z axes, invert Y (common conversion for GLB compatibility) + vertices[:, 1], vertices[:, 2] = vertices[:, 2], -vertices[:, 1] + normals[:, 1], normals[:, 2] = normals[:, 2], -normals[:, 1] + uvs[:, 1] = 1 - uvs[:, 1] # Flip UV V-coordinate + + textured_mesh = trimesh.Trimesh( + vertices=vertices, + faces=faces, + vertex_normals=normals, + process=False, + visual=trimesh.visual.TextureVisuals(uv=uvs, material=material) + ) + + return textured_mesh + + + @torch.no_grad() + def run( + self, + mesh: trimesh.Trimesh, + image: Image.Image, + seed: int = 42, + tex_slat_sampler_params: dict = {}, + preprocess_image: bool = True, + resolution: int = 1024, + texture_size: int = 2048, + ) -> trimesh.Trimesh: + """ + Run the pipeline. + + Args: + mesh (trimesh.Trimesh): The mesh to texture. + image (Image.Image): The image prompt. + seed (int): The random seed. + tex_slat_sampler_params (dict): Additional parameters for the texture latent sampler. + preprocess_image (bool): Whether to preprocess the image. + """ + if preprocess_image: + image = self.preprocess_image(image) + mesh = self.preprocess_mesh(mesh) + torch.manual_seed(seed) + cond = self.get_cond([image], 512) if resolution == 512 else self.get_cond([image], 1024) + shape_slat = self.encode_shape_slat(mesh, resolution) + tex_model = self.models['tex_slat_flow_model_512'] if resolution == 512 else self.models['tex_slat_flow_model_1024'] + tex_slat = self.sample_tex_slat( + cond, tex_model, + shape_slat, tex_slat_sampler_params + ) + pbr_voxel = self.decode_tex_slat(tex_slat) + out_mesh = self.postprocess_mesh(mesh, pbr_voxel, resolution, texture_size) + return out_mesh diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de3203d1bb16065f912bff039e431f609911782d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/__init__.py @@ -0,0 +1,33 @@ +import importlib + +__attributes = { + 'MeshRenderer': 'mesh_renderer', + 'VoxelRenderer': 'voxel_renderer', + 'PbrMeshRenderer': 'pbr_mesh_renderer', + 'EnvMap': 'pbr_mesh_renderer', +} + +__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] + + +# For Pylance +if __name__ == '__main__': + from .mesh_renderer import MeshRenderer + from .voxel_renderer import VoxelRenderer + from .pbr_mesh_renderer import PbrMeshRenderer, EnvMap + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/mesh_renderer.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/mesh_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..e20efc59c26fadcbd9c11cbafa2e31b78eec395c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/mesh_renderer.py @@ -0,0 +1,414 @@ +from typing import * +import torch +from easydict import EasyDict as edict +from ..representations.mesh import Mesh, MeshWithVoxel, MeshWithPbrMaterial, TextureFilterMode, AlphaMode, TextureWrapMode +import torch.nn.functional as F + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = (far + near) / (far - near) + ret[2, 3] = 2 * near * far / (near - far) + ret[3, 2] = 1. + return ret + + +class MeshRenderer: + """ + Renderer for the Mesh representation. + + Args: + rendering_options (dict): Rendering options. + """ + def __init__(self, rendering_options={}, device='cuda'): + if 'dr' not in globals(): + import nvdiffrast.torch as dr + + self.rendering_options = edict({ + "resolution": None, + "near": None, + "far": None, + "ssaa": 1, + "chunk_size": None, + "antialias": True, + "clamp_barycentric_coords": False, + }) + self.rendering_options.update(rendering_options) + self.glctx = dr.RasterizeCudaContext(device=device) + self.device=device + + def render( + self, + mesh : Mesh, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + return_types = ["mask", "normal", "depth"], + transformation : Optional[torch.Tensor] = None + ) -> edict: + """ + Render the mesh. + + Args: + mesh : meshmodel + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + return_types (list): list of return types, can be "attr", "mask", "depth", "coord", "normal" + + Returns: + edict based on return_types containing: + attr (torch.Tensor): [C, H, W] rendered attr image + depth (torch.Tensor): [H, W] rendered depth image + normal (torch.Tensor): [3, H, W] rendered normal image + mask (torch.Tensor): [H, W] rendered mask image + """ + if 'dr' not in globals(): + import nvdiffrast.torch as dr + + resolution = self.rendering_options["resolution"] + near = self.rendering_options["near"] + far = self.rendering_options["far"] + ssaa = self.rendering_options["ssaa"] + chunk_size = self.rendering_options["chunk_size"] + antialias = self.rendering_options["antialias"] + clamp_barycentric_coords = self.rendering_options["clamp_barycentric_coords"] + + if mesh.vertices.shape[0] == 0 or mesh.faces.shape[0] == 0: + ret_dict = edict() + for type in return_types: + if type == "mask" : + ret_dict[type] = torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device) + elif type == "depth": + ret_dict[type] = torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device) + elif type == "normal": + ret_dict[type] = torch.full((3, resolution, resolution), 0.5, dtype=torch.float32, device=self.device) + elif type == "coord": + ret_dict[type] = torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device) + elif type == "attr": + if isinstance(mesh, MeshWithVoxel): + ret_dict[type] = torch.zeros((mesh.attrs.shape[-1], resolution, resolution), dtype=torch.float32, device=self.device) + else: + ret_dict[type] = torch.zeros((mesh.vertex_attrs.shape[-1], resolution, resolution), dtype=torch.float32, device=self.device) + return ret_dict + + perspective = intrinsics_to_projection(intrinsics, near, far) + + full_proj = (perspective @ extrinsics).unsqueeze(0) + extrinsics = extrinsics.unsqueeze(0) + + vertices = mesh.vertices.unsqueeze(0) + vertices_homo = torch.cat([vertices, torch.ones_like(vertices[..., :1])], dim=-1) + if transformation is not None: + vertices_homo = torch.bmm(vertices_homo, transformation.unsqueeze(0).transpose(-1, -2)) + vertices = vertices_homo[..., :3].contiguous() + vertices_camera = torch.bmm(vertices_homo, extrinsics.transpose(-1, -2)) + vertices_clip = torch.bmm(vertices_homo, full_proj.transpose(-1, -2)) + faces = mesh.faces + + if 'normal' in return_types: + v0 = vertices_camera[0, mesh.faces[:, 0], :3] + v1 = vertices_camera[0, mesh.faces[:, 1], :3] + v2 = vertices_camera[0, mesh.faces[:, 2], :3] + e0 = v1 - v0 + e1 = v2 - v0 + face_normal = torch.cross(e0, e1, dim=1) + face_normal = F.normalize(face_normal, dim=1) + face_normal = torch.where(torch.sum(face_normal * v0, dim=1, keepdim=True) > 0, face_normal, -face_normal) + + out_dict = edict() + if chunk_size is None: + rast, rast_db = dr.rasterize( + self.glctx, vertices_clip, faces, (resolution * ssaa, resolution * ssaa) + ) + if clamp_barycentric_coords: + rast[..., :2] = torch.clamp(rast[..., :2], 0, 1) + rast[..., :2] /= torch.where(rast[..., :2].sum(dim=-1, keepdim=True) > 1, rast[..., :2].sum(dim=-1, keepdim=True), torch.ones_like(rast[..., :2])) + for type in return_types: + img = None + if type == "mask" : + img = (rast[..., -1:] > 0).float() + if antialias: img = dr.antialias(img, rast, vertices_clip, faces) + elif type == "depth": + img = dr.interpolate(vertices_camera[..., 2:3].contiguous(), rast, faces)[0] + if antialias: img = dr.antialias(img, rast, vertices_clip, faces) + elif type == "normal" : + img = dr.interpolate(face_normal.unsqueeze(0), rast, torch.arange(face_normal.shape[0], dtype=torch.int, device=self.device).unsqueeze(1).repeat(1, 3).contiguous())[0] + if antialias: img = dr.antialias(img, rast, vertices_clip, faces) + img = (img + 1) / 2 + elif type == "coord": + img = dr.interpolate(vertices, rast, faces)[0] + if antialias: img = dr.antialias(img, rast, vertices_clip, faces) + elif type == "attr": + if isinstance(mesh, MeshWithVoxel): + if 'grid_sample_3d' not in globals(): + from flex_gemm.ops.grid_sample import grid_sample_3d + mask = rast[..., -1:] > 0 + xyz = dr.interpolate(vertices, rast, faces)[0] + xyz = ((xyz - mesh.origin) / mesh.voxel_size).reshape(1, -1, 3) + img = grid_sample_3d( + mesh.attrs, + torch.cat([torch.zeros_like(mesh.coords[..., :1]), mesh.coords], dim=-1), + mesh.voxel_shape, + xyz, + mode='trilinear' + ) + img = img.reshape(1, resolution * ssaa, resolution * ssaa, mesh.attrs.shape[-1]) * mask + elif isinstance(mesh, MeshWithPbrMaterial): + tri_id = rast[0, :, :, -1:] + mask = tri_id > 0 + uv_coords = mesh.uv_coords.reshape(1, -1, 2) + texc, texd = dr.interpolate( + uv_coords, + rast, + torch.arange(mesh.uv_coords.shape[0] * 3, dtype=torch.int, device=self.device).reshape(-1, 3), + rast_db=rast_db, + diff_attrs='all' + ) + # Fix problematic texture coordinates + texc = torch.nan_to_num(texc, nan=0.0, posinf=1e3, neginf=-1e3) + texc = torch.clamp(texc, min=-1e3, max=1e3) + texd = torch.nan_to_num(texd, nan=0.0, posinf=1e3, neginf=-1e3) + texd = torch.clamp(texd, min=-1e3, max=1e3) + mid = mesh.material_ids[(tri_id - 1).long()] + imgs = { + 'base_color': torch.zeros((resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device), + 'metallic': torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device), + 'roughness': torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device), + 'alpha': torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + } + for id, mat in enumerate(mesh.materials): + mat_mask = (mid == id).float() * mask.float() + mat_texc = texc * mat_mask + mat_texd = texd * mat_mask + + if mat.base_color_texture is not None: + base_color = dr.texture( + mat.base_color_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.base_color_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.base_color_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + imgs['base_color'] += base_color * mat.base_color_factor * mat_mask + else: + imgs['base_color'] += mat.base_color_factor * mat_mask + + if mat.metallic_texture is not None: + metallic = dr.texture( + mat.metallic_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.metallic_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.metallic_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + imgs['metallic'] += metallic * mat.metallic_factor * mat_mask + else: + imgs['metallic'] += mat.metallic_factor * mat_mask + + if mat.roughness_texture is not None: + roughness = dr.texture( + mat.roughness_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.roughness_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.roughness_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + imgs['roughness'] += roughness * mat.roughness_factor * mat_mask + else: + imgs['roughness'] += mat.roughness_factor * mat_mask + + if mat.alpha_mode == AlphaMode.OPAQUE: + imgs['alpha'] += 1.0 * mat_mask + else: + if mat.alpha_texture is not None: + alpha = dr.texture( + mat.alpha_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.alpha_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.alpha_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + if mat.alpha_mode == AlphaMode.MASK: + imgs['alpha'] += (alpha * mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask + elif mat.alpha_mode == AlphaMode.BLEND: + imgs['alpha'] += alpha * mat.alpha_factor * mat_mask + else: + if mat.alpha_mode == AlphaMode.MASK: + imgs['alpha'] += (mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask + elif mat.alpha_mode == AlphaMode.BLEND: + imgs['alpha'] += mat.alpha_factor * mat_mask + + img = torch.cat([imgs[name] for name in imgs.keys()], dim=-1).unsqueeze(0) + else: + img = dr.interpolate(mesh.vertex_attrs.unsqueeze(0), rast, faces)[0] + if antialias: img = dr.antialias(img, rast, vertices_clip, faces) + + out_dict[type] = img + else: + z_buffer = torch.full((1, resolution * ssaa, resolution * ssaa), torch.inf, device=self.device, dtype=torch.float32) + for i in range(0, faces.shape[0], chunk_size): + faces_chunk = faces[i:i+chunk_size] + rast, rast_db = dr.rasterize( + self.glctx, vertices_clip, faces_chunk, (resolution * ssaa, resolution * ssaa) + ) + z_filter = torch.logical_and( + rast[..., 3] != 0, + rast[..., 2] < z_buffer + ) + z_buffer[z_filter] = rast[z_filter][..., 2] + + for type in return_types: + img = None + if type == "mask" : + img = (rast[..., -1:] > 0).float() + elif type == "depth": + img = dr.interpolate(vertices_camera[..., 2:3].contiguous(), rast, faces_chunk)[0] + elif type == "normal" : + face_normal_chunk = face_normal[i:i+chunk_size] + img = dr.interpolate(face_normal_chunk.unsqueeze(0), rast, torch.arange(face_normal_chunk.shape[0], dtype=torch.int, device=self.device).unsqueeze(1).repeat(1, 3).contiguous())[0] + img = (img + 1) / 2 + elif type == "coord": + img = dr.interpolate(vertices, rast, faces_chunk)[0] + elif type == "attr": + if isinstance(mesh, MeshWithVoxel): + if 'grid_sample_3d' not in globals(): + from flex_gemm.ops.grid_sample import grid_sample_3d + mask = rast[..., -1:] > 0 + xyz = dr.interpolate(vertices, rast, faces_chunk)[0] + xyz = ((xyz - mesh.origin) / mesh.voxel_size).reshape(1, -1, 3) + img = grid_sample_3d( + mesh.attrs, + torch.cat([torch.zeros_like(mesh.coords[..., :1]), mesh.coords], dim=-1), + mesh.voxel_shape, + xyz, + mode='trilinear' + ) + img = img.reshape(1, resolution * ssaa, resolution * ssaa, mesh.attrs.shape[-1]) * mask + elif isinstance(mesh, MeshWithPbrMaterial): + tri_id = rast[0, :, :, -1:] + mask = tri_id > 0 + uv_coords = mesh.uv_coords.reshape(1, -1, 2) + texc, texd = dr.interpolate( + uv_coords, + rast, + torch.arange(mesh.uv_coords.shape[0] * 3, dtype=torch.int, device=self.device).reshape(-1, 3), + rast_db=rast_db, + diff_attrs='all' + ) + # Fix problematic texture coordinates + texc = torch.nan_to_num(texc, nan=0.0, posinf=1e3, neginf=-1e3) + texc = torch.clamp(texc, min=-1e3, max=1e3) + texd = torch.nan_to_num(texd, nan=0.0, posinf=1e3, neginf=-1e3) + texd = torch.clamp(texd, min=-1e3, max=1e3) + mid = mesh.material_ids[(tri_id - 1).long()] + imgs = { + 'base_color': torch.zeros((resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device), + 'metallic': torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device), + 'roughness': torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device), + 'alpha': torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + } + for id, mat in enumerate(mesh.materials): + mat_mask = (mid == id).float() * mask.float() + mat_texc = texc * mat_mask + mat_texd = texd * mat_mask + + if mat.base_color_texture is not None: + base_color = dr.texture( + mat.base_color_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.base_color_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.base_color_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + imgs['base_color'] += base_color * mat.base_color_factor * mat_mask + else: + imgs['base_color'] += mat.base_color_factor * mat_mask + + if mat.metallic_texture is not None: + metallic = dr.texture( + mat.metallic_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.metallic_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.metallic_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + imgs['metallic'] += metallic * mat.metallic_factor * mat_mask + else: + imgs['metallic'] += mat.metallic_factor * mat_mask + + if mat.roughness_texture is not None: + roughness = dr.texture( + mat.roughness_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.roughness_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.roughness_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + imgs['roughness'] += roughness * mat.roughness_factor * mat_mask + else: + imgs['roughness'] += mat.roughness_factor * mat_mask + + if mat.alpha_mode == AlphaMode.OPAQUE: + imgs['alpha'] += 1.0 * mat_mask + else: + if mat.alpha_texture is not None: + alpha = dr.texture( + mat.alpha_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.alpha_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.alpha_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + if mat.alpha_mode == AlphaMode.MASK: + imgs['alpha'] += (alpha * mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask + elif mat.alpha_mode == AlphaMode.BLEND: + imgs['alpha'] += alpha * mat.alpha_factor * mat_mask + else: + if mat.alpha_mode == AlphaMode.MASK: + imgs['alpha'] += (mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask + elif mat.alpha_mode == AlphaMode.BLEND: + imgs['alpha'] += mat.alpha_factor * mat_mask + + img = torch.cat([imgs[name] for name in imgs.keys()], dim=-1).unsqueeze(0) + else: + img = dr.interpolate(mesh.vertex_attrs.unsqueeze(0), rast, faces_chunk)[0] + + if type not in out_dict: + out_dict[type] = img + else: + out_dict[type][z_filter] = img[z_filter] + + for type in return_types: + img = out_dict[type] + if ssaa > 1: + img = F.interpolate(img.permute(0, 3, 1, 2), (resolution, resolution), mode='bilinear', align_corners=False, antialias=True) + img = img.squeeze() + else: + img = img.permute(0, 3, 1, 2).squeeze() + out_dict[type] = img + + if isinstance(mesh, (MeshWithVoxel, MeshWithPbrMaterial)) and 'attr' in return_types: + for k, s in mesh.layout.items(): + out_dict[k] = out_dict['attr'][s] + del out_dict['attr'] + + return out_dict diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/pbr_mesh_renderer.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/pbr_mesh_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b465532cb15ec69c651a3814cd9b42dfb3171e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/pbr_mesh_renderer.py @@ -0,0 +1,490 @@ +from typing import * +import torch +from easydict import EasyDict as edict +import numpy as np +import utils3d +from ..representations.mesh import Mesh, MeshWithVoxel, MeshWithPbrMaterial, TextureFilterMode, AlphaMode, TextureWrapMode +import torch.nn.functional as F + + +def cube_to_dir(s, x, y): + if s == 0: rx, ry, rz = torch.ones_like(x), -x, -y + elif s == 1: rx, ry, rz = -torch.ones_like(x), x, -y + elif s == 2: rx, ry, rz = x, y, torch.ones_like(x) + elif s == 3: rx, ry, rz = x, -y, -torch.ones_like(x) + elif s == 4: rx, ry, rz = x, torch.ones_like(x), -y + elif s == 5: rx, ry, rz = -x, -torch.ones_like(x), -y + return torch.stack((rx, ry, rz), dim=-1) + + +def latlong_to_cubemap(latlong_map, res): + if 'dr' not in globals(): + import nvdiffrast.torch as dr + cubemap = torch.zeros(6, res[0], res[1], latlong_map.shape[-1], dtype=torch.float32, device='cuda') + for s in range(6): + gy, gx = torch.meshgrid(torch.linspace(-1.0 + 1.0 / res[0], 1.0 - 1.0 / res[0], res[0], device='cuda'), + torch.linspace(-1.0 + 1.0 / res[1], 1.0 - 1.0 / res[1], res[1], device='cuda'), + indexing='ij') + v = F.normalize(cube_to_dir(s, gx, gy), dim=-1) + + tu = torch.atan2(v[..., 0:1], -v[..., 2:3]) / (2 * np.pi) + 0.5 + tv = torch.acos(torch.clamp(v[..., 1:2], min=-1, max=1)) / np.pi + texcoord = torch.cat((tu, tv), dim=-1) + + cubemap[s, ...] = dr.texture(latlong_map[None, ...], texcoord[None, ...], filter_mode='linear')[0] + return cubemap + + +class EnvMap: + def __init__(self, image: torch.Tensor): + self.image = image + + @property + def _backend(self): + if not hasattr(self, '_nvdiffrec_envlight'): + if 'EnvironmentLight' not in globals(): + from nvdiffrec_render.light import EnvironmentLight + cubemap = latlong_to_cubemap(self.image, [512, 512]) + self._nvdiffrec_envlight = EnvironmentLight(cubemap) + self._nvdiffrec_envlight.build_mips() + return self._nvdiffrec_envlight + + def shade(self, gb_pos, gb_normal, kd, ks, view_pos, specular=True): + return self._backend.shade(gb_pos, gb_normal, kd, ks, view_pos, specular) + + def sample(self, directions: torch.Tensor): + if 'dr' not in globals(): + import nvdiffrast.torch as dr + return dr.texture( + self._backend.base.unsqueeze(0), + directions.unsqueeze(0), + boundary_mode='cube', + )[0] + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = (far + near) / (far - near) + ret[2, 3] = 2 * near * far / (near - far) + ret[3, 2] = 1. + return ret + + +def screen_space_ambient_occlusion( + depth: torch.Tensor, + normal: torch.Tensor, + perspective: torch.Tensor, + radius: float = 0.1, + bias: float = 1e-6, + samples: int = 64, + intensity: float = 1.0, +) -> torch.Tensor: + """ + Screen space ambient occlusion (SSAO) + + Args: + depth (torch.Tensor): [H, W, 1] depth image + normal (torch.Tensor): [H, W, 3] normal image + perspective (torch.Tensor): [4, 4] camera projection matrix + radius (float): radius of the SSAO kernel + bias (float): bias to avoid self-occlusion + samples (int): number of samples to use for the SSAO kernel + intensity (float): intensity of the SSAO effect + Returns: + (torch.Tensor): [H, W, 1] SSAO image + """ + device = depth.device + H, W, _ = depth.shape + + fx = perspective[0, 0] + fy = perspective[1, 1] + cx = perspective[0, 2] + cy = perspective[1, 2] + + y_grid, x_grid = torch.meshgrid( + (torch.arange(H, device=device) + 0.5) / H * 2 - 1, + (torch.arange(W, device=device) + 0.5) / W * 2 - 1, + indexing='ij' + ) + x_view = (x_grid.float() - cx) * depth[..., 0] / fx + y_view = (y_grid.float() - cy) * depth[..., 0] / fy + view_pos = torch.stack([x_view, y_view, depth[..., 0]], dim=-1) # [H, W, 3] + + depth_feat = depth.permute(2, 0, 1).unsqueeze(0) + occlusion = torch.zeros((H, W), device=device) + + # start sampling + for _ in range(samples): + # sample normal distribution, if inside, flip the sign + rnd_vec = torch.randn(H, W, 3, device=device) + rnd_vec = F.normalize(rnd_vec, p=2, dim=-1) + dot_val = torch.sum(rnd_vec * normal, dim=-1, keepdim=True) + sample_dir = torch.sign(dot_val) * rnd_vec + scale = torch.rand(H, W, 1, device=device) + scale = scale * scale + sample_pos = view_pos + sample_dir * radius * scale + sample_z = sample_pos[..., 2] + + # project to screen space + z_safe = torch.clamp(sample_pos[..., 2], min=1e-5) + proj_u = (sample_pos[..., 0] * fx / z_safe) + cx + proj_v = (sample_pos[..., 1] * fy / z_safe) + cy + grid = torch.stack([proj_u, proj_v], dim=-1).unsqueeze(0) + geo_z = F.grid_sample(depth_feat, grid, mode='nearest', padding_mode='border').squeeze() + range_check = torch.abs(geo_z - sample_z) < radius + is_occluded = (geo_z <= sample_z - bias) & range_check + occlusion += is_occluded.float() + + f_occ = occlusion / samples * intensity + f_occ = torch.clamp(f_occ, 0.0, 1.0) + + return f_occ.unsqueeze(-1) + + +def aces_tonemapping(x: torch.Tensor) -> torch.Tensor: + """ + Applies ACES tone mapping curve to an HDR image tensor. + Input: x - HDR tensor, shape (..., 3), range [0, +inf) + Output: LDR tensor, same shape, range [0, 1] + """ + a = 2.51 + b = 0.03 + c = 2.43 + d = 0.59 + e = 0.14 + + # Apply the ACES fitted curve + mapped = (x * (a * x + b)) / (x * (c * x + d) + e) + + # Clamp to [0, 1] for display or saving + return torch.clamp(mapped, 0.0, 1.0) + + +def gamma_correction(x: torch.Tensor, gamma: float = 2.2) -> torch.Tensor: + """ + Applies gamma correction to an HDR image tensor. + """ + return torch.clamp(x ** (1.0 / gamma), 0.0, 1.0) + + +class PbrMeshRenderer: + """ + Renderer for the PBR mesh. + + Args: + rendering_options (dict): Rendering options. + """ + def __init__(self, rendering_options={}, device='cuda'): + if 'dr' not in globals(): + import nvdiffrast.torch as dr + + self.rendering_options = edict({ + "resolution": None, + "near": None, + "far": None, + "ssaa": 1, + "peel_layers": 8, + }) + self.rendering_options.update(rendering_options) + self.glctx = dr.RasterizeCudaContext(device=device) + self.device=device + + def render( + self, + mesh : Mesh, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + envmap : Union[EnvMap, Dict[str, EnvMap]], + use_envmap_bg : bool = False, + transformation : Optional[torch.Tensor] = None + ) -> edict: + """ + Render the mesh. + + Args: + mesh : meshmodel + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + envmap (Union[EnvMap, Dict[str, EnvMap]]): environment map or a dictionary of environment maps + use_envmap_bg (bool): whether to use envmap as background + transformation (torch.Tensor): (4, 4) transformation matrix + + Returns: + edict based on return_types containing: + shaded (torch.Tensor): [3, H, W] shaded color image + normal (torch.Tensor): [3, H, W] normal image + base_color (torch.Tensor): [3, H, W] base color image + metallic (torch.Tensor): [H, W] metallic image + roughness (torch.Tensor): [H, W] roughness image + """ + if 'dr' not in globals(): + import nvdiffrast.torch as dr + + if not isinstance(envmap, dict): + envmap = {'' : envmap} + num_envmaps = len(envmap) + + resolution = self.rendering_options["resolution"] + near = self.rendering_options["near"] + far = self.rendering_options["far"] + ssaa = self.rendering_options["ssaa"] + + if mesh.vertices.shape[0] == 0 or mesh.faces.shape[0] == 0: + out_dict = edict( + normal=torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device), + mask=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device), + base_color=torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device), + metallic=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device), + roughness=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device), + alpha=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device), + clay=torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device), + ) + for i, k in enumerate(envmap.keys()): + shaded_key = f"shaded_{k}" if k != '' else "shaded" + out_dict[shaded_key] = torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device) + return out_dict + + rays_o, rays_d = utils3d.torch.get_image_rays( + extrinsics, intrinsics, resolution * ssaa, resolution * ssaa + ) + + perspective = intrinsics_to_projection(intrinsics, near, far) + + full_proj = (perspective @ extrinsics).unsqueeze(0) + extrinsics = extrinsics.unsqueeze(0) + + vertices = mesh.vertices.unsqueeze(0) + vertices_orig = vertices.clone() + vertices_homo = torch.cat([vertices, torch.ones_like(vertices[..., :1])], dim=-1) + if transformation is not None: + vertices_homo = torch.bmm(vertices_homo, transformation.unsqueeze(0).transpose(-1, -2)) + vertices = vertices_homo[..., :3].contiguous() + vertices_camera = torch.bmm(vertices_homo, extrinsics.transpose(-1, -2)) + vertices_clip = torch.bmm(vertices_homo, full_proj.transpose(-1, -2)) + faces = mesh.faces + + v0 = vertices[0, mesh.faces[:, 0], :3] + v1 = vertices[0, mesh.faces[:, 1], :3] + v2 = vertices[0, mesh.faces[:, 2], :3] + e0 = v1 - v0 + e1 = v2 - v0 + face_normal = torch.cross(e0, e1, dim=1) + face_normal = F.normalize(face_normal, dim=1) + + out_dict = edict() + shaded = torch.zeros((num_envmaps, resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device) + depth = torch.full((resolution * ssaa, resolution * ssaa, 1), 1e10, dtype=torch.float32, device=self.device) + normal = torch.zeros((resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device) + max_w = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + alpha = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + with dr.DepthPeeler(self.glctx, vertices_clip, faces, (resolution * ssaa, resolution * ssaa)) as peeler: + for _ in range(self.rendering_options["peel_layers"]): + rast, rast_db = peeler.rasterize_next_layer() + + # Pos + pos = dr.interpolate(vertices, rast, faces)[0][0] + + # Depth + gb_depth = dr.interpolate(vertices_camera[..., 2:3].contiguous(), rast, faces)[0][0] + + # Normal + gb_normal = dr.interpolate(face_normal.unsqueeze(0), rast, torch.arange(face_normal.shape[0], dtype=torch.int, device=self.device).unsqueeze(1).repeat(1, 3).contiguous())[0][0] + gb_normal = torch.where( + torch.sum(gb_normal * (pos - rays_o), dim=-1, keepdim=True) > 0, + -gb_normal, + gb_normal + ) + gb_cam_normal = (extrinsics[..., :3, :3].reshape(1, 1, 3, 3) @ gb_normal.unsqueeze(-1)).squeeze(-1) + if _ == 0: + out_dict.normal = -gb_cam_normal * 0.5 + 0.5 + mask = (rast[0, ..., -1:] > 0).float() + out_dict.mask = mask + + # PBR attributes + if isinstance(mesh, MeshWithVoxel): + if 'grid_sample_3d' not in globals(): + from flex_gemm.ops.grid_sample import grid_sample_3d + mask = rast[..., -1:] > 0 + xyz = dr.interpolate(vertices_orig, rast, faces)[0] + xyz = ((xyz - mesh.origin) / mesh.voxel_size).reshape(1, -1, 3) + img = grid_sample_3d( + mesh.attrs, + torch.cat([torch.zeros_like(mesh.coords[..., :1]), mesh.coords], dim=-1), + mesh.voxel_shape, + xyz, + mode='trilinear' + ) + img = img.reshape(1, resolution * ssaa, resolution * ssaa, mesh.attrs.shape[-1]) * mask + gb_basecolor = img[0, ..., mesh.layout['base_color']] + gb_metallic = img[0, ..., mesh.layout['metallic']] + gb_roughness = img[0, ..., mesh.layout['roughness']] + gb_alpha = img[0, ..., mesh.layout['alpha']] + elif isinstance(mesh, MeshWithPbrMaterial): + tri_id = rast[0, :, :, -1:] + mask = tri_id > 0 + uv_coords = mesh.uv_coords.reshape(1, -1, 2) + texc, texd = dr.interpolate( + uv_coords, + rast, + torch.arange(mesh.uv_coords.shape[0] * 3, dtype=torch.int, device=self.device).reshape(-1, 3), + rast_db=rast_db, + diff_attrs='all' + ) + # Fix problematic texture coordinates + texc = torch.nan_to_num(texc, nan=0.0, posinf=1e3, neginf=-1e3) + texc = torch.clamp(texc, min=-1e3, max=1e3) + texd = torch.nan_to_num(texd, nan=0.0, posinf=1e3, neginf=-1e3) + texd = torch.clamp(texd, min=-1e3, max=1e3) + mid = mesh.material_ids[(tri_id - 1).long()] + gb_basecolor = torch.zeros((resolution * ssaa, resolution * ssaa, 3), dtype=torch.float32, device=self.device) + gb_metallic = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + gb_roughness = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + gb_alpha = torch.zeros((resolution * ssaa, resolution * ssaa, 1), dtype=torch.float32, device=self.device) + for id, mat in enumerate(mesh.materials): + mat_mask = (mid == id).float() * mask.float() + mat_texc = texc * mat_mask + mat_texd = texd * mat_mask + + if mat.base_color_texture is not None: + bc = dr.texture( + mat.base_color_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.base_color_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.base_color_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + gb_basecolor += bc * mat.base_color_factor * mat_mask + else: + gb_basecolor += mat.base_color_factor * mat_mask + + if mat.metallic_texture is not None: + m = dr.texture( + mat.metallic_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.metallic_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.metallic_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + gb_metallic += m * mat.metallic_factor * mat_mask + else: + gb_metallic += mat.metallic_factor * mat_mask + + if mat.roughness_texture is not None: + r = dr.texture( + mat.roughness_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.roughness_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.roughness_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + gb_roughness += r * mat.roughness_factor * mat_mask + else: + gb_roughness += mat.roughness_factor * mat_mask + + if mat.alpha_mode == AlphaMode.OPAQUE: + gb_alpha += 1.0 * mat_mask + else: + if mat.alpha_texture is not None: + a = dr.texture( + mat.alpha_texture.image.unsqueeze(0), + mat_texc, + mat_texd, + filter_mode='linear-mipmap-linear' if mat.alpha_texture.filter_mode == TextureFilterMode.LINEAR else 'nearest', + boundary_mode='clamp' if mat.alpha_texture.wrap_mode == TextureWrapMode.CLAMP_TO_EDGE else 'wrap' + )[0] + if mat.alpha_mode == AlphaMode.MASK: + gb_alpha += (a * mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask + elif mat.alpha_mode == AlphaMode.BLEND: + gb_alpha += a * mat.alpha_factor * mat_mask + else: + if mat.alpha_mode == AlphaMode.MASK: + gb_alpha += (mat.alpha_factor > mat.alpha_cutoff).float() * mat_mask + elif mat.alpha_mode == AlphaMode.BLEND: + gb_alpha += mat.alpha_factor * mat_mask + if _ == 0: + out_dict.base_color = gb_basecolor + out_dict.metallic = gb_metallic + out_dict.roughness = gb_roughness + out_dict.alpha = gb_alpha + + # Shading + gb_basecolor = torch.clamp(gb_basecolor, 0.0, 1.0) ** 2.2 + gb_metallic = torch.clamp(gb_metallic, 0.0, 1.0) + gb_roughness = torch.clamp(gb_roughness, 0.0, 1.0) + gb_alpha = torch.clamp(gb_alpha, 0.0, 1.0) + gb_orm = torch.cat([ + torch.zeros_like(gb_metallic), + gb_roughness, + gb_metallic, + ], dim=-1) + gb_shaded = torch.stack([ + e.shade( + pos.unsqueeze(0), + gb_normal.unsqueeze(0), + gb_basecolor.unsqueeze(0), + gb_orm.unsqueeze(0), + rays_o, + specular=True, + )[0] + for e in envmap.values() + ], dim=0) + + # Compositing + w = (1 - alpha) * gb_alpha + depth = torch.where(w > max_w, gb_depth, depth) + normal = torch.where(w > max_w, gb_cam_normal, normal) + max_w = torch.maximum(max_w, w) + shaded += w * gb_shaded + alpha += w + + # Ambient occulusion + f_occ = screen_space_ambient_occlusion( + depth, normal, perspective, intensity=1.5 + ) + shaded *= (1 - f_occ) + out_dict.clay = (1 - f_occ) + + # Background + if use_envmap_bg: + bg = torch.stack([e.sample(rays_d) for e in envmap.values()], dim=0) + shaded += (1 - alpha) * bg + + for i, k in enumerate(envmap.keys()): + shaded_key = f"shaded_{k}" if k != '' else "shaded" + out_dict[shaded_key] = shaded[i] + + # SSAA + for k in out_dict.keys(): + if ssaa > 1: + out_dict[k] = F.interpolate(out_dict[k].unsqueeze(0).permute(0, 3, 1, 2), (resolution, resolution), mode='bilinear', align_corners=False, antialias=True) + else: + out_dict[k] = out_dict[k].permute(2, 0, 1) + out_dict[k] = out_dict[k].squeeze() + + # Post processing + for k in envmap.keys(): + shaded_key = f"shaded_{k}" if k != '' else "shaded" + out_dict[shaded_key] = aces_tonemapping(out_dict[shaded_key]) + out_dict[shaded_key] = gamma_correction(out_dict[shaded_key]) + + return out_dict diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/voxel_renderer.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/voxel_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe28ad8d341ed62c1d7a5ab739fed6cace30a5f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/renderers/voxel_renderer.py @@ -0,0 +1,68 @@ +import torch +from easydict import EasyDict as edict +from ..representations import Voxel +from easydict import EasyDict as edict + + +class VoxelRenderer: + """ + Renderer for the Voxel representation. + + Args: + rendering_options (dict): Rendering options. + """ + + def __init__(self, rendering_options={}) -> None: + self.rendering_options = edict({ + "resolution": None, + "near": 0.1, + "far": 10.0, + "ssaa": 1, + }) + self.rendering_options.update(rendering_options) + + def render( + self, + voxel: Voxel, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + colors_overwrite: torch.Tensor = None + ) -> edict: + """ + Render the gausssian. + + Args: + voxel (Voxel): Voxel representation. + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + colors_overwrite (torch.Tensor): (N, 3) override color + + Returns: + edict containing: + color (torch.Tensor): (3, H, W) rendered color image + depth (torch.Tensor): (H, W) rendered depth + alpha (torch.Tensor): (H, W) rendered alpha + ... + """ + # lazy import + if 'o_voxel' not in globals(): + import o_voxel + renderer = o_voxel.rasterize.VoxelRenderer(self.rendering_options) + positions = voxel.position + attrs = voxel.attrs if colors_overwrite is None else colors_overwrite + voxel_size = voxel.voxel_size + + # Render + render_ret = renderer.render(positions, attrs, voxel_size, extrinsics, intrinsics) + + ret = { + 'depth': render_ret['depth'], + 'alpha': render_ret['alpha'], + } + if colors_overwrite is not None: + ret['color'] = render_ret['attr'] + else: + for k, s in voxel.layout.items(): + ret[k] = render_ret['attr'][s] + + return ret diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e7d9299f866c344e81e27f748f837e5ce81ed8b --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/__init__.py @@ -0,0 +1,31 @@ +import importlib + +__attributes = { + 'Mesh': 'mesh', + 'Voxel': 'voxel', + 'MeshWithVoxel': 'mesh', + 'MeshWithPbrMaterial': 'mesh', +} + +__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] + + +# For Pylance +if __name__ == '__main__': + from .mesh import Mesh, MeshWithVoxel, MeshWithPbrMaterial + from .voxel import Voxel diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/mesh/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/mesh/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aff4c99a97f764a7c695d87d6a60bd03d61e2106 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/mesh/__init__.py @@ -0,0 +1 @@ +from .base import Mesh, MeshWithVoxel, MeshWithPbrMaterial, TextureFilterMode, TextureWrapMode, AlphaMode, PbrMaterial, Texture diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/mesh/base.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/mesh/base.py new file mode 100644 index 0000000000000000000000000000000000000000..b70e4cca19d65b47d07f297894b831d3506be5ff --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/mesh/base.py @@ -0,0 +1,234 @@ +from typing import * +import torch +from ..voxel import Voxel +import cumesh +from flex_gemm.ops.grid_sample import grid_sample_3d + + +class Mesh: + def __init__(self, + vertices, + faces, + vertex_attrs=None + ): + self.vertices = vertices.float() + self.faces = faces.int() + self.vertex_attrs = vertex_attrs + + @property + def device(self): + return self.vertices.device + + def to(self, device, non_blocking=False): + return Mesh( + self.vertices.to(device, non_blocking=non_blocking), + self.faces.to(device, non_blocking=non_blocking), + self.vertex_attrs.to(device, non_blocking=non_blocking) if self.vertex_attrs is not None else None, + ) + + def cuda(self, non_blocking=False): + return self.to('cuda', non_blocking=non_blocking) + + def cpu(self): + return self.to('cpu') + + def fill_holes(self, max_hole_perimeter=3e-2): + vertices = self.vertices.cuda() + faces = self.faces.cuda() + + mesh = cumesh.CuMesh() + mesh.init(vertices, faces) + mesh.get_edges() + mesh.get_boundary_info() + if mesh.num_boundaries == 0: + return + mesh.get_vertex_edge_adjacency() + mesh.get_vertex_boundary_adjacency() + mesh.get_manifold_boundary_adjacency() + mesh.read_manifold_boundary_adjacency() + mesh.get_boundary_connected_components() + mesh.get_boundary_loops() + if mesh.num_boundary_loops == 0: + return + mesh.fill_holes(max_hole_perimeter=max_hole_perimeter) + new_vertices, new_faces = mesh.read() + + self.vertices = new_vertices.to(self.device) + self.faces = new_faces.to(self.device) + + def remove_faces(self, face_mask: torch.Tensor): + vertices = self.vertices.cuda() + faces = self.faces.cuda() + + mesh = cumesh.CuMesh() + mesh.init(vertices, faces) + mesh.remove_faces(face_mask) + new_vertices, new_faces = mesh.read() + + self.vertices = new_vertices.to(self.device) + self.faces = new_faces.to(self.device) + + def simplify(self, target=1000000, verbose: bool=False, options: dict={}): + vertices = self.vertices.cuda() + faces = self.faces.cuda() + + mesh = cumesh.CuMesh() + mesh.init(vertices, faces) + mesh.simplify(target, verbose=verbose, options=options) + new_vertices, new_faces = mesh.read() + + self.vertices = new_vertices.to(self.device) + self.faces = new_faces.to(self.device) + + +class TextureFilterMode: + CLOSEST = 0 + LINEAR = 1 + + +class TextureWrapMode: + CLAMP_TO_EDGE = 0 + REPEAT = 1 + MIRRORED_REPEAT = 2 + + +class AlphaMode: + OPAQUE = 0 + MASK = 1 + BLEND = 2 + + +class Texture: + def __init__( + self, + image: torch.Tensor, + filter_mode: TextureFilterMode = TextureFilterMode.LINEAR, + wrap_mode: TextureWrapMode = TextureWrapMode.REPEAT + ): + self.image = image + self.filter_mode = filter_mode + self.wrap_mode = wrap_mode + + def to(self, device, non_blocking=False): + return Texture( + self.image.to(device, non_blocking=non_blocking), + self.filter_mode, + self.wrap_mode, + ) + + +class PbrMaterial: + def __init__( + self, + base_color_texture: Optional[Texture] = None, + base_color_factor: Union[torch.Tensor, List[float]] = [1.0, 1.0, 1.0], + metallic_texture: Optional[Texture] = None, + metallic_factor: float = 1.0, + roughness_texture: Optional[Texture] = None, + roughness_factor: float = 1.0, + alpha_texture: Optional[Texture] = None, + alpha_factor: float = 1.0, + alpha_mode: AlphaMode = AlphaMode.OPAQUE, + alpha_cutoff: float = 0.5, + ): + self.base_color_texture = base_color_texture + self.base_color_factor = torch.tensor(base_color_factor, dtype=torch.float32)[:3] + self.metallic_texture = metallic_texture + self.metallic_factor = metallic_factor + self.roughness_texture = roughness_texture + self.roughness_factor = roughness_factor + self.alpha_texture = alpha_texture + self.alpha_factor = alpha_factor + self.alpha_mode = alpha_mode + self.alpha_cutoff = alpha_cutoff + + def to(self, device, non_blocking=False): + return PbrMaterial( + base_color_texture=self.base_color_texture.to(device, non_blocking=non_blocking) if self.base_color_texture is not None else None, + base_color_factor=self.base_color_factor.to(device, non_blocking=non_blocking), + metallic_texture=self.metallic_texture.to(device, non_blocking=non_blocking) if self.metallic_texture is not None else None, + metallic_factor=self.metallic_factor, + roughness_texture=self.roughness_texture.to(device, non_blocking=non_blocking) if self.roughness_texture is not None else None, + roughness_factor=self.roughness_factor, + alpha_texture=self.alpha_texture.to(device, non_blocking=non_blocking) if self.alpha_texture is not None else None, + alpha_factor=self.alpha_factor, + alpha_mode=self.alpha_mode, + alpha_cutoff=self.alpha_cutoff, + ) + + +class MeshWithPbrMaterial(Mesh): + def __init__(self, + vertices, + faces, + material_ids, + uv_coords, + materials: List[PbrMaterial], + ): + self.vertices = vertices.float() + self.faces = faces.int() + self.material_ids = material_ids # [M] + self.uv_coords = uv_coords # [M, 3, 2] + self.materials = materials + self.layout = { + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + + def to(self, device, non_blocking=False): + return MeshWithPbrMaterial( + self.vertices.to(device, non_blocking=non_blocking), + self.faces.to(device, non_blocking=non_blocking), + self.material_ids.to(device, non_blocking=non_blocking), + self.uv_coords.to(device, non_blocking=non_blocking), + [material.to(device, non_blocking=non_blocking) for material in self.materials], + ) + + +class MeshWithVoxel(Mesh, Voxel): + def __init__(self, + vertices: torch.Tensor, + faces: torch.Tensor, + origin: list, + voxel_size: float, + coords: torch.Tensor, + attrs: torch.Tensor, + voxel_shape: torch.Size, + layout: Dict = {}, + ): + self.vertices = vertices.float() + self.faces = faces.int() + self.origin = torch.tensor(origin, dtype=torch.float32, device=self.device) + self.voxel_size = voxel_size + self.coords = coords + self.attrs = attrs + self.voxel_shape = voxel_shape + self.layout = layout + + def to(self, device, non_blocking=False): + return MeshWithVoxel( + self.vertices.to(device, non_blocking=non_blocking), + self.faces.to(device, non_blocking=non_blocking), + self.origin.tolist(), + self.voxel_size, + self.coords.to(device, non_blocking=non_blocking), + self.attrs.to(device, non_blocking=non_blocking), + self.voxel_shape, + self.layout, + ) + + def query_attrs(self, xyz): + grid = ((xyz - self.origin) / self.voxel_size).reshape(1, -1, 3) + vertex_attrs = grid_sample_3d( + self.attrs, + torch.cat([torch.zeros_like(self.coords[..., :1]), self.coords], dim=-1), + self.voxel_shape, + grid, + mode='trilinear' + )[0] + return vertex_attrs + + def query_vertex_attrs(self): + return self.query_attrs(self.vertices) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/voxel/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/voxel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5792ea14b2371a96c4130371eb976f0aff4b5dd --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/voxel/__init__.py @@ -0,0 +1 @@ +from .voxel_model import Voxel \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/voxel/voxel_model.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/voxel/voxel_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9317ab22db61c5da96514ca46a780378392f3cc8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/representations/voxel/voxel_model.py @@ -0,0 +1,54 @@ +from typing import Dict +import torch + + +class Voxel: + def __init__( + self, + origin: list, + voxel_size: float, + coords: torch.Tensor = None, + attrs: torch.Tensor = None, + layout: Dict = {}, + device: torch.device = 'cuda' + ): + self.origin = torch.tensor(origin, dtype=torch.float32, device=device) + self.voxel_size = voxel_size + self.coords = coords + self.attrs = attrs + self.layout = layout + self.device = device + + @property + def position(self): + return (self.coords + 0.5) * self.voxel_size + self.origin[None, :] + + def split_attrs(self): + return { + k: self.attrs[:, self.layout[k]] + for k in self.layout + } + + def save(self, path): + # lazy import + if 'o_voxel' not in globals(): + import o_voxel + o_voxel.io.write( + path, + self.coords, + self.split_attrs(), + ) + + def load(self, path): + # lazy import + if 'o_voxel' not in globals(): + import o_voxel + coord, attrs = o_voxel.io.read(path) + self.coords = coord.int().to(self.device) + self.attrs = torch.cat([attrs[k] for k in attrs], dim=1).to(self.device) + # build layout + start = 0 + self.layout = {} + for k in attrs: + self.layout[k] = slice(start, start + attrs[k].shape[1]) + start += attrs[k].shape[1] diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f25130f045b255496364d0f4b95d66ef8cddaab --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/__init__.py @@ -0,0 +1,68 @@ +import importlib + +__attributes = { + 'BasicTrainer': 'basic', + + 'SparseStructureVaeTrainer': 'vae.sparse_structure_vae', + 'ShapeVaeTrainer': 'vae.shape_vae', + 'PbrVaeTrainer': 'vae.pbr_vae', + + 'FlowMatchingTrainer': 'flow_matching.flow_matching', + 'FlowMatchingCFGTrainer': 'flow_matching.flow_matching', + 'TextConditionedFlowMatchingCFGTrainer': 'flow_matching.flow_matching', + 'ImageConditionedFlowMatchingCFGTrainer': 'flow_matching.flow_matching', + + 'SparseFlowMatchingTrainer': 'flow_matching.sparse_flow_matching', + 'SparseFlowMatchingCFGTrainer': 'flow_matching.sparse_flow_matching', + 'TextConditionedSparseFlowMatchingCFGTrainer': 'flow_matching.sparse_flow_matching', + 'ImageConditionedSparseFlowMatchingCFGTrainer': 'flow_matching.sparse_flow_matching', + 'MultiImageConditionedSparseFlowMatchingCFGTrainer': 'flow_matching.sparse_flow_matching', + + 'DinoV2FeatureExtractor': 'flow_matching.mixins.image_conditioned', + 'DinoV3FeatureExtractor': 'flow_matching.mixins.image_conditioned', +} + +__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] + + +# For Pylance +if __name__ == '__main__': + from .basic import BasicTrainer + + from .vae.sparse_structure_vae import SparseStructureVaeTrainer + from .vae.shape_vae import ShapeVaeTrainer + from .vae.pbr_vae import PbrVaeTrainer + + from .flow_matching.flow_matching import ( + FlowMatchingTrainer, + FlowMatchingCFGTrainer, + TextConditionedFlowMatchingCFGTrainer, + ImageConditionedFlowMatchingCFGTrainer, + ) + + from .flow_matching.sparse_flow_matching import ( + SparseFlowMatchingTrainer, + SparseFlowMatchingCFGTrainer, + TextConditionedSparseFlowMatchingCFGTrainer, + ImageConditionedSparseFlowMatchingCFGTrainer, + ) + + from .flow_matching.mixins.image_conditioned import ( + DinoV2FeatureExtractor, + DinoV3FeatureExtractor, + ) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/basic.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..c8e4b4c56247e33a0a73917ea010acf684e6d700 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/basic.py @@ -0,0 +1,910 @@ +from abc import abstractmethod +import os +import time +import json +import copy +import threading +from functools import partial +from contextlib import nullcontext + +import torch +import torch.distributed as dist +from torch.utils.data import DataLoader +from torch.nn.parallel import DistributedDataParallel as DDP +import numpy as np + +from torchvision import utils +from torch.utils.tensorboard import SummaryWriter + +from .utils import * +from ..utils.general_utils import * +from ..utils.data_utils import recursive_to_device, cycle, ResumableSampler +from ..utils.dist_utils import * +from ..utils import grad_clip_utils, elastic_utils + + +class BasicTrainer: + """ + Trainer for basic training loop. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + mix_precision_mode (str): + - None: No mixed precision. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + mix_precision_dtype (str): Mixed precision dtype. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + parallel_mode (str): Parallel mode. Options are 'ddp'. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + """ + def __init__(self, + models, + dataset, + *, + output_dir, + load_dir, + step, + max_steps, + batch_size=None, + batch_size_per_gpu=None, + batch_split=None, + optimizer={}, + lr_scheduler=None, + elastic=None, + grad_clip=None, + ema_rate=0.9999, + fp16_mode=None, + mix_precision_mode='inflat_all', + mix_precision_dtype='float16', + fp16_scale_growth=1e-3, + parallel_mode='ddp', + finetune_ckpt=None, + log_param_stats=False, + prefetch_data=True, + snapshot_batch_size=4, + i_print=1000, + i_log=500, + i_sample=10000, + i_save=10000, + i_ddpcheck=10000, + **kwargs + ): + assert batch_size is not None or batch_size_per_gpu is not None, 'Either batch_size or batch_size_per_gpu must be specified.' + + self.models = models + self.dataset = dataset + self.batch_split = batch_split if batch_split is not None else 1 + self.max_steps = max_steps + self.optimizer_config = optimizer + self.lr_scheduler_config = lr_scheduler + self.elastic_controller_config = elastic + self.grad_clip = grad_clip + self.ema_rate = [ema_rate] if isinstance(ema_rate, float) else ema_rate + if fp16_mode is not None: + mix_precision_dtype = 'float16' + mix_precision_mode = fp16_mode + self.mix_precision_mode = mix_precision_mode + self.mix_precision_dtype = str_to_dtype(mix_precision_dtype) + self.fp16_scale_growth = fp16_scale_growth + self.parallel_mode = parallel_mode + self.log_param_stats = log_param_stats + self.prefetch_data = prefetch_data + self.snapshot_batch_size = snapshot_batch_size + self.log = [] + if self.prefetch_data: + self._data_prefetched = None + + self.output_dir = output_dir + self.i_print = i_print + self.i_log = i_log + self.i_sample = i_sample + self.i_save = i_save + self.i_ddpcheck = i_ddpcheck + + if dist.is_initialized(): + # Multi-GPU params + self.world_size = dist.get_world_size() + self.rank = dist.get_rank() + self.local_rank = dist.get_rank() % torch.cuda.device_count() + self.is_master = self.rank == 0 + else: + # Single-GPU params + self.world_size = 1 + self.rank = 0 + self.local_rank = 0 + self.is_master = True + + self.batch_size = batch_size if batch_size_per_gpu is None else batch_size_per_gpu * self.world_size + self.batch_size_per_gpu = batch_size_per_gpu if batch_size_per_gpu is not None else batch_size // self.world_size + assert self.batch_size % self.world_size == 0, 'Batch size must be divisible by the number of GPUs.' + assert self.batch_size_per_gpu % self.batch_split == 0, 'Batch size per GPU must be divisible by batch split.' + + self.init_models_and_more(**kwargs) + self.prepare_dataloader(**kwargs) + + # Load checkpoint + self.step = 0 + if load_dir is not None and step is not None: + self.load(load_dir, step) + elif finetune_ckpt is not None: + self.finetune_from(finetune_ckpt) + + if self.is_master: + os.makedirs(os.path.join(self.output_dir, 'ckpts'), exist_ok=True) + os.makedirs(os.path.join(self.output_dir, 'samples'), exist_ok=True) + self.writer = SummaryWriter(os.path.join(self.output_dir, 'tb_logs')) + + if self.parallel_mode == 'ddp' and self.world_size > 1: + self.check_ddp() + + if self.is_master: + print('\n\nTrainer initialized.') + print(self) + + def __str__(self): + lines = [] + lines.append(self.__class__.__name__) + lines.append(f' - Models:') + for name, model in self.models.items(): + lines.append(f' - {name}: {model.__class__.__name__}') + lines.append(f' - Dataset: {indent(str(self.dataset), 2)}') + lines.append(f' - Dataloader:') + lines.append(f' - Sampler: {self.dataloader.sampler.__class__.__name__}') + lines.append(f' - Num workers: {self.dataloader.num_workers}') + lines.append(f' - Number of steps: {self.max_steps}') + lines.append(f' - Number of GPUs: {self.world_size}') + lines.append(f' - Batch size: {self.batch_size}') + lines.append(f' - Batch size per GPU: {self.batch_size_per_gpu}') + lines.append(f' - Batch split: {self.batch_split}') + lines.append(f' - Optimizer: {self.optimizer.__class__.__name__}') + lines.append(f' - Learning rate: {self.optimizer.param_groups[0]["lr"]}') + if self.lr_scheduler_config is not None: + lines.append(f' - LR scheduler: {self.lr_scheduler.__class__.__name__}') + if self.elastic_controller_config is not None: + lines.append(f' - Elastic memory: {indent(str(self.elastic_controller), 2)}') + if self.grad_clip is not None: + lines.append(f' - Gradient clip: {indent(str(self.grad_clip), 2)}') + lines.append(f' - EMA rate: {self.ema_rate}') + lines.append(f' - Mixed precision dtype: {self.mix_precision_dtype}') + lines.append(f' - Mixed precision mode: {self.mix_precision_mode}') + if self.mix_precision_mode == 'amp' and self.mix_precision_dtype == torch.float16: + lines.append(f' - FP16 scale growth: {self.fp16_scale_growth}') + lines.append(f' - Parallel mode: {self.parallel_mode}') + return '\n'.join(lines) + + @property + def device(self): + for _, model in self.models.items(): + if hasattr(model, 'device'): + return model.device + return next(list(self.models.values())[0].parameters()).device + + def init_models_and_more(self, **kwargs): + """ + Initialize models and more. + """ + if self.world_size > 1: + # Prepare distributed data parallel + self.training_models = { + name: DDP( + model, + device_ids=[self.local_rank], + output_device=self.local_rank, + bucket_cap_mb=128, + find_unused_parameters=False + ) + for name, model in self.models.items() + } + else: + self.training_models = self.models + + # Build master params + self.model_params = sum( + [[p for p in model.parameters() if p.requires_grad] for model in self.models.values()] + , []) + if self.mix_precision_mode == 'amp': + self.master_params = self.model_params + if self.mix_precision_dtype == torch.float16: + self.scaler = torch.GradScaler() + elif self.mix_precision_mode == 'inflat_all': + self.master_params = make_master_params(self.model_params) + if self.mix_precision_dtype == torch.float16: + self.log_scale = 20.0 + elif self.mix_precision_mode is None: + self.master_params = self.model_params + else: + raise NotImplementedError(f'Mix precision mode {self.mix_precision_mode} is not implemented.') + + # Build EMA params + if self.is_master: + self.ema_params = [copy.deepcopy(self.master_params) for _ in self.ema_rate] + + # Initialize optimizer + if hasattr(torch.optim, self.optimizer_config['name']): + self.optimizer = getattr(torch.optim, self.optimizer_config['name'])(self.master_params, **self.optimizer_config['args']) + else: + self.optimizer = globals()[self.optimizer_config['name']](self.master_params, **self.optimizer_config['args']) + + # Initalize learning rate scheduler + if self.lr_scheduler_config is not None: + if hasattr(torch.optim.lr_scheduler, self.lr_scheduler_config['name']): + self.lr_scheduler = getattr(torch.optim.lr_scheduler, self.lr_scheduler_config['name'])(self.optimizer, **self.lr_scheduler_config['args']) + else: + self.lr_scheduler = globals()[self.lr_scheduler_config['name']](self.optimizer, **self.lr_scheduler_config['args']) + + # Initialize elastic memory controller + if self.elastic_controller_config is not None: + assert any([isinstance(model, (elastic_utils.ElasticModule, elastic_utils.ElasticModuleMixin)) for model in self.models.values()]), \ + 'No elastic module found in models, please inherit from ElasticModule or ElasticModuleMixin' + self.elastic_controller = getattr(elastic_utils, self.elastic_controller_config['name'])(**self.elastic_controller_config['args']) + for model in self.models.values(): + if isinstance(model, (elastic_utils.ElasticModule, elastic_utils.ElasticModuleMixin)): + model.register_memory_controller(self.elastic_controller) + + # Initialize gradient clipper + if self.grad_clip is not None: + if isinstance(self.grad_clip, (float, int)): + self.grad_clip = float(self.grad_clip) + else: + self.grad_clip = getattr(grad_clip_utils, self.grad_clip['name'])(**self.grad_clip['args']) + + def prepare_dataloader(self, **kwargs): + """ + Prepare dataloader. + """ + self.data_sampler = ResumableSampler( + self.dataset, + shuffle=True, + ) + self.dataloader = DataLoader( + self.dataset, + batch_size=self.batch_size_per_gpu, + num_workers=int(np.ceil(os.cpu_count() / torch.cuda.device_count())), + pin_memory=True, + drop_last=True, + persistent_workers=True, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + sampler=self.data_sampler, + ) + self.data_iterator = cycle(self.dataloader) + + def _master_params_to_state_dicts(self, master_params): + """ + Convert master params to dict of state_dicts. + """ + if self.mix_precision_mode == 'inflat_all': + master_params = unflatten_master_params(self.model_params, master_params) + state_dicts = {name: model.state_dict() for name, model in self.models.items()} + master_params_names = sum( + [[(name, n) for n, p in model.named_parameters() if p.requires_grad] for name, model in self.models.items()] + , []) + for i, (model_name, param_name) in enumerate(master_params_names): + state_dicts[model_name][param_name] = master_params[i] + return state_dicts + + def _state_dicts_to_master_params(self, master_params, state_dicts): + """ + Convert a state_dict to master params. + """ + master_params_names = sum( + [[(name, n) for n, p in model.named_parameters() if p.requires_grad] for name, model in self.models.items()] + , []) + params = [state_dicts[name][param_name] for name, param_name in master_params_names] + if self.mix_precision_mode == 'inflat_all': + model_params_to_master_params(params, master_params) + else: + for i, param in enumerate(params): + master_params[i].data.copy_(param.data) + + def load(self, load_dir, step=0): + """ + Load a checkpoint. + Should be called by all processes. + """ + if self.is_master: + print(f'\nLoading checkpoint from step {step}...', end='') + + model_ckpts = {} + for name, model in self.models.items(): + model_ckpt = torch.load(read_file_dist(os.path.join(load_dir, 'ckpts', f'{name}_step{step:07d}.pt')), map_location=self.device, weights_only=True) + model_ckpts[name] = model_ckpt + model.load_state_dict(model_ckpt) + self._state_dicts_to_master_params(self.master_params, model_ckpts) + del model_ckpts + + if self.is_master: + for i, ema_rate in enumerate(self.ema_rate): + ema_ckpts = {} + for name, model in self.models.items(): + ema_ckpt = torch.load(os.path.join(load_dir, 'ckpts', f'{name}_ema{ema_rate}_step{step:07d}.pt'), map_location=self.device, weights_only=True) + ema_ckpts[name] = ema_ckpt + self._state_dicts_to_master_params(self.ema_params[i], ema_ckpts) + del ema_ckpts + + misc_ckpt = torch.load(read_file_dist(os.path.join(load_dir, 'ckpts', f'misc_step{step:07d}.pt')), map_location=torch.device('cpu'), weights_only=False) + self.optimizer.load_state_dict(misc_ckpt['optimizer']) + self.step = misc_ckpt['step'] + self.data_sampler.load_state_dict(misc_ckpt['data_sampler']) + if self.mix_precision_mode == 'amp' and self.mix_precision_dtype == torch.float16: + self.scaler.load_state_dict(misc_ckpt['scaler']) + elif self.mix_precision_mode == 'inflat_all' and self.mix_precision_dtype == torch.float16: + self.log_scale = misc_ckpt['log_scale'] + if self.lr_scheduler_config is not None: + self.lr_scheduler.load_state_dict(misc_ckpt['lr_scheduler']) + if self.elastic_controller_config is not None: + self.elastic_controller.load_state_dict(misc_ckpt['elastic_controller']) + if self.grad_clip is not None and not isinstance(self.grad_clip, float): + self.grad_clip.load_state_dict(misc_ckpt['grad_clip']) + del misc_ckpt + + if self.world_size > 1: + dist.barrier() + if self.is_master: + print(' Done.') + + if self.world_size > 1: + self.check_ddp() + + def save(self, non_blocking=True): + """ + Save a checkpoint. + Should be called only by the rank 0 process. + """ + assert self.is_master, 'save() should be called only by the rank 0 process.' + print(f'\nSaving checkpoint at step {self.step}...', end='') + + model_ckpts = self._master_params_to_state_dicts(self.master_params) + for name, model_ckpt in model_ckpts.items(): + model_ckpt = {k: v.cpu() for k, v in model_ckpt.items()} # Move to CPU for saving + if non_blocking: + threading.Thread( + target=torch.save, + args=(model_ckpt, os.path.join(self.output_dir, 'ckpts', f'{name}_step{self.step:07d}.pt')), + ).start() + else: + torch.save(model_ckpt, os.path.join(self.output_dir, 'ckpts', f'{name}_step{self.step:07d}.pt')) + + for i, ema_rate in enumerate(self.ema_rate): + ema_ckpts = self._master_params_to_state_dicts(self.ema_params[i]) + for name, ema_ckpt in ema_ckpts.items(): + ema_ckpt = {k: v.cpu() for k, v in ema_ckpt.items()} # Move to CPU for saving + if non_blocking: + threading.Thread( + target=torch.save, + args=(ema_ckpt, os.path.join(self.output_dir, 'ckpts', f'{name}_ema{ema_rate}_step{self.step:07d}.pt')), + ).start() + else: + torch.save(ema_ckpt, os.path.join(self.output_dir, 'ckpts', f'{name}_ema{ema_rate}_step{self.step:07d}.pt')) + + misc_ckpt = { + 'optimizer': self.optimizer.state_dict(), + 'step': self.step, + 'data_sampler': self.data_sampler.state_dict(), + } + if self.mix_precision_mode == 'amp' and self.mix_precision_dtype == torch.float16: + misc_ckpt['scaler'] = self.scaler.state_dict() + elif self.mix_precision_mode == 'inflat_all' and self.mix_precision_dtype == torch.float16: + misc_ckpt['log_scale'] = self.log_scale + if self.lr_scheduler_config is not None: + misc_ckpt['lr_scheduler'] = self.lr_scheduler.state_dict() + if self.elastic_controller_config is not None: + misc_ckpt['elastic_controller'] = self.elastic_controller.state_dict() + if self.grad_clip is not None and not isinstance(self.grad_clip, float): + misc_ckpt['grad_clip'] = self.grad_clip.state_dict() + if non_blocking: + threading.Thread( + target=torch.save, + args=(misc_ckpt, os.path.join(self.output_dir, 'ckpts', f'misc_step{self.step:07d}.pt')), + ).start() + else: + torch.save(misc_ckpt, os.path.join(self.output_dir, 'ckpts', f'misc_step{self.step:07d}.pt')) + print(' Done.') + + def finetune_from(self, finetune_ckpt): + """ + Finetune from a checkpoint. + Should be called by all processes. + """ + if self.is_master: + print('\nFinetuning from:') + for name, path in finetune_ckpt.items(): + print(f' - {name}: {path}') + + model_ckpts = {} + for name, model in self.models.items(): + model_state_dict = model.state_dict() + if name in finetune_ckpt: + model_ckpt = torch.load(read_file_dist(finetune_ckpt[name]), map_location=self.device, weights_only=True) + for k, v in model_ckpt.items(): + if k not in model_state_dict: + if self.is_master: + print(f'Warning: {k} not found in model_state_dict, skipped.') + model_ckpt[k] = None + elif model_ckpt[k].shape != model_state_dict[k].shape: + if self.is_master: + print(f'Warning: {k} shape mismatch, {model_ckpt[k].shape} vs {model_state_dict[k].shape}, skipped.') + model_ckpt[k] = model_state_dict[k] + model_ckpt = {k: v for k, v in model_ckpt.items() if v is not None} + model_ckpts[name] = model_ckpt + model.load_state_dict(model_ckpt) + else: + if self.is_master: + print(f'Warning: {name} not found in finetune_ckpt, skipped.') + model_ckpts[name] = model_state_dict + self._state_dicts_to_master_params(self.master_params, model_ckpts) + if self.is_master: + for i, ema_rate in enumerate(self.ema_rate): + self._state_dicts_to_master_params(self.ema_params[i], model_ckpts) + del model_ckpts + + if self.world_size > 1: + dist.barrier() + if self.is_master: + print('Done.') + + if self.world_size > 1: + self.check_ddp() + + @abstractmethod + def run_snapshot(self, num_samples, batch_size=4, verbose=False, **kwargs): + """ + Run a snapshot of the model. + """ + pass + + @torch.no_grad() + def visualize_sample(self, sample): + """ + Convert a sample to an image. + """ + if hasattr(self.dataset, 'visualize_sample'): + return self.dataset.visualize_sample(sample) + else: + return sample + + @torch.no_grad() + def snapshot_dataset(self, num_samples=100, batch_size=4): + """ + Sample images from the dataset. + """ + dataloader = torch.utils.data.DataLoader( + self.dataset, + batch_size=batch_size, + num_workers=1, + shuffle=True, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + ) + save_cfg = {} + for i in range(0, num_samples, batch_size): + data = next(iter(dataloader)) + data = {k: v[:min(num_samples - i, batch_size)] for k, v in data.items()} + data = recursive_to_device(data, self.device) + vis = self.visualize_sample(data) + if isinstance(vis, dict): + for k, v in vis.items(): + if f'dataset_{k}' not in save_cfg: + save_cfg[f'dataset_{k}'] = [] + save_cfg[f'dataset_{k}'].append(v) + else: + if 'dataset' not in save_cfg: + save_cfg['dataset'] = [] + save_cfg['dataset'].append(vis) + for name, image in save_cfg.items(): + utils.save_image( + torch.cat(image, dim=0), + os.path.join(self.output_dir, 'samples', f'{name}.jpg'), + nrow=int(np.sqrt(num_samples)), + normalize=True, + value_range=self.dataset.value_range, + ) + + @torch.no_grad() + def snapshot(self, suffix=None, num_samples=64, batch_size=4, verbose=False): + """ + Sample images from the model. + NOTE: This function should be called by all processes. + """ + if self.is_master: + print(f'\nSampling {num_samples} images...', end='') + + if suffix is None: + suffix = f'step{self.step:07d}' + + # Assign tasks + num_samples_per_process = int(np.ceil(num_samples / self.world_size)) + amp_context = partial(torch.autocast, device_type='cuda', dtype=self.mix_precision_dtype) if self.mix_precision_mode == 'amp' else nullcontext + with amp_context(): + samples = self.run_snapshot(num_samples_per_process, batch_size=batch_size, verbose=verbose) + + # Preprocess images + for key in list(samples.keys()): + if samples[key]['type'] == 'sample': + vis = self.visualize_sample(samples[key]['value']) + if isinstance(vis, dict): + for k, v in vis.items(): + samples[f'{key}_{k}'] = {'value': v, 'type': 'image'} + del samples[key] + else: + samples[key] = {'value': vis, 'type': 'image'} + + # Gather results + if self.world_size > 1: + for key in samples.keys(): + samples[key]['value'] = samples[key]['value'].contiguous() + if self.is_master: + all_images = [torch.empty_like(samples[key]['value']) for _ in range(self.world_size)] + else: + all_images = [] + dist.gather(samples[key]['value'], all_images, dst=0) + if self.is_master: + samples[key]['value'] = torch.cat(all_images, dim=0)[:num_samples] + + # Save images + if self.is_master: + os.makedirs(os.path.join(self.output_dir, 'samples', suffix), exist_ok=True) + for key in samples.keys(): + if samples[key]['type'] == 'image': + utils.save_image( + samples[key]['value'], + os.path.join(self.output_dir, 'samples', suffix, f'{key}_{suffix}.jpg'), + nrow=int(np.sqrt(num_samples)), + normalize=True, + value_range=self.dataset.value_range, + ) + elif samples[key]['type'] == 'number': + min = samples[key]['value'].min() + max = samples[key]['value'].max() + images = (samples[key]['value'] - min) / (max - min) + images = utils.make_grid( + images, + nrow=int(np.sqrt(num_samples)), + normalize=False, + ) + save_image_with_notes( + images, + os.path.join(self.output_dir, 'samples', suffix, f'{key}_{suffix}.jpg'), + notes=f'{key} min: {min}, max: {max}', + ) + + if self.is_master: + print(' Done.') + + def update_ema(self): + """ + Update exponential moving average. + Should only be called by the rank 0 process. + """ + assert self.is_master, 'update_ema() should be called only by the rank 0 process.' + for i, ema_rate in enumerate(self.ema_rate): + for master_param, ema_param in zip(self.master_params, self.ema_params[i]): + ema_param.detach().mul_(ema_rate).add_(master_param, alpha=1.0 - ema_rate) + + def check_ddp(self): + """ + Check if DDP is working properly. + Should be called by all process. + """ + if self.is_master: + print('\nPerforming DDP check...') + + if self.is_master: + print('Checking if parameters are consistent across processes...') + dist.barrier() + try: + for p in self.master_params: + # split to avoid OOM + for i in range(0, p.numel(), 10000000): + sub_size = min(10000000, p.numel() - i) + sub_p = p.detach().view(-1)[i:i+sub_size] + # gather from all processes + sub_p_gather = [torch.empty_like(sub_p) for _ in range(self.world_size)] + dist.all_gather(sub_p_gather, sub_p) + # check if equal + assert all([torch.equal(sub_p, sub_p_gather[i]) for i in range(self.world_size)]), 'parameters are not consistent across processes' + except AssertionError as e: + if self.is_master: + print(f'\n\033[91mError: {e}\033[0m') + print('DDP check failed.') + raise e + + dist.barrier() + if self.is_master: + print('Done.') + + @abstractmethod + def training_losses(**mb_data): + """ + Compute training losses. + """ + pass + + def load_data(self): + """ + Load data. + """ + if self.prefetch_data: + if self._data_prefetched is None: + self._data_prefetched = recursive_to_device(next(self.data_iterator), self.device, non_blocking=True) + data = self._data_prefetched + self._data_prefetched = recursive_to_device(next(self.data_iterator), self.device, non_blocking=True) + else: + data = recursive_to_device(next(self.data_iterator), self.device, non_blocking=True) + + # if the data is a dict, we need to split it into multiple dicts with batch_size_per_gpu + if isinstance(data, dict): + if self.batch_split == 1: + data_list = [data] + else: + batch_size = list(data.values())[0].shape[0] + data_list = [ + {k: v[i * batch_size // self.batch_split:(i + 1) * batch_size // self.batch_split] for k, v in data.items()} + for i in range(self.batch_split) + ] + elif isinstance(data, list): + data_list = data + else: + raise ValueError('Data must be a dict or a list of dicts.') + + return data_list + + def run_step(self, data_list): + """ + Run a training step. + """ + step_log = {'loss': {}, 'status': {}} + amp_context = partial(torch.autocast, device_type='cuda', dtype=self.mix_precision_dtype) if self.mix_precision_mode == 'amp' else nullcontext + elastic_controller_context = self.elastic_controller.record if self.elastic_controller_config is not None else nullcontext + + # Train + losses = [] + statuses = [] + elastic_controller_logs = [] + zero_grad(self.model_params) + for i, mb_data in enumerate(data_list): + ## sync at the end of each batch split + sync_contexts = [self.training_models[name].no_sync for name in self.training_models] if i != len(data_list) - 1 and self.world_size > 1 else [nullcontext] + with nested_contexts(*sync_contexts), elastic_controller_context(): + with amp_context(): + loss, status = self.training_losses(**mb_data) + l = loss['loss'] / len(data_list) + ## backward + if self.mix_precision_mode == 'amp' and self.mix_precision_dtype == torch.float16: + self.scaler.scale(l).backward() + elif self.mix_precision_mode == 'inflat_all' and self.mix_precision_dtype == torch.float16: + scaled_l = l * (2 ** self.log_scale) + scaled_l.backward() + else: + l.backward() + ## log + losses.append(dict_foreach(loss, lambda x: x.item() if isinstance(x, torch.Tensor) else x)) + statuses.append(dict_foreach(status, lambda x: x.item() if isinstance(x, torch.Tensor) else x)) + if self.elastic_controller_config is not None: + elastic_controller_logs.append(self.elastic_controller.log()) + ## gradient clip + if self.grad_clip is not None: + if self.mix_precision_mode == 'amp' and self.mix_precision_dtype == torch.float16: + self.scaler.unscale_(self.optimizer) + elif self.mix_precision_mode == 'inflat_all': + model_grads_to_master_grads(self.model_params, self.master_params) + if self.mix_precision_dtype == torch.float16: + self.master_params[0].grad.mul_(1.0 / (2 ** self.log_scale)) + if isinstance(self.grad_clip, float): + grad_norm = torch.nn.utils.clip_grad_norm_(self.master_params, self.grad_clip) + else: + grad_norm = self.grad_clip(self.master_params) + if torch.isfinite(grad_norm): + statuses[-1]['grad_norm'] = grad_norm.item() + ## step + if self.mix_precision_mode == 'amp' and self.mix_precision_dtype == torch.float16: + prev_scale = self.scaler.get_scale() + self.scaler.step(self.optimizer) + self.scaler.update() + elif self.mix_precision_mode == 'inflat_all': + if self.mix_precision_dtype == torch.float16: + prev_scale = 2 ** self.log_scale + if not any(not p.grad.isfinite().all() for p in self.model_params): + if self.grad_clip is None: + model_grads_to_master_grads(self.model_params, self.master_params) + self.master_params[0].grad.mul_(1.0 / (2 ** self.log_scale)) + self.optimizer.step() + master_params_to_model_params(self.model_params, self.master_params) + self.log_scale += self.fp16_scale_growth + else: + self.log_scale -= 1 + else: + prev_scale = 1.0 + if self.grad_clip is None: + model_grads_to_master_grads(self.model_params, self.master_params) + if not any(not p.grad.isfinite().all() for p in self.master_params): + self.optimizer.step() + master_params_to_model_params(self.model_params, self.master_params) + else: + print('\n\033[93mWarning: NaN detected in gradients. Skipping update.\033[0m') + else: + prev_scale = 1.0 + if not any(not p.grad.isfinite().all() for p in self.model_params): + self.optimizer.step() + else: + print('\n\033[93mWarning: NaN detected in gradients. Skipping update.\033[0m') + ## adjust learning rate + if self.lr_scheduler_config is not None: + statuses[-1]['lr'] = self.lr_scheduler.get_last_lr()[0] + self.lr_scheduler.step() + + # Logs + step_log['loss'] = dict_reduce(losses, lambda x: np.mean(x)) + step_log['status'] = dict_reduce(statuses, lambda x: np.mean(x), special_func={'min': lambda x: np.min(x), 'max': lambda x: np.max(x)}) + if self.elastic_controller_config is not None: + step_log['elastic'] = dict_reduce(elastic_controller_logs, lambda x: np.mean(x)) + if self.grad_clip is not None: + step_log['grad_clip'] = self.grad_clip if isinstance(self.grad_clip, float) else self.grad_clip.log() + + # Check grad and norm of each param + if self.log_param_stats: + param_norms = {} + param_grads = {} + for model_name, model in self.models.items(): + for name, param in model.named_parameters(): + if param.requires_grad: + param_norms[f'{model_name}.{name}'] = param.norm().item() + if param.grad is not None and torch.isfinite(param.grad).all(): + param_grads[f'{model_name}.{name}'] = param.grad.norm().item() / prev_scale + step_log['param_norms'] = param_norms + step_log['param_grads'] = param_grads + + # Update exponential moving average + if self.is_master: + self.update_ema() + + return step_log + + def save_logs(self): + log_str = '\n'.join([ + f'{step}: {json.dumps(dict_foreach(log, lambda x: float(x)))}' for step, log in self.log + ]) + with open(os.path.join(self.output_dir, 'log.txt'), 'a') as log_file: + log_file.write(log_str + '\n') + + # show with mlflow + log_show = [l for _, l in self.log if not dict_any(l, lambda x: np.isnan(x))] + log_show = dict_reduce(log_show, lambda x: np.mean(x)) + log_show = dict_flatten(log_show, sep='/') + for key, value in log_show.items(): + self.writer.add_scalar(key, value, self.step) + self.log = [] + + def check_abort(self): + """ + Check if training should be aborted due to certain conditions. + """ + # 1. If log_scale in inflat_all mode is less than 0 + if self.mix_precision_dtype == torch.float16 and \ + self.mix_precision_mode == 'inflat_all' and \ + self.log_scale < 0: + if self.is_master: + print ('\n\n\033[91m') + print (f'ABORT: log_scale in inflat_all mode is less than 0 at step {self.step}.') + print ('This indicates that the model is diverging. You should look into the model and the data.') + print ('\033[0m') + self.save(non_blocking=False) + self.save_logs() + if self.world_size > 1: + dist.barrier() + raise ValueError('ABORT: log_scale in inflat_all mode is less than 0.') + + def run(self): + """ + Run training. + """ + if self.is_master: + print('\nStarting training...') + self.snapshot_dataset(batch_size=self.snapshot_batch_size) + if self.step == 0: + self.snapshot(suffix='init', batch_size=self.snapshot_batch_size) + else: # resume + self.snapshot(suffix=f'resume_step{self.step:07d}', batch_size=self.snapshot_batch_size) + + time_last_print = 0.0 + time_elapsed = 0.0 + while self.step < self.max_steps: + time_start = time.time() + + data_list = self.load_data() + step_log = self.run_step(data_list) + + time_end = time.time() + time_elapsed += time_end - time_start + + self.step += 1 + + # Print progress + if self.is_master and self.step % self.i_print == 0: + speed = self.i_print / (time_elapsed - time_last_print) * 3600 + columns = [ + f'Step: {self.step}/{self.max_steps} ({self.step / self.max_steps * 100:.2f}%)', + f'Elapsed: {time_elapsed / 3600:.2f} h', + f'Speed: {speed:.2f} steps/h', + f'ETA: {(self.max_steps - self.step) / speed:.2f} h', + ] + print(' | '.join([c.ljust(25) for c in columns]), flush=True) + time_last_print = time_elapsed + + # Check ddp + if self.parallel_mode == 'ddp' and self.world_size > 1 and self.i_ddpcheck is not None and self.step % self.i_ddpcheck == 0: + self.check_ddp() + + # Sample images + if self.step % self.i_sample == 0: + self.snapshot() + + if self.is_master: + self.log.append((self.step, {})) + + # Log time + self.log[-1][1]['time'] = { + 'step': time_end - time_start, + 'elapsed': time_elapsed, + } + + # Log losses + if step_log is not None: + self.log[-1][1].update(step_log) + + # Log scale + if self.mix_precision_dtype == torch.float16: + if self.mix_precision_mode == 'amp': + self.log[-1][1]['scale'] = self.scaler.get_scale() + elif self.mix_precision_mode == 'inflat_all': + self.log[-1][1]['log_scale'] = self.log_scale + + # Save log + if self.step % self.i_log == 0: + self.save_logs() + + # Save checkpoint + if self.step % self.i_save == 0: + self.save() + + # Check abort + self.check_abort() + + self.snapshot(suffix='final', batch_size=self.snapshot_batch_size) + if self.world_size > 1: + dist.barrier() + if self.is_master: + self.writer.close() + print('Training finished.') + + def profile(self, wait=2, warmup=3, active=5): + """ + Profile the training loop. + """ + with torch.profiler.profile( + schedule=torch.profiler.schedule(wait=wait, warmup=warmup, active=active, repeat=1), + on_trace_ready=torch.profiler.tensorboard_trace_handler(os.path.join(self.output_dir, 'profile')), + profile_memory=True, + with_stack=True, + ) as prof: + for _ in range(wait + warmup + active): + self.run_step() + prof.step() diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/flow_matching.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/flow_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..7b4390e0fd5bb611f407887db0f3586b15ac741c --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/flow_matching.py @@ -0,0 +1,353 @@ +from typing import * +import copy +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader +import numpy as np +from easydict import EasyDict as edict + +from ..basic import BasicTrainer +from ...pipelines import samplers +from ...utils.general_utils import dict_reduce +from .mixins.classifier_free_guidance import ClassifierFreeGuidanceMixin +from .mixins.text_conditioned import TextConditionedMixin +from .mixins.image_conditioned import ImageConditionedMixin + + +class FlowMatchingTrainer(BasicTrainer): + """ + Trainer for diffusion model with flow matching objective. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + """ + def __init__( + self, + *args, + t_schedule: dict = { + 'name': 'logitNormal', + 'args': { + 'mean': 0.0, + 'std': 1.0, + } + }, + sigma_min: float = 1e-5, + **kwargs + ): + super().__init__(*args, **kwargs) + self.t_schedule = t_schedule + self.sigma_min = sigma_min + + def diffuse(self, x_0: torch.Tensor, t: torch.Tensor, noise: Optional[torch.Tensor] = None) -> torch.Tensor: + """ + Diffuse the data for a given number of diffusion steps. + In other words, sample from q(x_t | x_0). + + Args: + x_0: The [N x C x ...] tensor of noiseless inputs. + t: The [N] tensor of diffusion steps [0-1]. + noise: If specified, use this noise instead of generating new noise. + + Returns: + x_t, the noisy version of x_0 under timestep t. + """ + if noise is None: + noise = torch.randn_like(x_0) + assert noise.shape == x_0.shape, "noise must have same shape as x_0" + + t = t.view(-1, *[1 for _ in range(len(x_0.shape) - 1)]) + x_t = (1 - t) * x_0 + (self.sigma_min + (1 - self.sigma_min) * t) * noise + + return x_t + + def reverse_diffuse(self, x_t: torch.Tensor, t: torch.Tensor, noise: torch.Tensor) -> torch.Tensor: + """ + Get original image from noisy version under timestep t. + """ + assert noise.shape == x_t.shape, "noise must have same shape as x_t" + t = t.view(-1, *[1 for _ in range(len(x_t.shape) - 1)]) + x_0 = (x_t - (self.sigma_min + (1 - self.sigma_min) * t) * noise) / (1 - t) + return x_0 + + def get_v(self, x_0: torch.Tensor, noise: torch.Tensor, t: torch.Tensor) -> torch.Tensor: + """ + Compute the velocity of the diffusion process at time t. + """ + return (1 - self.sigma_min) * noise - x_0 + + def get_cond(self, cond, **kwargs): + """ + Get the conditioning data. + """ + return cond + + def get_inference_cond(self, cond, **kwargs): + """ + Get the conditioning data for inference. + """ + return {'cond': cond, **kwargs} + + def get_sampler(self, **kwargs) -> samplers.FlowEulerSampler: + """ + Get the sampler for the diffusion process. + """ + return samplers.FlowEulerSampler(self.sigma_min) + + def vis_cond(self, **kwargs): + """ + Visualize the conditioning data. + """ + return {} + + def sample_t(self, batch_size: int) -> torch.Tensor: + """ + Sample timesteps. + """ + if self.t_schedule['name'] == 'uniform': + t = torch.rand(batch_size) + elif self.t_schedule['name'] == 'logitNormal': + mean = self.t_schedule['args']['mean'] + std = self.t_schedule['args']['std'] + t = torch.sigmoid(torch.randn(batch_size) * std + mean) + else: + raise ValueError(f"Unknown t_schedule: {self.t_schedule['name']}") + return t + + def training_losses( + self, + x_0: torch.Tensor, + cond=None, + **kwargs + ) -> Tuple[Dict, Dict]: + """ + Compute training losses for a single timestep. + + Args: + x_0: The [N x C x ...] tensor of noiseless inputs. + cond: The [N x ...] tensor of additional conditions. + kwargs: Additional arguments to pass to the backbone. + + Returns: + a dict with the key "loss" containing a tensor of shape [N]. + may also contain other keys for different terms. + """ + noise = torch.randn_like(x_0) + t = self.sample_t(x_0.shape[0]).to(x_0.device).float() + x_t = self.diffuse(x_0, t, noise=noise) + cond = self.get_cond(cond, **kwargs) + + pred = self.training_models['denoiser'](x_t, t * 1000, cond, **kwargs) + assert pred.shape == noise.shape == x_0.shape + target = self.get_v(x_0, noise, t) + terms = edict() + terms["mse"] = F.mse_loss(pred, target) + terms["loss"] = terms["mse"] + + # log loss with time bins + mse_per_instance = np.array([ + F.mse_loss(pred[i], target[i]).item() + for i in range(x_0.shape[0]) + ]) + time_bin = np.digitize(t.cpu().numpy(), np.linspace(0, 1, 11)) - 1 + for i in range(10): + if (time_bin == i).sum() != 0: + terms[f"bin_{i}"] = {"mse": mse_per_instance[time_bin == i].mean()} + + return terms, {} + + @torch.no_grad() + def run_snapshot( + self, + num_samples: int, + batch_size: int, + verbose: bool = False, + ) -> Dict: + dataloader = DataLoader( + copy.deepcopy(self.dataset), + batch_size=batch_size, + shuffle=True, + num_workers=0, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + ) + + # inference + sampler = self.get_sampler() + sample_gt = [] + sample = [] + cond_vis = [] + for i in range(0, num_samples, batch_size): + batch = min(batch_size, num_samples - i) + data = next(iter(dataloader)) + data = {k: v[:batch].cuda() if isinstance(v, torch.Tensor) else v[:batch] for k, v in data.items()} + noise = torch.randn_like(data['x_0']) + sample_gt.append(data['x_0']) + cond_vis.append(self.vis_cond(**data)) + del data['x_0'] + args = self.get_inference_cond(**data) + res = sampler.sample( + self.models['denoiser'], + noise=noise, + **args, + steps=50, guidance_strength=3.0, verbose=verbose, + ) + sample.append(res.samples) + + sample_gt = torch.cat(sample_gt, dim=0) + sample = torch.cat(sample, dim=0) + sample_dict = { + 'sample_gt': {'value': sample_gt, 'type': 'sample'}, + 'sample': {'value': sample, 'type': 'sample'}, + } + sample_dict.update(dict_reduce(cond_vis, None, { + 'value': lambda x: torch.cat(x, dim=0), + 'type': lambda x: x[0], + })) + + return sample_dict + + +class FlowMatchingCFGTrainer(ClassifierFreeGuidanceMixin, FlowMatchingTrainer): + """ + Trainer for diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + """ + pass + + +class TextConditionedFlowMatchingCFGTrainer(TextConditionedMixin, FlowMatchingCFGTrainer): + """ + Trainer for text-conditioned diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + text_cond_model(str): Text conditioning model. + """ + pass + + +class ImageConditionedFlowMatchingCFGTrainer(ImageConditionedMixin, FlowMatchingCFGTrainer): + """ + Trainer for image-conditioned diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + image_cond_model (str): Image conditioning model. + """ + pass diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/classifier_free_guidance.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/classifier_free_guidance.py new file mode 100644 index 0000000000000000000000000000000000000000..548e007bbf3122d818fe05041fba171665d7e450 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/classifier_free_guidance.py @@ -0,0 +1,59 @@ +import torch +import numpy as np +from ....utils.general_utils import dict_foreach +from ....pipelines import samplers + + +class ClassifierFreeGuidanceMixin: + def __init__(self, *args, p_uncond: float = 0.1, **kwargs): + super().__init__(*args, **kwargs) + self.p_uncond = p_uncond + + def get_cond(self, cond, neg_cond=None, **kwargs): + """ + Get the conditioning data. + """ + assert neg_cond is not None, "neg_cond must be provided for classifier-free guidance" + + if self.p_uncond > 0: + # randomly drop the class label + def get_batch_size(cond): + if isinstance(cond, torch.Tensor): + return cond.shape[0] + elif isinstance(cond, list): + return len(cond) + else: + raise ValueError(f"Unsupported type of cond: {type(cond)}") + + ref_cond = cond if not isinstance(cond, dict) else cond[list(cond.keys())[0]] + B = get_batch_size(ref_cond) + + def select(cond, neg_cond, mask): + if isinstance(cond, torch.Tensor): + mask = torch.tensor(mask, device=cond.device).reshape(-1, *[1] * (cond.ndim - 1)) + return torch.where(mask, neg_cond, cond) + elif isinstance(cond, list): + return [nc if m else c for c, nc, m in zip(cond, neg_cond, mask)] + else: + raise ValueError(f"Unsupported type of cond: {type(cond)}") + + mask = list(np.random.rand(B) < self.p_uncond) + if not isinstance(cond, dict): + cond = select(cond, neg_cond, mask) + else: + cond = dict_foreach([cond, neg_cond], lambda x: select(x[0], x[1], mask)) + + return cond + + def get_inference_cond(self, cond, neg_cond=None, **kwargs): + """ + Get the conditioning data for inference. + """ + assert neg_cond is not None, "neg_cond must be provided for classifier-free guidance" + return {'cond': cond, 'neg_cond': neg_cond, **kwargs} + + def get_sampler(self, **kwargs) -> samplers.FlowEulerCfgSampler: + """ + Get the sampler for the diffusion process. + """ + return samplers.FlowEulerCfgSampler(self.sigma_min) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/image_conditioned.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/image_conditioned.py new file mode 100644 index 0000000000000000000000000000000000000000..13b932eb714084ad7fc4ac56d3136d5c90db4350 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/image_conditioned.py @@ -0,0 +1,249 @@ +from typing import * +import torch +import torch.nn.functional as F +from torchvision import transforms +from transformers import DINOv3ViTModel +import numpy as np +from PIL import Image + +from ....utils import dist_utils + + +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 features + + +class ImageConditionedMixin: + """ + Mixin for image-conditioned models. + + Args: + image_cond_model: The image conditioning model. + """ + def __init__(self, *args, image_cond_model: dict, **kwargs): + super().__init__(*args, **kwargs) + self.image_cond_model_config = image_cond_model + self.image_cond_model = None # the model is init lazily + + def _init_image_cond_model(self): + """ + Initialize the image conditioning model. + """ + with dist_utils.local_master_first(): + self.image_cond_model = globals()[self.image_cond_model_config['name']](**self.image_cond_model_config.get('args', {})) + self.image_cond_model.cuda() + + @torch.no_grad() + def encode_image(self, image: Union[torch.Tensor, List[Image.Image]]) -> torch.Tensor: + """ + Encode the image. + """ + if self.image_cond_model is None: + self._init_image_cond_model() + features = self.image_cond_model(image) + return features + + def get_cond(self, cond, **kwargs): + """ + Get the conditioning data. + """ + cond = self.encode_image(cond) + kwargs['neg_cond'] = torch.zeros_like(cond) + cond = super().get_cond(cond, **kwargs) + return cond + + def get_inference_cond(self, cond, **kwargs): + """ + Get the conditioning data for inference. + """ + cond = self.encode_image(cond) + kwargs['neg_cond'] = torch.zeros_like(cond) + cond = super().get_inference_cond(cond, **kwargs) + return cond + + def vis_cond(self, cond, **kwargs): + """ + Visualize the conditioning data. + """ + return {'image': {'value': cond, 'type': 'image'}} + + +class MultiImageConditionedMixin: + """ + Mixin for multiple-image-conditioned models. + + Args: + image_cond_model: The image conditioning model. + """ + def __init__(self, *args, image_cond_model: dict, **kwargs): + super().__init__(*args, **kwargs) + self.image_cond_model_config = image_cond_model + self.image_cond_model = None # the model is init lazily + + def _init_image_cond_model(self): + """ + Initialize the image conditioning model. + """ + with dist_utils.local_master_first(): + self.image_cond_model = globals()[self.image_cond_model_config['name']](**self.image_cond_model_config.get('args', {})) + + @torch.no_grad() + def encode_images(self, images: Union[List[torch.Tensor], List[List[Image.Image]]]) -> List[torch.Tensor]: + """ + Encode the image. + """ + if self.image_cond_model is None: + self._init_image_cond_model() + seqlen = [len(i) for i in images] + images = torch.cat(images, dim=0) if isinstance(images[0], torch.Tensor) else sum(images, []) + features = self.image_cond_model(images) + features = torch.split(features, seqlen) + features = [feature.reshape(-1, feature.shape[-1]) for feature in features] + return features + + def get_cond(self, cond, **kwargs): + """ + Get the conditioning data. + """ + cond = self.encode_images(cond) + kwargs['neg_cond'] = [ + torch.zeros_like(cond[0][:1, :]) for _ in range(len(cond)) + ] + cond = super().get_cond(cond, **kwargs) + return cond + + def get_inference_cond(self, cond, **kwargs): + """ + Get the conditioning data for inference. + """ + cond = self.encode_images(cond) + kwargs['neg_cond'] = [ + torch.zeros_like(cond[0][:1, :]) for _ in range(len(cond)) + ] + cond = super().get_inference_cond(cond, **kwargs) + return cond + + def vis_cond(self, cond, **kwargs): + """ + Visualize the conditioning data. + """ + H, W = cond[0].shape[-2:] + vis = [] + for images in cond: + canvas = torch.zeros(3, H * 2, W * 2, device=images.device, dtype=images.dtype) + for i, image in enumerate(images): + if i == 4: + break + kh = i // 2 + kw = i % 2 + canvas[:, kh*H:(kh+1)*H, kw*W:(kw+1)*W] = image + vis.append(canvas) + vis = torch.stack(vis) + return {'image': {'value': vis, 'type': 'image'}} diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/text_conditioned.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/text_conditioned.py new file mode 100644 index 0000000000000000000000000000000000000000..85f1dcf2582c07edd9b629c07181265f24a90134 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/mixins/text_conditioned.py @@ -0,0 +1,68 @@ +from typing import * +import os +os.environ['TOKENIZERS_PARALLELISM'] = 'true' +import torch +from transformers import AutoTokenizer, CLIPTextModel + +from ....utils import dist_utils + + +class TextConditionedMixin: + """ + Mixin for text-conditioned models. + + Args: + text_cond_model: The text conditioning model. + """ + def __init__(self, *args, text_cond_model: str = 'openai/clip-vit-large-patch14', **kwargs): + super().__init__(*args, **kwargs) + self.text_cond_model_name = text_cond_model + self.text_cond_model = None # the model is init lazily + + def _init_text_cond_model(self): + """ + Initialize the text conditioning model. + """ + # load model + with dist_utils.local_master_first(): + model = CLIPTextModel.from_pretrained(self.text_cond_model_name) + tokenizer = AutoTokenizer.from_pretrained(self.text_cond_model_name) + model.eval() + model = model.cuda() + self.text_cond_model = { + 'model': model, + 'tokenizer': tokenizer, + } + self.text_cond_model['null_cond'] = self.encode_text(['']) + + @torch.no_grad() + def encode_text(self, text: List[str]) -> torch.Tensor: + """ + Encode the text. + """ + assert isinstance(text, list) and isinstance(text[0], str), "TextConditionedMixin only supports list of strings as cond" + if self.text_cond_model is None: + self._init_text_cond_model() + encoding = self.text_cond_model['tokenizer'](text, max_length=77, padding='max_length', truncation=True, return_tensors='pt') + tokens = encoding['input_ids'].cuda() + embeddings = self.text_cond_model['model'](input_ids=tokens).last_hidden_state + + return embeddings + + def get_cond(self, cond, **kwargs): + """ + Get the conditioning data. + """ + cond = self.encode_text(cond) + kwargs['neg_cond'] = self.text_cond_model['null_cond'].repeat(cond.shape[0], 1, 1) + cond = super().get_cond(cond, **kwargs) + return cond + + def get_inference_cond(self, cond, **kwargs): + """ + Get the conditioning data for inference. + """ + cond = self.encode_text(cond) + kwargs['neg_cond'] = self.text_cond_model['null_cond'].repeat(cond.shape[0], 1, 1) + cond = super().get_inference_cond(cond, **kwargs) + return cond diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/sparse_flow_matching.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/sparse_flow_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..c6735d08740ef4548116e46f0d594724e07def6d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/flow_matching/sparse_flow_matching.py @@ -0,0 +1,325 @@ +from typing import * +import os +import copy +import functools +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader +import numpy as np +from easydict import EasyDict as edict + +from ...modules import sparse as sp +from ...utils.general_utils import dict_reduce +from ...utils.data_utils import recursive_to_device, cycle, BalancedResumableSampler +from .flow_matching import FlowMatchingTrainer +from .mixins.classifier_free_guidance import ClassifierFreeGuidanceMixin +from .mixins.text_conditioned import TextConditionedMixin +from .mixins.image_conditioned import ImageConditionedMixin, MultiImageConditionedMixin + + +class SparseFlowMatchingTrainer(FlowMatchingTrainer): + """ + Trainer for sparse diffusion model with flow matching objective. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + """ + + def prepare_dataloader(self, **kwargs): + """ + Prepare dataloader. + """ + self.data_sampler = BalancedResumableSampler( + self.dataset, + shuffle=True, + batch_size=self.batch_size_per_gpu, + ) + self.dataloader = DataLoader( + self.dataset, + batch_size=self.batch_size_per_gpu, + num_workers=int(np.ceil(os.cpu_count() / torch.cuda.device_count())), + pin_memory=True, + drop_last=True, + persistent_workers=True, + collate_fn=functools.partial(self.dataset.collate_fn, split_size=self.batch_split), + sampler=self.data_sampler, + ) + self.data_iterator = cycle(self.dataloader) + + def training_losses( + self, + x_0: sp.SparseTensor, + cond=None, + **kwargs + ) -> Tuple[Dict, Dict]: + """ + Compute training losses for a single timestep. + + Args: + x_0: The [N x ... x C] sparse tensor of the inputs. + cond: The [N x ...] tensor of additional conditions. + kwargs: Additional arguments to pass to the backbone. + + Returns: + a dict with the key "loss" containing a tensor of shape [N]. + may also contain other keys for different terms. + """ + noise = x_0.replace(torch.randn_like(x_0.feats)) + t = self.sample_t(x_0.shape[0]).to(x_0.device).float() + x_t = self.diffuse(x_0, t, noise=noise) + cond = self.get_cond(cond, **kwargs) + + pred = self.training_models['denoiser'](x_t, t * 1000, cond, **kwargs) + assert pred.shape == noise.shape == x_0.shape + target = self.get_v(x_0, noise, t) + terms = edict() + terms["mse"] = F.mse_loss(pred.feats, target.feats) + terms["loss"] = terms["mse"] + + # log loss with time bins + mse_per_instance = np.array([ + F.mse_loss(pred.feats[x_0.layout[i]], target.feats[x_0.layout[i]]).item() + for i in range(x_0.shape[0]) + ]) + time_bin = np.digitize(t.cpu().numpy(), np.linspace(0, 1, 11)) - 1 + for i in range(10): + if (time_bin == i).sum() != 0: + terms[f"bin_{i}"] = {"mse": mse_per_instance[time_bin == i].mean()} + + return terms, {} + + @torch.no_grad() + def run_snapshot( + self, + num_samples: int, + batch_size: int, + verbose: bool = False, + ) -> Dict: + dataloader = DataLoader( + copy.deepcopy(self.dataset), + batch_size=num_samples, + shuffle=True, + num_workers=0, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + ) + data = next(iter(dataloader)) + + # inference + sampler = self.get_sampler() + sample = [] + cond_vis = [] + for i in range(0, num_samples, batch_size): + batch_data = {k: v[i:i+batch_size] for k, v in data.items()} + batch_data = recursive_to_device(batch_data, 'cuda') + noise = batch_data['x_0'].replace(torch.randn_like(batch_data['x_0'].feats)) + cond_vis.append(self.vis_cond(**batch_data)) + del batch_data['x_0'] + args = self.get_inference_cond(**batch_data) + res = sampler.sample( + self.models['denoiser'], + noise=noise, + **args, + steps=12, guidance_strength=3.0, verbose=verbose, + ) + sample.append(res.samples) + sample = sp.sparse_cat(sample) + + sample_gt = {k: v for k, v in data.items()} + sample = {k: v if k != 'x_0' else sample for k, v in data.items()} + sample_dict = { + 'sample_gt': {'value': sample_gt, 'type': 'sample'}, + 'sample': {'value': sample, 'type': 'sample'}, + } + sample_dict.update(dict_reduce(cond_vis, None, { + 'value': lambda x: torch.cat(x, dim=0), + 'type': lambda x: x[0], + })) + + return sample_dict + + +class SparseFlowMatchingCFGTrainer(ClassifierFreeGuidanceMixin, SparseFlowMatchingTrainer): + """ + Trainer for sparse diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + """ + pass + + +class TextConditionedSparseFlowMatchingCFGTrainer(TextConditionedMixin, SparseFlowMatchingCFGTrainer): + """ + Trainer for sparse text-conditioned diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + text_cond_model(str): Text conditioning model. + """ + pass + + +class ImageConditionedSparseFlowMatchingCFGTrainer(ImageConditionedMixin, SparseFlowMatchingCFGTrainer): + """ + Trainer for sparse image-conditioned diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + image_cond_model (str): Image conditioning model. + """ + pass + + +class MultiImageConditionedSparseFlowMatchingCFGTrainer(MultiImageConditionedMixin, SparseFlowMatchingCFGTrainer): + """ + Trainer for sparse image-conditioned diffusion model with flow matching objective and classifier-free guidance. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + t_schedule (dict): Time schedule for flow matching. + sigma_min (float): Minimum noise level. + p_uncond (float): Probability of dropping conditions. + image_cond_model (str): Image conditioning model. + """ + pass diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23e4286d02b6fc102c364d2ef7571ef97c9fcd41 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/utils.py @@ -0,0 +1,91 @@ +import torch +import torch.nn as nn + +# FP16 utils +from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors + + +def str_to_dtype(dtype_str: str): + return { + 'f16': torch.float16, + 'fp16': torch.float16, + 'float16': torch.float16, + 'bf16': torch.bfloat16, + 'bfloat16': torch.bfloat16, + 'f32': torch.float32, + 'fp32': torch.float32, + 'float32': torch.float32, + }[dtype_str] + + +def make_master_params(model_params): + """ + Copy model parameters into a inflated tensor of full-precision parameters. + """ + master_params = _flatten_dense_tensors( + [param.detach().float() for param in model_params] + ) + master_params = nn.Parameter(master_params) + master_params.requires_grad = True + return [master_params] + + +def unflatten_master_params(model_params, master_params): + """ + Unflatten the master parameters to look like model_params. + """ + return _unflatten_dense_tensors(master_params[0].detach(), model_params) + + +def model_params_to_master_params(model_params, master_params): + """ + Copy the model parameter data into the master parameters. + """ + master_params[0].detach().copy_( + _flatten_dense_tensors([param.detach().float() for param in model_params]) + ) + + +def master_params_to_model_params(model_params, master_params): + """ + Copy the master parameter data back into the model parameters. + """ + for param, master_param in zip( + model_params, _unflatten_dense_tensors(master_params[0].detach(), model_params) + ): + param.detach().copy_(master_param) + + +def model_grads_to_master_grads(model_params, master_params): + """ + Copy the gradients from the model parameters into the master parameters + from make_master_params(). + """ + master_params[0].grad = _flatten_dense_tensors( + [param.grad.data.detach().float() for param in model_params] + ) + + +def zero_grad(model_params): + for param in model_params: + if param.grad is not None: + if param.grad.grad_fn is not None: + param.grad.detach_() + else: + param.grad.requires_grad_(False) + param.grad.zero_() + + +# LR Schedulers +from torch.optim.lr_scheduler import LambdaLR + +class LinearWarmupLRScheduler(LambdaLR): + def __init__(self, optimizer, warmup_steps, last_epoch=-1): + self.warmup_steps = warmup_steps + super(LinearWarmupLRScheduler, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) + + def lr_lambda(self, current_step): + if current_step < self.warmup_steps: + return float(current_step + 1) / self.warmup_steps + return 1.0 + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/pbr_vae.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/pbr_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..552723652714a7bc0fc9eeec7620992d4d07a2b5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/pbr_vae.py @@ -0,0 +1,281 @@ +from typing import * +import os +import copy +import functools +import numpy as np +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader +import utils3d +from easydict import EasyDict as edict + +from ..basic import BasicTrainer +from ...modules import sparse as sp +from ...renderers import MeshRenderer +from ...representations import Mesh, MeshWithPbrMaterial, MeshWithVoxel +from ...utils.data_utils import recursive_to_device, cycle, BalancedResumableSampler +from ...utils.loss_utils import l1_loss, l2_loss, ssim, lpips + + +class PbrVaeTrainer(BasicTrainer): + """ + Trainer for PBR attributes VAE + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + loss_type (str): Loss type. + lambda_kl (float): KL loss weight. + lambda_ssim (float): SSIM loss weight. + lambda_lpips (float): LPIPS loss weight. + """ + + def __init__( + self, + *args, + loss_type: str = 'l1', + lambda_kl: float = 1e-6, + lambda_ssim: float = 0.2, + lambda_lpips: float = 0.2, + lambda_render: float = 1.0, + render_resolution: float = 1024, + camera_randomization_config: dict = { + 'radius_range': [2, 100], + }, + **kwargs + ): + super().__init__(*args, **kwargs) + self.loss_type = loss_type + self.lambda_kl = lambda_kl + self.lambda_ssim = lambda_ssim + self.lambda_lpips = lambda_lpips + self.lambda_render = lambda_render + self.camera_randomization_config = camera_randomization_config + + self.renderer = MeshRenderer({'near': 1, 'far': 3, 'resolution': render_resolution}, device=self.device) + + def prepare_dataloader(self, **kwargs): + """ + Prepare dataloader. + """ + self.data_sampler = BalancedResumableSampler( + self.dataset, + shuffle=True, + batch_size=self.batch_size_per_gpu, + ) + self.dataloader = DataLoader( + self.dataset, + batch_size=self.batch_size_per_gpu, + num_workers=int(np.ceil(os.cpu_count() / torch.cuda.device_count())), + pin_memory=True, + drop_last=True, + persistent_workers=True, + collate_fn=functools.partial(self.dataset.collate_fn, split_size=self.batch_split), + sampler=self.data_sampler, + ) + self.data_iterator = cycle(self.dataloader) + + def _randomize_camera(self, num_samples: int): + # sample radius and fov + r_min, r_max = self.camera_randomization_config['radius_range'] + k_min = 1 / r_max**2 + k_max = 1 / r_min**2 + ks = torch.rand(num_samples, device=self.device) * (k_max - k_min) + k_min + radius = 1 / torch.sqrt(ks) + fov = 2 * torch.arcsin(0.5 / radius) + origin = radius.unsqueeze(-1) * F.normalize(torch.randn(num_samples, 3, device=self.device), dim=-1) + + # build camera + extrinsics = utils3d.torch.extrinsics_look_at(origin, torch.zeros_like(origin), torch.tensor([0, 0, 1], dtype=torch.float32, device=self.device)) + intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + near = [np.random.uniform(r - 1, r) for r in radius.tolist()] + + return { + 'extrinsics': extrinsics, + 'intrinsics': intrinsics, + 'near': near, + } + + def _render_batch(self, reps: List[Mesh], extrinsics: torch.Tensor, intrinsics: torch.Tensor, near: List, + ) -> Dict[str, torch.Tensor]: + """ + Render a batch of representations. + + Args: + reps: The dictionary of lists of representations. + extrinsics: The [N x 4 x 4] tensor of extrinsics. + intrinsics: The [N x 3 x 3] tensor of intrinsics. + + Returns: + a dict with + base_color : [N x 3 x H x W] tensor of base color. + metallic : [N x 1 x H x W] tensor of metallic. + roughness : [N x 1 x H x W] tensor of roughness. + alpha : [N x 1 x H x W] tensor of alpha. + """ + ret = {k : [] for k in ['base_color', 'metallic', 'roughness', 'alpha']} + for i, rep in enumerate(reps): + self.renderer.rendering_options['near'] = near[i] + self.renderer.rendering_options['far'] = near[i] + 2 + out_dict = self.renderer.render(rep, extrinsics[i], intrinsics[i], return_types=['attr']) + for k in out_dict: + ret[k].append(out_dict[k]) + for k in ret: + ret[k] = torch.stack(ret[k]) + return ret + + def training_losses( + self, + x: sp.SparseTensor, + mesh: List[MeshWithPbrMaterial] = None, + **kwargs + ) -> Tuple[Dict, Dict]: + """ + Compute training losses. + + Args: + x (SparseTensor): Input sparse tensor for pbr materials. + mesh (List[MeshWithPbrMaterial]): The list of meshes with PBR materials. + + Returns: + a dict with the key "loss" containing a scalar tensor. + may also contain other keys for different terms. + + """ + z, mean, logvar = self.training_models['encoder'](x, sample_posterior=True, return_raw=True) + y = self.training_models['decoder'](z) + + terms = edict(loss = 0.0) + + # direct regression + if self.loss_type == 'l1': + terms["l1"] = l1_loss(x.feats, y.feats) + terms["loss"] = terms["loss"] + terms["l1"] + elif self.loss_type == 'l2': + terms["l2"] = l2_loss(x.feats, y.feats) + terms["loss"] = terms["loss"] + terms["l2"] + else: + raise ValueError(f'Invalid loss type {self.loss_type}') + + # rendering loss + if self.lambda_render != 0.0: + recon = [MeshWithVoxel( + m.vertices, + m.faces, + [-0.5, -0.5, -0.5], + 1 / self.dataset.resolution, + v.coords[:, 1:], + v.feats * 0.5 + 0.5, + torch.Size([*v.shape, *v.spatial_shape]), + layout={ + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + ) for m, v in zip(mesh, y)] + cameras = self._randomize_camera(len(mesh)) + gt_renders = self._render_batch(mesh, **cameras) + pred_renders = self._render_batch(recon, **cameras) + gt_base_color = gt_renders['base_color'] + pred_base_color = pred_renders['base_color'] + gt_mra = torch.cat([gt_renders['metallic'], gt_renders['roughness'], gt_renders['alpha']], dim=1) + pred_mra = torch.cat([pred_renders['metallic'], pred_renders['roughness'], pred_renders['alpha']], dim=1) + terms['render/base_color/ssim'] = 1 - ssim(pred_base_color, gt_base_color) + terms['render/base_color/lpips'] = lpips(pred_base_color, gt_base_color) + terms['render/mra/ssim'] = 1 - ssim(pred_mra, gt_mra) + terms['render/mra/lpips'] = lpips(pred_mra, gt_mra) + terms['loss'] = terms['loss'] + \ + self.lambda_render * (self.lambda_ssim * terms['render/base_color/ssim'] + self.lambda_lpips * terms['render/base_color/lpips'] + \ + self.lambda_ssim * terms['render/mra/ssim'] + self.lambda_lpips * terms['render/mra/lpips']) + + # KL regularization + terms["kl"] = 0.5 * torch.mean(mean.pow(2) + logvar.exp() - logvar - 1) + terms["loss"] = terms["loss"] + self.lambda_kl * terms["kl"] + + return terms, {} + + @torch.no_grad() + def run_snapshot( + self, + num_samples: int, + batch_size: int, + verbose: bool = False, + ) -> Dict: + dataloader = DataLoader( + copy.deepcopy(self.dataset), + batch_size=batch_size, + shuffle=True, + num_workers=1, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + ) + dataloader.dataset.with_mesh = True + + # inference + gts = [] + recons = [] + self.models['encoder'].eval() + self.models['decoder'].eval() + for i in range(0, num_samples, batch_size): + batch = min(batch_size, num_samples - i) + data = next(iter(dataloader)) + args = {k: v[:batch] for k, v in data.items()} + args = recursive_to_device(args, self.device) + z = self.models['encoder'](args['x']) + y = self.models['decoder'](z) + gts.extend(args['mesh']) + recons.extend([MeshWithVoxel( + m.vertices, + m.faces, + [-0.5, -0.5, -0.5], + 1 / self.dataset.resolution, + v.coords[:, 1:], + v.feats * 0.5 + 0.5, + torch.Size([*v.shape, *v.spatial_shape]), + layout={ + 'base_color': slice(0, 3), + 'metallic': slice(3, 4), + 'roughness': slice(4, 5), + 'alpha': slice(5, 6), + } + ) for m, v in zip(args['mesh'], y)]) + self.models['encoder'].train() + self.models['decoder'].train() + + cameras = self._randomize_camera(num_samples) + gt_renders = self._render_batch(gts, **cameras) + pred_renders = self._render_batch(recons, **cameras) + + sample_dict = { + 'gt_base_color': {'value': gt_renders['base_color'] * 2 - 1, 'type': 'image'}, + 'pred_base_color': {'value': pred_renders['base_color'] * 2 - 1, 'type': 'image'}, + 'gt_mra': {'value': torch.cat([gt_renders['metallic'], gt_renders['roughness'], gt_renders['alpha']], dim=1) * 2 - 1, 'type': 'image'}, + 'pred_mra': {'value': torch.cat([pred_renders['metallic'], pred_renders['roughness'], pred_renders['alpha']], dim=1) * 2 - 1, 'type': 'image'}, + } + + return sample_dict diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/shape_vae.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/shape_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..f9441fabd0d9629f69e540f9b627e67950e56f48 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/shape_vae.py @@ -0,0 +1,266 @@ +from typing import * +import os +import copy +import functools +import numpy as np +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader +import utils3d +from easydict import EasyDict as edict + +from ..basic import BasicTrainer +from ...modules import sparse as sp +from ...renderers import MeshRenderer +from ...representations import Mesh +from ...utils.data_utils import recursive_to_device, cycle, BalancedResumableSampler +from ...utils.loss_utils import l1_loss, ssim, lpips + + +class ShapeVaeTrainer(BasicTrainer): + """ + Trainer for Shape VAE + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + lambda_subdiv (float): Subdivision loss weight. + lambda_intersected (float): Intersected loss weight. + lambda_vertice (float): Vertice loss weight. + lambda_kl (float): KL loss weight. + lambda_ssim (float): SSIM loss weight. + lambda_lpips (float): LPIPS loss weight. + """ + + def __init__( + self, + *args, + lambda_subdiv: float = 0.1, + lambda_intersected: float = 0.1, + lambda_vertice: float = 1e-2, + lambda_mask: float = 1, + lambda_depth: float = 10, + lambda_normal: float = 1, + lambda_kl: float = 1e-6, + lambda_ssim: float = 0.2, + lambda_lpips: float = 0.2, + render_resolution: float = 1024, + camera_randomization_config: dict = { + 'radius_range': [2, 100], + }, + **kwargs + ): + super().__init__(*args, **kwargs) + self.lambda_subdiv = lambda_subdiv + self.lambda_intersected = lambda_intersected + self.lambda_mask = lambda_mask + self.lambda_vertice = lambda_vertice + self.lambda_depth = lambda_depth + self.lambda_normal = lambda_normal + self.lambda_kl = lambda_kl + self.lambda_ssim = lambda_ssim + self.lambda_lpips = lambda_lpips + self.camera_randomization_config = camera_randomization_config + + self.renderer = MeshRenderer({'near': 1, 'far': 3, 'resolution': render_resolution}, device=self.device) + + def prepare_dataloader(self, **kwargs): + """ + Prepare dataloader. + """ + self.data_sampler = BalancedResumableSampler( + self.dataset, + shuffle=True, + batch_size=self.batch_size_per_gpu, + ) + self.dataloader = DataLoader( + self.dataset, + batch_size=self.batch_size_per_gpu, + num_workers=int(np.ceil(os.cpu_count() / torch.cuda.device_count())), + pin_memory=True, + drop_last=True, + persistent_workers=True, + collate_fn=functools.partial(self.dataset.collate_fn, split_size=self.batch_split), + sampler=self.data_sampler, + ) + self.data_iterator = cycle(self.dataloader) + + def _randomize_camera(self, num_samples: int): + # sample radius and fov + r_min, r_max = self.camera_randomization_config['radius_range'] + k_min = 1 / r_max**2 + k_max = 1 / r_min**2 + ks = torch.rand(num_samples, device=self.device) * (k_max - k_min) + k_min + radius = 1 / torch.sqrt(ks) + fov = 2 * torch.arcsin(0.5 / radius) + origin = radius.unsqueeze(-1) * F.normalize(torch.randn(num_samples, 3, device=self.device), dim=-1) + + # build camera + extrinsics = utils3d.torch.extrinsics_look_at(origin, torch.zeros_like(origin), torch.tensor([0, 0, 1], dtype=torch.float32, device=self.device)) + intrinsics = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + near = [np.random.uniform(r - 1, r) for r in radius.tolist()] + + return { + 'extrinsics': extrinsics, + 'intrinsics': intrinsics, + 'near': near, + } + + def _render_batch(self, reps: List[Mesh], extrinsics: torch.Tensor, intrinsics: torch.Tensor, near: List, + return_types=['mask', 'normal', 'depth']) -> Dict[str, torch.Tensor]: + """ + Render a batch of representations. + + Args: + reps: The dictionary of lists of representations. + extrinsics: The [N x 4 x 4] tensor of extrinsics. + intrinsics: The [N x 3 x 3] tensor of intrinsics. + return_types: vary in ['mask', 'normal', 'depth', 'normal_map', 'color'] + + Returns: + a dict with + mask : [N x 1 x H x W] tensor of rendered masks + normal : [N x 3 x H x W] tensor of rendered normals + depth : [N x 1 x H x W] tensor of rendered depths + """ + ret = {k : [] for k in return_types} + for i, rep in enumerate(reps): + self.renderer.rendering_options['near'] = near[i] + self.renderer.rendering_options['far'] = near[i] + 2 + out_dict = self.renderer.render(rep, extrinsics[i], intrinsics[i], return_types=return_types) + for k in out_dict: + ret[k].append(out_dict[k][None] if k in ['mask', 'depth'] else out_dict[k]) + for k in ret: + ret[k] = torch.stack(ret[k]) + return ret + + def training_losses( + self, + vertices: sp.SparseTensor, + intersected: sp.SparseTensor, + mesh: List[Mesh], + ) -> Tuple[Dict, Dict]: + """ + Compute training losses. + + Args: + vertices (SparseTensor): vertices of each active voxel + intersected (SparseTensor): intersected flag of each active voxel + mesh (List[Mesh]): the list of meshes to render + + Returns: + a dict with the key "loss" containing a scalar tensor. + may also contain other keys for different terms. + """ + z, mean, logvar = self.training_models['encoder'](vertices, intersected, sample_posterior=True, return_raw=True) + recon, pred_vertice, pred_intersected, subs_gt, subs = self.training_models['decoder'](z, intersected) + + terms = edict(loss = 0.0) + + # direct regression + if self.lambda_intersected > 0: + terms["direct/intersected"] = F.binary_cross_entropy_with_logits(pred_intersected.feats.flatten(), intersected.feats.flatten().float()) + terms["loss"] = terms["loss"] + self.lambda_intersected * terms["direct/intersected"] + if self.lambda_vertice > 0: + terms["direct/vertice"] = F.mse_loss(pred_vertice.feats, vertices.feats) + terms["loss"] = terms["loss"] + self.lambda_vertice * terms["direct/vertice"] + + # subdivision prediction loss + for i, (sub_gt, sub) in enumerate(zip(subs_gt, subs)): + terms[f"bce_sub{i}"] = F.binary_cross_entropy_with_logits(sub.feats, sub_gt.float()) + terms["loss"] = terms["loss"] + self.lambda_subdiv * terms[f"bce_sub{i}"] + + # rendering loss + cameras = self._randomize_camera(len(mesh)) + gt_renders = self._render_batch(mesh, **cameras, return_types=['mask', 'normal', 'depth']) + pred_renders = self._render_batch(recon, **cameras, return_types=['mask', 'normal', 'depth']) + terms['render/mask'] = l1_loss(pred_renders['mask'], gt_renders['mask']) + terms['render/depth'] = l1_loss(pred_renders['depth'], gt_renders['depth']) + terms['render/normal/l1'] = l1_loss(pred_renders['normal'], gt_renders['normal']) + terms['render/normal/ssim'] = 1 - ssim(pred_renders['normal'], gt_renders['normal']) + terms['render/normal/lpips'] = lpips(pred_renders['normal'], gt_renders['normal']) + terms['loss'] = terms['loss'] + \ + self.lambda_mask * terms['render/mask'] + \ + self.lambda_depth * terms['render/depth'] + \ + self.lambda_normal * (terms['render/normal/l1'] + self.lambda_ssim * terms['render/normal/ssim'] + self.lambda_lpips * terms['render/normal/lpips']) + + # KL regularization + terms["kl"] = 0.5 * torch.mean(mean.pow(2) + logvar.exp() - logvar - 1) + terms["loss"] = terms["loss"] + self.lambda_kl * terms["kl"] + + return terms, {} + + @torch.no_grad() + def run_snapshot( + self, + num_samples: int, + batch_size: int, + verbose: bool = False, + ) -> Dict: + dataloader = DataLoader( + copy.deepcopy(self.dataset), + batch_size=batch_size, + shuffle=True, + num_workers=1, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + ) + + # inference + gts = [] + recons = [] + recons2 = [] + self.models['encoder'].eval() + for i in range(0, num_samples, batch_size): + batch = min(batch_size, num_samples - i) + data = next(iter(dataloader)) + args = {k: v[:batch] for k, v in data.items()} + args = recursive_to_device(args, self.device) + z = self.models['encoder'](args['vertices'], args['intersected']) + self.models['decoder'].train() + y = self.models['decoder'](z, args['intersected'])[0] + z.clear_spatial_cache() + self.models['decoder'].eval() + y2 = self.models['decoder'](z) + gts.extend(args['mesh']) + recons.extend(y) + recons2.extend(y2) + self.models['encoder'].train() + self.models['decoder'].train() + + cameras = self._randomize_camera(num_samples) + gt_renders = self._render_batch(gts, **cameras, return_types=['normal']) + recons_renders = self._render_batch(recons, **cameras, return_types=['normal']) + recons2_renders = self._render_batch(recons2, **cameras, return_types=['normal']) + + sample_dict = { + 'gt': {'value': gt_renders['normal'], 'type': 'image'}, + 'rec': {'value': recons_renders['normal'], 'type': 'image'}, + 'rec2': {'value': recons2_renders['normal'], 'type': 'image'}, + } + + return sample_dict diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/sparse_structure_vae.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/sparse_structure_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..5563641c2423b578a487fe98e22f09abf2524202 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/trainers/vae/sparse_structure_vae.py @@ -0,0 +1,130 @@ +from typing import * +import copy +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader +from easydict import EasyDict as edict + +from ..basic import BasicTrainer + + +class SparseStructureVaeTrainer(BasicTrainer): + """ + Trainer for Sparse Structure VAE. + + Args: + models (dict[str, nn.Module]): Models to train. + dataset (torch.utils.data.Dataset): Dataset. + output_dir (str): Output directory. + load_dir (str): Load directory. + step (int): Step to load. + batch_size (int): Batch size. + batch_size_per_gpu (int): Batch size per GPU. If specified, batch_size will be ignored. + batch_split (int): Split batch with gradient accumulation. + max_steps (int): Max steps. + optimizer (dict): Optimizer config. + lr_scheduler (dict): Learning rate scheduler config. + elastic (dict): Elastic memory management config. + grad_clip (float or dict): Gradient clip config. + ema_rate (float or list): Exponential moving average rates. + fp16_mode (str): FP16 mode. + - None: No FP16. + - 'inflat_all': Hold a inflated fp32 master param for all params. + - 'amp': Automatic mixed precision. + fp16_scale_growth (float): Scale growth for FP16 gradient backpropagation. + finetune_ckpt (dict): Finetune checkpoint. + log_param_stats (bool): Log parameter stats. + i_print (int): Print interval. + i_log (int): Log interval. + i_sample (int): Sample interval. + i_save (int): Save interval. + i_ddpcheck (int): DDP check interval. + + loss_type (str): Loss type. 'bce' for binary cross entropy, 'l1' for L1 loss, 'dice' for Dice loss. + lambda_kl (float): KL divergence loss weight. + """ + + def __init__( + self, + *args, + loss_type='bce', + lambda_kl=1e-6, + **kwargs + ): + super().__init__(*args, **kwargs) + self.loss_type = loss_type + self.lambda_kl = lambda_kl + + def training_losses( + self, + ss: torch.Tensor, + **kwargs + ) -> Tuple[Dict, Dict]: + """ + Compute training losses. + + Args: + ss: The [N x 1 x H x W x D] tensor of binary sparse structure. + + Returns: + a dict with the key "loss" containing a scalar tensor. + may also contain other keys for different terms. + """ + z, mean, logvar = self.training_models['encoder'](ss.float(), sample_posterior=True, return_raw=True) + logits = self.training_models['decoder'](z) + + terms = edict(loss = 0.0) + if self.loss_type == 'bce': + terms["bce"] = F.binary_cross_entropy_with_logits(logits, ss.float(), reduction='mean') + terms["loss"] = terms["loss"] + terms["bce"] + elif self.loss_type == 'l1': + terms["l1"] = F.l1_loss(F.sigmoid(logits), ss.float(), reduction='mean') + terms["loss"] = terms["loss"] + terms["l1"] + elif self.loss_type == 'dice': + logits = F.sigmoid(logits) + terms["dice"] = 1 - (2 * (logits * ss.float()).sum() + 1) / (logits.sum() + ss.float().sum() + 1) + terms["loss"] = terms["loss"] + terms["dice"] + else: + raise ValueError(f'Invalid loss type {self.loss_type}') + terms["kl"] = 0.5 * torch.mean(mean.pow(2) + logvar.exp() - logvar - 1) + terms["loss"] = terms["loss"] + self.lamda_kl * terms["kl"] + + return terms, {} + + @torch.no_grad() + def snapshot(self, suffix=None, num_samples=64, batch_size=1, verbose=False): + super().snapshot(suffix=suffix, num_samples=num_samples, batch_size=batch_size, verbose=verbose) + + @torch.no_grad() + def run_snapshot( + self, + num_samples: int, + batch_size: int, + verbose: bool = False, + ) -> Dict: + dataloader = DataLoader( + copy.deepcopy(self.dataset), + batch_size=batch_size, + shuffle=True, + num_workers=0, + collate_fn=self.dataset.collate_fn if hasattr(self.dataset, 'collate_fn') else None, + ) + + # inference + gts = [] + recons = [] + for i in range(0, num_samples, batch_size): + batch = min(batch_size, num_samples - i) + data = next(iter(dataloader)) + args = {k: v[:batch].cuda() if isinstance(v, torch.Tensor) else v[:batch] for k, v in data.items()} + z = self.models['encoder'](args['ss'].float(), sample_posterior=False) + logits = self.models['decoder'](z) + recon = (logits > 0).long() + gts.append(args['ss']) + recons.append(recon) + + sample_dict = { + 'gt': {'value': torch.cat(gts, dim=0), 'type': 'sample'}, + 'recon': {'value': torch.cat(recons, dim=0), 'type': 'sample'}, + } + return sample_dict diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/__init__.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/data_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..805b6cc118106857e7ef767ab4bfd133dbd78e6f --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/data_utils.py @@ -0,0 +1,226 @@ +from typing import * +import math +import torch +import numpy as np +from torch.utils.data import Sampler, Dataset, DataLoader, DistributedSampler +import torch.distributed as dist + + +def recursive_to_device( + data: Any, + device: torch.device, + non_blocking: bool = False, +) -> Any: + """ + Recursively move all tensors in a data structure to a device. + """ + if hasattr(data, "to"): + return data.to(device, non_blocking=non_blocking) + elif isinstance(data, (list, tuple)): + return type(data)(recursive_to_device(d, device, non_blocking) for d in data) + elif isinstance(data, dict): + return {k: recursive_to_device(v, device, non_blocking) for k, v in data.items()} + else: + return data + + +def load_balanced_group_indices( + load: List[int], + num_groups: int, + equal_size: bool = False, +) -> List[List[int]]: + """ + Split indices into groups with balanced load. + """ + if equal_size: + group_size = len(load) // num_groups + indices = np.argsort(load)[::-1] + groups = [[] for _ in range(num_groups)] + group_load = np.zeros(num_groups) + for idx in indices: + min_group_idx = np.argmin(group_load) + groups[min_group_idx].append(idx) + if equal_size and len(groups[min_group_idx]) == group_size: + group_load[min_group_idx] = float('inf') + else: + group_load[min_group_idx] += load[idx] + return groups + + +def cycle(data_loader: DataLoader) -> Iterator: + while True: + for data in data_loader: + if isinstance(data_loader.sampler, ResumableSampler): + data_loader.sampler.idx += data_loader.batch_size # type: ignore[attr-defined] + yield data + if isinstance(data_loader.sampler, DistributedSampler): + data_loader.sampler.epoch += 1 + if isinstance(data_loader.sampler, ResumableSampler): + data_loader.sampler.epoch += 1 + data_loader.sampler.idx = 0 + + +class ResumableSampler(Sampler): + """ + Distributed sampler that is resumable. + + Args: + dataset: Dataset used for sampling. + rank (int, optional): Rank of the current process within :attr:`num_replicas`. + By default, :attr:`rank` is retrieved from the current distributed + group. + shuffle (bool, optional): If ``True`` (default), sampler will shuffle the + indices. + seed (int, optional): random seed used to shuffle the sampler if + :attr:`shuffle=True`. This number should be identical across all + processes in the distributed group. Default: ``0``. + drop_last (bool, optional): if ``True``, then the sampler will drop the + tail of the data to make it evenly divisible across the number of + replicas. If ``False``, the sampler will add extra indices to make + the data evenly divisible across the replicas. Default: ``False``. + """ + + def __init__( + self, + dataset: Dataset, + shuffle: bool = True, + seed: int = 0, + drop_last: bool = False, + ) -> None: + self.dataset = dataset + self.epoch = 0 + self.idx = 0 + self.drop_last = drop_last + self.world_size = dist.get_world_size() if dist.is_initialized() else 1 + self.rank = dist.get_rank() if dist.is_initialized() else 0 + # If the dataset length is evenly divisible by # of replicas, then there + # is no need to drop any data, since the dataset will be split equally. + if self.drop_last and len(self.dataset) % self.world_size != 0: # type: ignore[arg-type] + # Split to nearest available length that is evenly divisible. + # This is to ensure each rank receives the same amount of data when + # using this Sampler. + self.num_samples = math.ceil( + (len(self.dataset) - self.world_size) / self.world_size # type: ignore[arg-type] + ) + else: + self.num_samples = math.ceil(len(self.dataset) / self.world_size) # type: ignore[arg-type] + self.total_size = self.num_samples * self.world_size + self.shuffle = shuffle + self.seed = seed + + def __iter__(self) -> Iterator: + if self.shuffle: + # deterministically shuffle based on epoch and seed + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type] + else: + indices = list(range(len(self.dataset))) # type: ignore[arg-type] + + if not self.drop_last: + # add extra samples to make it evenly divisible + padding_size = self.total_size - len(indices) + if padding_size <= len(indices): + indices += indices[:padding_size] + else: + indices += (indices * math.ceil(padding_size / len(indices)))[ + :padding_size + ] + else: + # remove tail of data to make it evenly divisible. + indices = indices[: self.total_size] + assert len(indices) == self.total_size + + # subsample + indices = indices[self.rank : self.total_size : self.world_size] + + # resume from previous state + indices = indices[self.idx:] + + return iter(indices) + + def __len__(self) -> int: + return self.num_samples + + def state_dict(self) -> dict[str, int]: + return { + 'epoch': self.epoch, + 'idx': self.idx, + } + + def load_state_dict(self, state_dict): + self.epoch = state_dict['epoch'] + self.idx = state_dict['idx'] + + +class BalancedResumableSampler(ResumableSampler): + """ + Distributed sampler that is resumable and balances the load among the processes. + + Args: + dataset: Dataset used for sampling. + rank (int, optional): Rank of the current process within :attr:`num_replicas`. + By default, :attr:`rank` is retrieved from the current distributed + group. + shuffle (bool, optional): If ``True`` (default), sampler will shuffle the + indices. + seed (int, optional): random seed used to shuffle the sampler if + :attr:`shuffle=True`. This number should be identical across all + processes in the distributed group. Default: ``0``. + drop_last (bool, optional): if ``True``, then the sampler will drop the + tail of the data to make it evenly divisible across the number of + replicas. If ``False``, the sampler will add extra indices to make + the data evenly divisible across the replicas. Default: ``False``. + """ + + def __init__( + self, + dataset: Dataset, + shuffle: bool = True, + seed: int = 0, + drop_last: bool = False, + batch_size: int = 1, + ) -> None: + assert hasattr(dataset, 'loads'), 'Dataset must have "loads" attribute to use BalancedResumableSampler' + super().__init__(dataset, shuffle, seed, drop_last) + self.batch_size = batch_size + self.loads = dataset.loads + + def __iter__(self) -> Iterator: + if self.shuffle: + # deterministically shuffle based on epoch and seed + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type] + else: + indices = list(range(len(self.dataset))) # type: ignore[arg-type] + + if not self.drop_last: + # add extra samples to make it evenly divisible + padding_size = self.total_size - len(indices) + if padding_size <= len(indices): + indices += indices[:padding_size] + else: + indices += (indices * math.ceil(padding_size / len(indices)))[ + :padding_size + ] + else: + # remove tail of data to make it evenly divisible. + indices = indices[: self.total_size] + assert len(indices) == self.total_size + + # balance load among processes + num_batches = len(indices) // (self.batch_size * self.world_size) + balanced_indices = [] + for i in range(num_batches): + start_idx = i * self.batch_size * self.world_size + end_idx = (i + 1) * self.batch_size * self.world_size + batch_indices = indices[start_idx:end_idx] + batch_loads = [self.loads[idx] for idx in batch_indices] + groups = load_balanced_group_indices(batch_loads, self.world_size, equal_size=True) + balanced_indices.extend([batch_indices[j] for j in groups[self.rank]]) + + # resume from previous state + indices = balanced_indices[self.idx:] + + return iter(indices) diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/dist_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..348799c064804ed3ae1a98144249bd9b6bfb9915 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/dist_utils.py @@ -0,0 +1,93 @@ +import os +import io +from contextlib import contextmanager +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel as DDP + + +def setup_dist(rank, local_rank, world_size, master_addr, master_port): + os.environ['MASTER_ADDR'] = master_addr + os.environ['MASTER_PORT'] = master_port + os.environ['WORLD_SIZE'] = str(world_size) + os.environ['RANK'] = str(rank) + os.environ['LOCAL_RANK'] = str(local_rank) + torch.cuda.set_device(local_rank) + dist.init_process_group('nccl', rank=rank, world_size=world_size) + + +def read_file_dist(path): + """ + Read the binary file distributedly. + File is only read once by the rank 0 process and broadcasted to other processes. + + Returns: + data (io.BytesIO): The binary data read from the file. + """ + if dist.is_initialized() and dist.get_world_size() > 1: + # read file + size = torch.LongTensor(1).cuda() + if dist.get_rank() == 0: + with open(path, 'rb') as f: + data = f.read() + data = torch.ByteTensor( + torch.UntypedStorage.from_buffer(data, dtype=torch.uint8) + ).cuda() + size[0] = data.shape[0] + # broadcast size + dist.broadcast(size, src=0) + if dist.get_rank() != 0: + data = torch.ByteTensor(size[0].item()).cuda() + # broadcast data + dist.broadcast(data, src=0) + # convert to io.BytesIO + data = data.cpu().numpy().tobytes() + data = io.BytesIO(data) + return data + else: + with open(path, 'rb') as f: + data = f.read() + data = io.BytesIO(data) + return data + + +def unwrap_dist(model): + """ + Unwrap the model from distributed training. + """ + if isinstance(model, DDP): + return model.module + return model + + +@contextmanager +def master_first(): + """ + A context manager that ensures master process executes first. + """ + if not dist.is_initialized(): + yield + else: + if dist.get_rank() == 0: + yield + dist.barrier() + else: + dist.barrier() + yield + + +@contextmanager +def local_master_first(): + """ + A context manager that ensures local master process executes first. + """ + if not dist.is_initialized(): + yield + else: + if dist.get_rank() % torch.cuda.device_count() == 0: + yield + dist.barrier() + else: + dist.barrier() + yield + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/elastic_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/elastic_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cba3cf83836e5b58f5bc3333e809ffc932375a04 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/elastic_utils.py @@ -0,0 +1,228 @@ +from abc import abstractmethod +from contextlib import contextmanager +from typing import Tuple +import torch +import torch.nn as nn +import numpy as np + + +class MemoryController: + """ + Base class for memory management during training. + """ + + _last_input_size = None + _last_mem_ratio = [] + + @contextmanager + def record(self): + pass + + def update_run_states(self, input_size=None, mem_ratio=None): + if self._last_input_size is None: + self._last_input_size = input_size + elif self._last_input_size!= input_size: + raise ValueError(f'Input size should not change for different ElasticModules.') + self._last_mem_ratio.append(mem_ratio) + + @abstractmethod + def get_mem_ratio(self, input_size): + pass + + @abstractmethod + def state_dict(self): + pass + + @abstractmethod + def log(self): + pass + + +class LinearMemoryController(MemoryController): + """ + A simple controller for memory management during training. + The memory usage is modeled as a linear function of: + - the number of input parameters + - the ratio of memory the model use compared to the maximum usage (with no checkpointing) + memory_usage = k * input_size * mem_ratio + b + The controller keeps track of the memory usage and gives the + expected memory ratio to keep the memory usage under a target + """ + def __init__( + self, + buffer_size=1000, + update_every=500, + target_ratio=0.8, + available_memory=None, + max_mem_ratio_start=0.1, + params=None, + device=None + ): + self.buffer_size = buffer_size + self.update_every = update_every + self.target_ratio = target_ratio + self.device = device or torch.cuda.current_device() + self.available_memory = available_memory or torch.cuda.get_device_properties(self.device).total_memory / 1024**3 + + self._memory = np.zeros(buffer_size, dtype=np.float32) + self._input_size = np.zeros(buffer_size, dtype=np.float32) + self._mem_ratio = np.zeros(buffer_size, dtype=np.float32) + self._buffer_ptr = 0 + self._buffer_length = 0 + self._params = tuple(params) if params is not None else (0.0, 0.0) + self._max_mem_ratio = max_mem_ratio_start + self.step = 0 + + def __repr__(self): + return f'LinearMemoryController(target_ratio={self.target_ratio}, available_memory={self.available_memory})' + + def _add_sample(self, memory, input_size, mem_ratio): + self._memory[self._buffer_ptr] = memory + self._input_size[self._buffer_ptr] = input_size + self._mem_ratio[self._buffer_ptr] = mem_ratio + self._buffer_ptr = (self._buffer_ptr + 1) % self.buffer_size + self._buffer_length = min(self._buffer_length + 1, self.buffer_size) + + @contextmanager + def record(self): + torch.cuda.reset_peak_memory_stats(self.device) + self._last_input_size = None + self._last_mem_ratio = [] + yield + self._last_memory = torch.cuda.max_memory_allocated(self.device) / 1024**3 + self._last_mem_ratio = sum(self._last_mem_ratio) / len(self._last_mem_ratio) + self._add_sample(self._last_memory, self._last_input_size, self._last_mem_ratio) + self.step += 1 + if self.step % self.update_every == 0: + self._max_mem_ratio = min(1.0, self._max_mem_ratio + 0.1) + self._fit_params() + + def _fit_params(self): + memory_usage = self._memory[:self._buffer_length] + input_size = self._input_size[:self._buffer_length] + mem_ratio = self._mem_ratio[:self._buffer_length] + + x = input_size * mem_ratio + y = memory_usage + k, b = np.polyfit(x, y, 1) + self._params = (k, b) + # self._visualize() + + def _visualize(self): + import matplotlib.pyplot as plt + memory_usage = self._memory[:self._buffer_length] + input_size = self._input_size[:self._buffer_length] + mem_ratio = self._mem_ratio[:self._buffer_length] + k, b = self._params + + plt.scatter(input_size * mem_ratio, memory_usage, c=mem_ratio, cmap='viridis') + x = np.array([0.0, 20000.0]) + plt.plot(x, k * x + b, c='r') + plt.savefig(f'linear_memory_controller_{self.step}.png') + plt.cla() + + def get_mem_ratio(self, input_size): + k, b = self._params + if k == 0: return np.random.rand() * self._max_mem_ratio + pred = (self.available_memory * self.target_ratio - b) / (k * input_size) + return min(self._max_mem_ratio, max(0.0, pred)) + + def state_dict(self): + return { + 'params': self._params, + } + + def load_state_dict(self, state_dict): + self._params = tuple(state_dict['params']) + + def log(self): + return { + 'params/k': self._params[0], + 'params/b': self._params[1], + 'memory': self._last_memory, + 'input_size': self._last_input_size, + 'mem_ratio': self._last_mem_ratio, + } + + +class ElasticModule(nn.Module): + """ + Module for training with elastic memory management. + """ + def __init__(self): + super().__init__() + self._memory_controller: MemoryController = None + + @abstractmethod + def _get_input_size(self, *args, **kwargs) -> int: + """ + Get the size of the input data. + + Returns: + int: The size of the input data. + """ + pass + + @abstractmethod + def _forward_with_mem_ratio(self, *args, mem_ratio=0.0, **kwargs) -> Tuple[float, Tuple]: + """ + Forward with a given memory ratio. + """ + pass + + def register_memory_controller(self, memory_controller: MemoryController): + self._memory_controller = memory_controller + + def forward(self, *args, **kwargs): + if self._memory_controller is None or not torch.is_grad_enabled() or not self.training: + _, ret = self._forward_with_mem_ratio(*args, **kwargs) + else: + input_size = self._get_input_size(*args, **kwargs) + mem_ratio = self._memory_controller.get_mem_ratio(input_size) + mem_ratio, ret = self._forward_with_mem_ratio(*args, mem_ratio=mem_ratio, **kwargs) + self._memory_controller.update_run_states(input_size, mem_ratio) + return ret + + +class ElasticModuleMixin: + """ + Mixin for training with elastic memory management. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._memory_controller: MemoryController = None + + @abstractmethod + def _get_input_size(self, *args, **kwargs) -> int: + """ + Get the size of the input data. + + Returns: + int: The size of the input data. + """ + pass + + @abstractmethod + @contextmanager + def with_mem_ratio(self, mem_ratio=1.0) -> float: + """ + Context manager for training with a reduced memory ratio compared to the full memory usage. + + Returns: + float: The exact memory ratio used during the forward pass. + """ + pass + + def register_memory_controller(self, memory_controller: MemoryController): + self._memory_controller = memory_controller + + def forward(self, *args, **kwargs): + if self._memory_controller is None or not torch.is_grad_enabled() or not self.training: + ret = super().forward(*args, **kwargs) + else: + input_size = self._get_input_size(*args, **kwargs) + mem_ratio = self._memory_controller.get_mem_ratio(input_size) + with self.with_mem_ratio(mem_ratio) as exact_mem_ratio: + ret = super().forward(*args, **kwargs) + self._memory_controller.update_run_states(input_size, exact_mem_ratio) + return ret diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/general_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/general_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..589c103de8a777aea9994a899f97431cbab5447a --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/general_utils.py @@ -0,0 +1,373 @@ +import re +import numpy as np +import cv2 +import torch +import contextlib + + +# Dictionary utils +def _dict_merge(dicta, dictb, prefix=''): + """ + Merge two dictionaries. + """ + assert isinstance(dicta, dict), 'input must be a dictionary' + assert isinstance(dictb, dict), 'input must be a dictionary' + dict_ = {} + all_keys = set(dicta.keys()).union(set(dictb.keys())) + for key in all_keys: + if key in dicta.keys() and key in dictb.keys(): + if isinstance(dicta[key], dict) and isinstance(dictb[key], dict): + dict_[key] = _dict_merge(dicta[key], dictb[key], prefix=f'{prefix}.{key}') + else: + raise ValueError(f'Duplicate key {prefix}.{key} found in both dictionaries. Types: {type(dicta[key])}, {type(dictb[key])}') + elif key in dicta.keys(): + dict_[key] = dicta[key] + else: + dict_[key] = dictb[key] + return dict_ + + +def dict_merge(dicta, dictb): + """ + Merge two dictionaries. + """ + return _dict_merge(dicta, dictb, prefix='') + + +def dict_foreach(dic, func, special_func={}): + """ + Recursively apply a function to all non-dictionary leaf values in a dictionary. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + for key in dic.keys(): + if isinstance(dic[key], dict): + dic[key] = dict_foreach(dic[key], func) + else: + if key in special_func.keys(): + dic[key] = special_func[key](dic[key]) + else: + dic[key] = func(dic[key]) + return dic + + +def dict_reduce(dicts, func, special_func={}): + """ + Reduce a list of dictionaries. Leaf values must be scalars. + """ + assert isinstance(dicts, list), 'input must be a list of dictionaries' + assert all([isinstance(d, dict) for d in dicts]), 'input must be a list of dictionaries' + assert len(dicts) > 0, 'input must be a non-empty list of dictionaries' + all_keys = set([key for dict_ in dicts for key in dict_.keys()]) + reduced_dict = {} + for key in all_keys: + vlist = [dict_[key] for dict_ in dicts if key in dict_.keys()] + if isinstance(vlist[0], dict): + reduced_dict[key] = dict_reduce(vlist, func, special_func) + else: + if key in special_func.keys(): + reduced_dict[key] = special_func[key](vlist) + else: + reduced_dict[key] = func(vlist) + return reduced_dict + + +def dict_any(dic, func): + """ + Recursively apply a function to all non-dictionary leaf values in a dictionary. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + for key in dic.keys(): + if isinstance(dic[key], dict): + if dict_any(dic[key], func): + return True + else: + if func(dic[key]): + return True + return False + + +def dict_all(dic, func): + """ + Recursively apply a function to all non-dictionary leaf values in a dictionary. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + for key in dic.keys(): + if isinstance(dic[key], dict): + if not dict_all(dic[key], func): + return False + else: + if not func(dic[key]): + return False + return True + + +def dict_flatten(dic, sep='.'): + """ + Flatten a nested dictionary into a dictionary with no nested dictionaries. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + flat_dict = {} + for key in dic.keys(): + if isinstance(dic[key], dict): + sub_dict = dict_flatten(dic[key], sep=sep) + for sub_key in sub_dict.keys(): + flat_dict[str(key) + sep + str(sub_key)] = sub_dict[sub_key] + else: + flat_dict[key] = dic[key] + return flat_dict + + +# Context utils +@contextlib.contextmanager +def nested_contexts(*contexts): + with contextlib.ExitStack() as stack: + for ctx in contexts: + stack.enter_context(ctx()) + yield + + +# Image utils +def make_grid(images, nrow=None, ncol=None, aspect_ratio=None): + num_images = len(images) + if nrow is None and ncol is None: + if aspect_ratio is not None: + nrow = int(np.round(np.sqrt(num_images / aspect_ratio))) + else: + nrow = int(np.sqrt(num_images)) + ncol = (num_images + nrow - 1) // nrow + elif nrow is None and ncol is not None: + nrow = (num_images + ncol - 1) // ncol + elif nrow is not None and ncol is None: + ncol = (num_images + nrow - 1) // nrow + else: + assert nrow * ncol >= num_images, 'nrow * ncol must be greater than or equal to the number of images' + + if images[0].ndim == 2: + grid = np.zeros((nrow * images[0].shape[0], ncol * images[0].shape[1]), dtype=images[0].dtype) + else: + grid = np.zeros((nrow * images[0].shape[0], ncol * images[0].shape[1], images[0].shape[2]), dtype=images[0].dtype) + for i, img in enumerate(images): + row = i // ncol + col = i % ncol + grid[row * img.shape[0]:(row + 1) * img.shape[0], col * img.shape[1]:(col + 1) * img.shape[1]] = img + return grid + + +def notes_on_image(img, notes=None): + img = np.pad(img, ((0, 32), (0, 0), (0, 0)), 'constant', constant_values=0) + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + if notes is not None: + img = cv2.putText(img, notes, (0, img.shape[0] - 4), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + return img + + + +def text_image(text, resolution=(512, 512), max_size=0.5, h_align="left", v_align="center"): + """ + Draw text on an image of the given resolution. The text is automatically wrapped + and scaled so that it fits completely within the image while preserving any explicit + line breaks and original spacing. Horizontal and vertical alignment can be controlled + via flags. + + Parameters: + text (str): The input text. Newline characters and spacing are preserved. + resolution (tuple): The image resolution as (width, height). + max_size (float): The maximum font size. + h_align (str): Horizontal alignment. Options: "left", "center", "right". + v_align (str): Vertical alignment. Options: "top", "center", "bottom". + + Returns: + numpy.ndarray: The resulting image (BGR format) with the text drawn. + """ + width, height = resolution + # Create a white background image + img = np.full((height, width, 3), 255, dtype=np.uint8) + + # Set margins and compute available drawing area + margin = 10 + avail_width = width - 2 * margin + avail_height = height - 2 * margin + + # Choose OpenCV font and text thickness + font = cv2.FONT_HERSHEY_SIMPLEX + thickness = 1 + # Ratio for additional spacing between lines (relative to the height of "A") + line_spacing_ratio = 0.5 + + def wrap_line(line, max_width, font, thickness, scale): + """ + Wrap a single line of text into multiple lines such that each line's + width (measured at the given scale) does not exceed max_width. + This function preserves the original spacing by splitting the line into tokens + (words and whitespace) using a regular expression. + + Parameters: + line (str): The input text line. + max_width (int): Maximum allowed width in pixels. + font (int): OpenCV font identifier. + thickness (int): Text thickness. + scale (float): The current font scale. + + Returns: + List[str]: A list of wrapped lines. + """ + # Split the line into tokens (words and whitespace), preserving spacing + tokens = re.split(r'(\s+)', line) + if not tokens: + return [''] + + wrapped_lines = [] + current_line = "" + for token in tokens: + candidate = current_line + token + candidate_width = cv2.getTextSize(candidate, font, scale, thickness)[0][0] + if candidate_width <= max_width: + current_line = candidate + else: + # If current_line is empty, the token itself is too wide; + # break the token character by character. + if current_line == "": + sub_token = "" + for char in token: + candidate_char = sub_token + char + if cv2.getTextSize(candidate_char, font, scale, thickness)[0][0] <= max_width: + sub_token = candidate_char + else: + if sub_token: + wrapped_lines.append(sub_token) + sub_token = char + current_line = sub_token + else: + wrapped_lines.append(current_line) + current_line = token + if current_line: + wrapped_lines.append(current_line) + return wrapped_lines + + def compute_text_block(scale): + """ + Wrap the entire text (splitting at explicit newline characters) using the + provided scale, and then compute the overall width and height of the text block. + + Returns: + wrapped_lines (List[str]): The list of wrapped lines. + block_width (int): Maximum width among the wrapped lines. + block_height (int): Total height of the text block including spacing. + sizes (List[tuple]): A list of (width, height) for each wrapped line. + spacing (int): The spacing between lines (computed from the scaled "A" height). + """ + # Split text by explicit newlines + input_lines = text.splitlines() if text else [''] + wrapped_lines = [] + for line in input_lines: + wrapped = wrap_line(line, avail_width, font, thickness, scale) + wrapped_lines.extend(wrapped) + + sizes = [] + for line in wrapped_lines: + (text_size, _) = cv2.getTextSize(line, font, scale, thickness) + sizes.append(text_size) # (width, height) + + block_width = max((w for w, h in sizes), default=0) + # Use the height of "A" (at the current scale) to compute line spacing + base_height = cv2.getTextSize("A", font, scale, thickness)[0][1] + spacing = int(line_spacing_ratio * base_height) + block_height = sum(h for w, h in sizes) + spacing * (len(sizes) - 1) if sizes else 0 + + return wrapped_lines, block_width, block_height, sizes, spacing + + # Use binary search to find the maximum scale that allows the text block to fit + lo = 0.001 + hi = max_size + eps = 0.001 # convergence threshold + best_scale = lo + best_result = None + + while hi - lo > eps: + mid = (lo + hi) / 2 + wrapped_lines, block_width, block_height, sizes, spacing = compute_text_block(mid) + # Ensure that both width and height constraints are met + if block_width <= avail_width and block_height <= avail_height: + best_scale = mid + best_result = (wrapped_lines, block_width, block_height, sizes, spacing) + lo = mid # try a larger scale + else: + hi = mid # reduce the scale + + if best_result is None: + best_scale = 0.5 + best_result = compute_text_block(best_scale) + + wrapped_lines, block_width, block_height, sizes, spacing = best_result + + # Compute starting y-coordinate based on vertical alignment flag + if v_align == "top": + y_top = margin + elif v_align == "center": + y_top = margin + (avail_height - block_height) // 2 + elif v_align == "bottom": + y_top = margin + (avail_height - block_height) + else: + y_top = margin + (avail_height - block_height) // 2 # default to center if invalid flag + + # For cv2.putText, the y coordinate represents the text baseline; + # so for the first line add its height. + y = y_top + (sizes[0][1] if sizes else 0) + + # Draw each line with horizontal alignment based on the flag + for i, line in enumerate(wrapped_lines): + line_width, line_height = sizes[i] + if h_align == "left": + x = margin + elif h_align == "center": + x = margin + (avail_width - line_width) // 2 + elif h_align == "right": + x = margin + (avail_width - line_width) + else: + x = margin # default to left if invalid flag + + cv2.putText(img, line, (x, y), font, best_scale, (0, 0, 0), thickness, cv2.LINE_AA) + y += line_height + spacing + + return img + + +def save_image_with_notes(img, path, notes=None): + """ + Save an image with notes. + """ + if isinstance(img, torch.Tensor): + img = img.cpu().numpy().transpose(1, 2, 0) + if img.dtype == np.float32 or img.dtype == np.float64: + img = np.clip(img * 255, 0, 255).astype(np.uint8) + img = notes_on_image(img, notes) + cv2.imwrite(path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) + + +# debug utils + +def atol(x, y): + """ + Absolute tolerance. + """ + return torch.abs(x - y) + + +def rtol(x, y): + """ + Relative tolerance. + """ + return torch.abs(x - y) / torch.clamp_min(torch.maximum(torch.abs(x), torch.abs(y)), 1e-12) + + +# print utils +def indent(s, n=4): + """ + Indent a string. + """ + lines = s.split('\n') + for i in range(1, len(lines)): + lines[i] = ' ' * n + lines[i] + return '\n'.join(lines) + diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/grad_clip_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/grad_clip_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..990a4352e24fc73bf732d8eb0f8ca9a07365b49e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/grad_clip_utils.py @@ -0,0 +1,81 @@ +from typing import * +import torch +import numpy as np +import torch.utils + + +class AdaptiveGradClipper: + """ + Adaptive gradient clipping for training. + """ + def __init__( + self, + max_norm=None, + clip_percentile=95.0, + buffer_size=1000, + ): + self.max_norm = max_norm + self.clip_percentile = clip_percentile + self.buffer_size = buffer_size + + self._grad_norm = np.zeros(buffer_size, dtype=np.float32) + self._max_norm = max_norm + self._buffer_ptr = 0 + self._buffer_length = 0 + + def __repr__(self): + return f'AdaptiveGradClipper(max_norm={self.max_norm}, clip_percentile={self.clip_percentile})' + + def state_dict(self): + return { + 'grad_norm': self._grad_norm, + 'max_norm': self._max_norm, + 'buffer_ptr': self._buffer_ptr, + 'buffer_length': self._buffer_length, + } + + def load_state_dict(self, state_dict): + self._grad_norm = state_dict['grad_norm'] + self._max_norm = state_dict['max_norm'] + self._buffer_ptr = state_dict['buffer_ptr'] + self._buffer_length = state_dict['buffer_length'] + + def log(self): + return { + 'max_norm': self._max_norm, + } + + def __call__(self, parameters, norm_type=2.0, error_if_nonfinite=False, foreach=None): + """Clip the gradient norm of an iterable of parameters. + + The norm is computed over all gradients together, as if they were + concatenated into a single vector. Gradients are modified in-place. + + Args: + parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a + single Tensor that will have gradients normalized + norm_type (float): type of the used p-norm. Can be ``'inf'`` for + infinity norm. + error_if_nonfinite (bool): if True, an error is thrown if the total + norm of the gradients from :attr:`parameters` is ``nan``, + ``inf``, or ``-inf``. Default: False (will switch to True in the future) + foreach (bool): use the faster foreach-based implementation. + If ``None``, use the foreach implementation for CUDA and CPU native tensors and silently + fall back to the slow implementation for other device types. + Default: ``None`` + + Returns: + Total norm of the parameter gradients (viewed as a single vector). + """ + max_norm = self._max_norm if self._max_norm is not None else float('inf') + grad_norm = torch.nn.utils.clip_grad_norm_(parameters, max_norm=max_norm, norm_type=norm_type, error_if_nonfinite=error_if_nonfinite, foreach=foreach) + + if torch.isfinite(grad_norm): + self._grad_norm[self._buffer_ptr] = grad_norm + self._buffer_ptr = (self._buffer_ptr + 1) % self.buffer_size + self._buffer_length = min(self._buffer_length + 1, self.buffer_size) + if self._buffer_length == self.buffer_size: + self._max_norm = np.percentile(self._grad_norm, self.clip_percentile) + self._max_norm = min(self._max_norm, self.max_norm) if self.max_norm is not None else self._max_norm + + return grad_norm \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/loss_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/loss_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..52049f69543f2700bc5525b09cbf2fb25c08aa9e --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/loss_utils.py @@ -0,0 +1,92 @@ +import torch +import torch.nn.functional as F +from torch.autograd import Variable +from math import exp +from lpips import LPIPS + + +def smooth_l1_loss(pred, target, beta=1.0): + diff = torch.abs(pred - target) + loss = torch.where(diff < beta, 0.5 * diff ** 2 / beta, diff - 0.5 * beta) + return loss.mean() + + +def l1_loss(network_output, gt): + return torch.abs((network_output - gt)).mean() + + +def l2_loss(network_output, gt): + return ((network_output - gt) ** 2).mean() + + +def gaussian(window_size, sigma): + gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)]) + return gauss / gauss.sum() + + +def create_window(window_size, channel): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) + window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous()) + return window + + +def psnr(img1, img2, max_val=1.0): + mse = F.mse_loss(img1, img2) + return 20 * torch.log10(max_val / torch.sqrt(mse)) + + +def ssim(img1, img2, window_size=11, size_average=True): + channel = img1.size(-3) + window = create_window(window_size, channel) + + if img1.is_cuda: + window = window.cuda(img1.get_device()) + window = window.type_as(img1) + + return _ssim(img1, img2, window, window_size, channel, size_average) + +def _ssim(img1, img2, window, window_size, channel, size_average=True): + mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel) + mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq + sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq + sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2 + + C1 = 0.01 ** 2 + C2 = 0.03 ** 2 + + ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) + + if size_average: + return ssim_map.mean() + else: + return ssim_map.mean(1).mean(1).mean(1) + + +loss_fn_vgg = None +def lpips(img1, img2, value_range=(0, 1)): + global loss_fn_vgg + if loss_fn_vgg is None: + loss_fn_vgg = LPIPS(net='vgg').cuda().eval() + # normalize to [-1, 1] + img1 = (img1 - value_range[0]) / (value_range[1] - value_range[0]) * 2 - 1 + img2 = (img2 - value_range[0]) / (value_range[1] - value_range[0]) * 2 - 1 + return loss_fn_vgg(img1, img2).mean() + + +def normal_angle(pred, gt): + pred = pred * 2.0 - 1.0 + gt = gt * 2.0 - 1.0 + norms = pred.norm(dim=-1) * gt.norm(dim=-1) + cos_sim = (pred * gt).sum(-1) / (norms + 1e-9) + cos_sim = torch.clamp(cos_sim, -1.0, 1.0) + ang = torch.rad2deg(torch.acos(cos_sim[norms > 1e-9])).mean() + if ang.isnan(): + return -1 + return ang diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/mesh_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/mesh_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f1451ebd8b89879eee79cc61a6f4161136f245 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/mesh_utils.py @@ -0,0 +1,268 @@ +from typing import Tuple, Dict +import numpy as np +from trimesh import grouping, util, remesh +import struct +import re +from plyfile import PlyData, PlyElement + + +def read_ply(filename): + """ + Read a PLY file and return vertices, triangle faces, and quad faces. + + Args: + filename (str): The file path to read from. + + Returns: + vertices (np.ndarray): Array of shape [N, 3] containing vertex positions. + tris (np.ndarray): Array of shape [M, 3] containing triangle face indices (empty if none). + quads (np.ndarray): Array of shape [K, 4] containing quad face indices (empty if none). + """ + with open(filename, 'rb') as f: + # Read the header until 'end_header' is encountered + header_bytes = b"" + while True: + line = f.readline() + if not line: + raise ValueError("PLY header not found") + header_bytes += line + if b"end_header" in line: + break + header = header_bytes.decode('utf-8') + + # Determine if the file is in ASCII or binary format + is_ascii = "ascii" in header + + # Extract the number of vertices and faces from the header using regex + vertex_match = re.search(r'element vertex (\d+)', header) + if vertex_match: + num_vertices = int(vertex_match.group(1)) + else: + raise ValueError("Vertex count not found in header") + + face_match = re.search(r'element face (\d+)', header) + if face_match: + num_faces = int(face_match.group(1)) + else: + raise ValueError("Face count not found in header") + + vertices = [] + tris = [] + quads = [] + + if is_ascii: + # For ASCII format, read each line of vertex data (each line contains 3 floats) + for _ in range(num_vertices): + line = f.readline().decode('utf-8').strip() + if not line: + continue + parts = line.split() + vertices.append([float(parts[0]), float(parts[1]), float(parts[2])]) + + # Read face data, where the first number indicates the number of vertices for the face + for _ in range(num_faces): + line = f.readline().decode('utf-8').strip() + if not line: + continue + parts = line.split() + count = int(parts[0]) + indices = list(map(int, parts[1:])) + if count == 3: + tris.append(indices) + elif count == 4: + quads.append(indices) + else: + # Skip faces with other numbers of vertices (can be extended as needed) + pass + else: + # For binary format: read directly from the binary stream + # Each vertex consists of 3 floats (12 bytes per vertex) + for _ in range(num_vertices): + data = f.read(12) + if len(data) < 12: + raise ValueError("Insufficient vertex data") + v = struct.unpack(' 0 else np.empty((0, 3), dtype=np.int32) + quads = np.array(quads, dtype=np.int32) if len(quads) > 0 else np.empty((0, 4), dtype=np.int32) + + return vertices, tris, quads + + +def write_ply( + filename: str, + vertices: np.ndarray, + tris: np.ndarray, + quads: np.ndarray, + vertex_colors: np.ndarray = None, + ascii: bool = False +): + """ + Write a mesh to a PLY file, with the option to save in ASCII or binary format, + and optional per-vertex colors. + + Args: + filename (str): The filename to write to. + vertices (np.ndarray): [N, 3] The vertex positions. + tris (np.ndarray): [M, 3] The triangle indices. + quads (np.ndarray): [K, 4] The quad indices. + vertex_colors (np.ndarray, optional): [N, 3] or [N, 4] UInt8 colors for each vertex (RGB or RGBA). + ascii (bool): If True, write in ASCII format; otherwise binary little-endian. + """ + import struct + + num_vertices = len(vertices) + num_faces = len(tris) + len(quads) + + # Build header + header_lines = [ + "ply", + f"format {'ascii 1.0' if ascii else 'binary_little_endian 1.0'}", + f"element vertex {num_vertices}", + "property float x", + "property float y", + "property float z", + ] + + # Add vertex color properties if provided + has_color = vertex_colors is not None + if has_color: + # Expect uint8 values 0-255 + header_lines += [ + "property uchar red", + "property uchar green", + "property uchar blue", + ] + # Include alpha if RGBA + if vertex_colors.shape[1] == 4: + header_lines.append("property uchar alpha") + + header_lines += [ + f"element face {num_faces}", + "property list uchar int vertex_index", + "end_header", + "" + ] + header = "\n".join(header_lines) + + mode = 'w' if ascii else 'wb' + with open(filename, mode) as f: + # Write header + if ascii: + f.write(header) + else: + f.write(header.encode('utf-8')) + + # Write vertex data + for i, v in enumerate(vertices): + if ascii: + line = f"{v[0]} {v[1]} {v[2]}" + if has_color: + col = vertex_colors[i] + line += ' ' + ' '.join(str(int(c)) for c in col) + f.write(line + '\n') + else: + # pack xyz as floats + f.write(struct.pack(' 0: + digit = n % base + val += digit * inv_base_n + n //= base + inv_base_n *= inv_base + return val + +def halton_sequence(dim, n): + return [radical_inverse(PRIMES[dim], n) for dim in range(dim)] + +def hammersley_sequence(dim, n, num_samples): + return [n / num_samples] + halton_sequence(dim - 1, n) + +def sphere_hammersley_sequence(n, num_samples, offset=(0, 0), remap=False): + u, v = hammersley_sequence(2, n, num_samples) + u += offset[0] / num_samples + v += offset[1] + if remap: + u = 2 * u if u < 0.25 else 2 / 3 * u + 1 / 3 + theta = np.arccos(1 - 2 * u) - np.pi / 2 + phi = v * 2 * np.pi + return [phi, theta] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/render_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/render_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d6fb3e9c3b0d826f77ff56d65ccf4adbc247cf0d --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/render_utils.py @@ -0,0 +1,129 @@ +import torch +import numpy as np +from tqdm import tqdm +import utils3d +from PIL import Image + +from ..renderers import MeshRenderer, VoxelRenderer, PbrMeshRenderer +from ..representations import Mesh, Voxel, MeshWithPbrMaterial, MeshWithVoxel +from .random_utils import sphere_hammersley_sequence + + +def yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, rs, fovs): + is_list = isinstance(yaws, list) + if not is_list: + yaws = [yaws] + pitchs = [pitchs] + if not isinstance(rs, list): + rs = [rs] * len(yaws) + if not isinstance(fovs, list): + fovs = [fovs] * len(yaws) + extrinsics = [] + intrinsics = [] + for yaw, pitch, r, fov in zip(yaws, pitchs, rs, fovs): + fov = torch.deg2rad(torch.tensor(float(fov))).cuda() + yaw = torch.tensor(float(yaw)).cuda() + pitch = torch.tensor(float(pitch)).cuda() + orig = torch.tensor([ + torch.sin(yaw) * torch.cos(pitch), + torch.cos(yaw) * torch.cos(pitch), + torch.sin(pitch), + ]).cuda() * r + extr = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda()) + intr = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + extrinsics.append(extr) + intrinsics.append(intr) + if not is_list: + extrinsics = extrinsics[0] + intrinsics = intrinsics[0] + return extrinsics, intrinsics + + +def get_renderer(sample, **kwargs): + if isinstance(sample, (MeshWithPbrMaterial, MeshWithVoxel)): + renderer = PbrMeshRenderer() + renderer.rendering_options.resolution = kwargs.get('resolution', 512) + renderer.rendering_options.near = kwargs.get('near', 1) + renderer.rendering_options.far = kwargs.get('far', 100) + renderer.rendering_options.ssaa = kwargs.get('ssaa', 2) + renderer.rendering_options.peel_layers = kwargs.get('peel_layers', 8) + elif isinstance(sample, Mesh): + renderer = MeshRenderer() + renderer.rendering_options.resolution = kwargs.get('resolution', 512) + renderer.rendering_options.near = kwargs.get('near', 1) + renderer.rendering_options.far = kwargs.get('far', 100) + renderer.rendering_options.ssaa = kwargs.get('ssaa', 2) + renderer.rendering_options.chunk_size = kwargs.get('chunk_size', None) + elif isinstance(sample, Voxel): + renderer = VoxelRenderer() + renderer.rendering_options.resolution = kwargs.get('resolution', 512) + renderer.rendering_options.near = kwargs.get('near', 0.1) + renderer.rendering_options.far = kwargs.get('far', 10.0) + renderer.rendering_options.ssaa = kwargs.get('ssaa', 2) + else: + raise ValueError(f'Unsupported sample type: {type(sample)}') + return renderer + + +def render_frames(sample, extrinsics, intrinsics, options={}, verbose=True, **kwargs): + renderer = get_renderer(sample, **options) + rets = {} + for j, (extr, intr) in tqdm(enumerate(zip(extrinsics, intrinsics)), total=len(extrinsics), desc='Rendering', disable=not verbose): + res = renderer.render(sample, extr, intr, **kwargs) + for k, v in res.items(): + if k not in rets: rets[k] = [] + if v.dim() == 2: v = v[None].repeat(3, 1, 1) + rets[k].append(np.clip(v.detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255).astype(np.uint8)) + return rets + + +def render_video(sample, resolution=1024, bg_color=(0, 0, 0), num_frames=120, r=2, fov=40, **kwargs): + yaws = -torch.linspace(0, 2 * 3.1415, num_frames) + np.pi/2 + pitch = 0.25 + 0.5 * torch.sin(torch.linspace(0, 2 * 3.1415, num_frames)) + yaws = yaws.tolist() + pitch = pitch.tolist() + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitch, r, fov) + return render_frames(sample, extrinsics, intrinsics, {'resolution': resolution, 'bg_color': bg_color}, **kwargs) + + +def render_multiview(sample, resolution=512, nviews=30): + r = 2 + fov = 40 + cams = [sphere_hammersley_sequence(i, nviews) for i in range(nviews)] + yaws = [cam[0] for cam in cams] + pitchs = [cam[1] for cam in cams] + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, r, fov) + res = render_frames(sample, extrinsics, intrinsics, {'resolution': resolution, 'bg_color': (0, 0, 0)}) + return res['color'], extrinsics, intrinsics + + +def render_snapshot(samples, resolution=512, bg_color=(0, 0, 0), offset=(-16 / 180 * np.pi, 20 / 180 * np.pi), r=10, fov=8, nviews=4, **kwargs): + yaw = np.linspace(0, 2 * np.pi, nviews, endpoint=False) + yaw_offset = offset[0] + yaw = [y + yaw_offset for y in yaw] + pitch = [offset[1] for _ in range(nviews)] + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaw, pitch, r, fov) + return render_frames(samples, extrinsics, intrinsics, {'resolution': resolution, 'bg_color': bg_color}, **kwargs) + + +def make_pbr_vis_frames(result, resolution=1024): + num_frames = len(result['shaded']) + frames = [] + for i in range(num_frames): + shaded = Image.fromarray(result['shaded'][i]) + normal = Image.fromarray(result['normal'][i]) + base_color = Image.fromarray(result['base_color'][i]) + metallic = Image.fromarray(result['metallic'][i]) + roughness = Image.fromarray(result['roughness'][i]) + alpha = Image.fromarray(result['alpha'][i]) + shaded = shaded.resize((resolution, resolution)) + normal = normal.resize((resolution, resolution)) + base_color = base_color.resize((resolution//2, resolution//2)) + metallic = metallic.resize((resolution//2, resolution//2)) + roughness = roughness.resize((resolution//2, resolution//2)) + alpha = alpha.resize((resolution//2, resolution//2)) + row1 = np.concatenate([shaded, normal], axis=1) + row2 = np.concatenate([base_color, metallic, roughness, alpha], axis=1) + frame = np.concatenate([row1, row2], axis=0) + frames.append(frame) + return frames diff --git a/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/vis_utils.py b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/vis_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5f58e564aea50e4d80b0265220ee3fb382cd69 --- /dev/null +++ b/OVOW/engine/oneposeviagen/TRELLIS2/trellis2/utils/vis_utils.py @@ -0,0 +1,44 @@ +from typing import * +import numpy as np +import torch +from ..modules import sparse as sp +from ..representations import Voxel +from .render_utils import render_video + + +def pca_color(feats: torch.Tensor, channels: Tuple[int, int, int] = (0, 1, 2)) -> torch.Tensor: + """ + Apply PCA to the features and return the first three principal components. + """ + feats = feats.detach() + u, s, v = torch.svd(feats) + color = u[:, channels] + color = (color - color.min(dim=0, keepdim=True)[0]) / (color.max(dim=0, keepdim=True)[0] - color.min(dim=0, keepdim=True)[0]) + return color + + +def vis_sparse_tensor( + x: sp.SparseTensor, + num_frames: int = 300, +): + assert x.shape[0] == 1, "Only support batch size 1" + assert x.coords.shape[1] == 4, "Only support 3D coordinates" + + coords = x.coords.cuda().detach()[:, 1:] + feats = x.feats.cuda().detach() + color = pca_color(feats) + + resolution = max(list(x.spatial_shape)) + resolution = int(2**np.ceil(np.log2(resolution))) + + rep = Voxel( + origin=[-0.5, -0.5, -0.5], + voxel_size=1/resolution, + coords=coords, + attrs=color, + layout={ + 'color': slice(0, 3), + } + ) + + return render_video(rep, colors_overwrite=color, num_frames=num_frames)['color'] diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000000.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000000.txt new file mode 100644 index 0000000000000000000000000000000000000000..2999f93744f8ea2b2c8c5bf45476b296c01123dc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000000.txt @@ -0,0 +1,4 @@ +6.202282593860970472e-01 -2.515007418449344834e-01 7.435574896872494399e-01 -4.485767581348126254e-01 +-7.688537710018328308e-01 -3.817847309062720740e-01 5.121920340703911556e-01 1.178510214030554226e-01 +1.560719472310490019e-01 -8.885882238750235640e-01 -4.312162231485986985e-01 8.033601713736024941e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000001.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000001.txt new file mode 100644 index 0000000000000000000000000000000000000000..54c98432fde808b912adb41658ba97d8582da100 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000001.txt @@ -0,0 +1,4 @@ +6.204752488185271142e-01 -2.517975904941436305e-01 7.431087727596743520e-01 -4.485008783383387931e-01 +-7.684010101135674287e-01 -3.818595014320375625e-01 5.126785632283183958e-01 1.175150707889479479e-01 +1.558579675931975606e-01 -8.879042831720853624e-01 -4.305638655154737093e-01 8.035482790812963350e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000002.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000002.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d9894940af401c73681d799e11c706d3b45d33f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000002.txt @@ -0,0 +1,4 @@ +6.206192626746839247e-01 -2.517818763054288089e-01 7.429750254593390224e-01 -4.476506221596036061e-01 +-7.688835044320422307e-01 -3.818650643946640000e-01 5.125497173255268990e-01 1.178858816417053118e-01 +1.557563614240046190e-01 -8.885966766810526885e-01 -4.306630066826383496e-01 8.041437156349857673e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000003.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000003.txt new file mode 100644 index 0000000000000000000000000000000000000000..26bd191e11fcae2e763efbe763734c23c4b3cfb5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000003.txt @@ -0,0 +1,4 @@ +6.202243809774468097e-01 -2.522238479959009183e-01 7.431755510545791088e-01 -4.480081608898833223e-01 +-7.681723615528722737e-01 -3.822628987433853154e-01 5.125731305406274751e-01 1.180505296724505410e-01 +1.557412730776991938e-01 -8.885747697256174416e-01 -4.311398920047637695e-01 8.034968457932369912e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000004.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000004.txt new file mode 100644 index 0000000000000000000000000000000000000000..8647ae4ec42577e47ebd35778dafbeaffee7c1d7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000004.txt @@ -0,0 +1,4 @@ +6.207588198035163263e-01 -2.521876895601374291e-01 7.438184976299784257e-01 -4.478358000070888911e-01 +-7.685744793682182108e-01 -3.823670027555698958e-01 5.126934176586128711e-01 1.174727375856258887e-01 +1.557557437947517665e-01 -8.882241193920733524e-01 -4.303274520693403105e-01 8.034810820576795409e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000008.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000008.txt new file mode 100644 index 0000000000000000000000000000000000000000..e17715a4a0cabb3d4adec29794e3dee7dbffe449 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000008.txt @@ -0,0 +1,4 @@ +6.162562341475855687e-01 -2.609660081555911781e-01 7.439518985582042054e-01 -4.483721324648345385e-01 +-7.739958558416247802e-01 -3.751057145375686352e-01 5.092156051332498157e-01 1.172938831328591142e-01 +1.462113240613582832e-01 -8.888764343725465977e-01 -4.330030396760862765e-01 8.038146047813611306e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000010.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000010.txt new file mode 100644 index 0000000000000000000000000000000000000000..64f0d6e4cb3a0dec929bd5d0725c949a423bc4fd --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000010.txt @@ -0,0 +1,4 @@ +6.167329021066062511e-01 -2.528931970345209002e-01 7.460504265832623716e-01 -4.476404195242605355e-01 +-7.729741749954882613e-01 -3.756103214283395553e-01 5.106886900796566708e-01 1.175167150476561645e-01 +1.519328061058508039e-01 -8.907181065044597057e-01 -4.273831112683016409e-01 8.032519198893040002e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000014.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000014.txt new file mode 100644 index 0000000000000000000000000000000000000000..8aca20588faac2da9e161a9d636a523f6214f695 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000014.txt @@ -0,0 +1,4 @@ +6.185992673484869142e-01 -2.527614043769160768e-01 7.442134003784778296e-01 -4.477235888041219414e-01 +-7.700534309889131013e-01 -3.794192813565739897e-01 5.120844222961222769e-01 1.173255979840922836e-01 +1.536301268756591343e-01 -8.899348303157970097e-01 -4.287568398742147568e-01 8.035195146122968701e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000019.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000019.txt new file mode 100644 index 0000000000000000000000000000000000000000..581ebd8a13f4c3f1df7e75ebd343c0ba52f2f23b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000019.txt @@ -0,0 +1,4 @@ +6.198450480315526034e-01 -2.505753376324572068e-01 7.441833943659338368e-01 -4.482399651223532011e-01 +-7.693947393748912233e-01 -3.788767240343282050e-01 5.139734186552221695e-01 1.172788111375239889e-01 +1.531971860175793954e-01 -8.906305410208780193e-01 -4.278204052801078405e-01 8.036489990663738814e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000020.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000020.txt new file mode 100644 index 0000000000000000000000000000000000000000..547be7ae6801f4d820236f9bc14bb4e0fc671069 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000020.txt @@ -0,0 +1,4 @@ +6.222332920527836597e-01 -2.519145110940338994e-01 7.418069556858001290e-01 -4.477485154463826111e-01 +-7.684024868855047208e-01 -3.796061555262597587e-01 5.145653519431208078e-01 1.171327464108140176e-01 +1.527379264283539873e-01 -8.892969139461319728e-01 -4.303014861137358649e-01 8.036177418088273905e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000023.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000023.txt new file mode 100644 index 0000000000000000000000000000000000000000..97deed5d5b243b12068676346eee93f562ca0ecc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000023.txt @@ -0,0 +1,4 @@ +6.193764789716851293e-01 -2.495000301913068153e-01 7.452266201207492502e-01 -4.476907134827370904e-01 +-7.693735002885168095e-01 -3.776592011196757692e-01 5.142250742062898228e-01 1.175200876771816810e-01 +1.532558861492351876e-01 -8.910894577061633237e-01 -4.257682517095995323e-01 8.036615729008541598e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000025.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000025.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c2c41b06f97b401581a57d503d9e31f1314dbe2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000025.txt @@ -0,0 +1,4 @@ +6.191590783977964918e-01 -2.529405379308508062e-01 7.448705126432578760e-01 -4.482599750300962915e-01 +-7.708910389201127922e-01 -3.790500798153094153e-01 5.124055814758859961e-01 1.176140045474338286e-01 +1.531799099089704019e-01 -8.892377118416429083e-01 -4.290074268784597189e-01 8.036600184629727472e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000027.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000027.txt new file mode 100644 index 0000000000000000000000000000000000000000..45004117a86307a64a483cdfea9091b6a832f94d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000027.txt @@ -0,0 +1,4 @@ +6.200778485954773211e-01 -2.569191668528258976e-01 7.421122190758794313e-01 -4.476023644850877781e-01 +-7.709687820485207066e-01 -3.729797371153509289e-01 5.147805361587397543e-01 1.177294986810425437e-01 +1.457189645446935466e-01 -8.902796882214485397e-01 -4.292989607891690151e-01 8.042142872394242303e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000029.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000029.txt new file mode 100644 index 0000000000000000000000000000000000000000..74a3f1d9fbae04968cdb3dd76e29bc858e71b405 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000029.txt @@ -0,0 +1,4 @@ +6.203478396711855636e-01 -2.579189667990993695e-01 7.420368423250959244e-01 -4.487448516986908276e-01 +-7.705882715322067700e-01 -3.788029222182033862e-01 5.122470152894660345e-01 1.171279845928241414e-01 +1.491890641865804279e-01 -8.880320286255350970e-01 -4.335815590672796316e-01 8.040006235658598843e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000036.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000036.txt new file mode 100644 index 0000000000000000000000000000000000000000..60b2b1b90553739436dc67c0309fa82eaf89cc4f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000036.txt @@ -0,0 +1,4 @@ +6.182885607034872555e-01 -2.537781437709450971e-01 7.446351225887224423e-01 -4.478556273676987387e-01 +-7.701089718606149992e-01 -3.804482333200642219e-01 5.106835933664330973e-01 1.175849684503111059e-01 +1.542602237825619893e-01 -8.882621196685577258e-01 -4.315772986063036165e-01 8.040469266608371024e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000037.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000037.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b26aa418886120e9033cefc938215aa9f84b7f7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000037.txt @@ -0,0 +1,4 @@ +6.186260787153095020e-01 -2.530138512579381826e-01 7.449442218927646575e-01 -4.475710294192208893e-01 +-7.712095281267129510e-01 -3.744536886906117967e-01 5.138631933354175230e-01 1.176596839554663460e-01 +1.499077471942608653e-01 -8.913566635089192891e-01 -4.263348822945075556e-01 8.038000367649187350e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000038.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000038.txt new file mode 100644 index 0000000000000000000000000000000000000000..faf364bb1eaf7ed4036ed200803308ae855b2132 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000038.txt @@ -0,0 +1,4 @@ +6.207118299369295267e-01 -2.519466490616852350e-01 7.426425709549686616e-01 -4.480769597527707870e-01 +-7.677998140500704727e-01 -3.829703883746373161e-01 5.119961662625684973e-01 1.173556324446035221e-01 +1.559216630772616574e-01 -8.880248792231145716e-01 -4.312973307568952475e-01 8.035739517932629639e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000039.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000039.txt new file mode 100644 index 0000000000000000000000000000000000000000..f71eebed49505d5efd5a09b2add3d79edebac252 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000039.txt @@ -0,0 +1,4 @@ +6.177206241289511235e-01 -2.521897335944353613e-01 7.459635452731174787e-01 -4.478401122328874440e-01 +-7.705575342073359701e-01 -3.813526883029436099e-01 5.091813388137824692e-01 1.178199836384590804e-01 +1.563615328813947880e-01 -8.880698379738364290e-01 -4.301353660321948769e-01 8.038244452305222110e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000040.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000040.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b6cc57d48163269ab36bda9a9ac19c0d39109ce --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000040.txt @@ -0,0 +1,4 @@ +6.216333173843113791e-01 -2.502858580789864562e-01 7.435577360261793611e-01 -4.478963327527554772e-01 +-7.689055663100591298e-01 -3.768556904073587788e-01 5.158761788049568420e-01 1.175516198859020284e-01 +1.519184185152882560e-01 -8.908257628900567715e-01 -4.265033661530128195e-01 8.032752950946260295e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000041.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000041.txt new file mode 100644 index 0000000000000000000000000000000000000000..91ebbe3e6a9ad05d034329daf109e04ac1219713 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000041.txt @@ -0,0 +1,4 @@ +6.207093466216275779e-01 -2.574122531318103202e-01 7.420962790400474907e-01 -4.475583339001598659e-01 +-7.710747372235270403e-01 -3.751264434850359319e-01 5.153227124166041007e-01 1.177667796169226816e-01 +1.463999843183182159e-01 -8.894292541086202819e-01 -4.310855678670176272e-01 8.034791485654506626e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000042.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000042.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b0bfb3fbf377e88f5e559fe7290dc9ab106e937 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000042.txt @@ -0,0 +1,4 @@ +6.174581249864290466e-01 -2.581635098554385110e-01 7.443057777788333329e-01 -4.483048349320870041e-01 +-7.724286304598345643e-01 -3.748172547830556089e-01 5.113291516280318305e-01 1.178958874982677513e-01 +1.474726278751183894e-01 -8.897845821758212370e-01 -4.313411595383497832e-01 8.030280046959782370e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000043.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000043.txt new file mode 100644 index 0000000000000000000000000000000000000000..d732e7522359c7e223377ad7702009a571046266 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000043.txt @@ -0,0 +1,4 @@ +6.175060429589998012e-01 -2.526849874218925485e-01 7.455246226882390470e-01 -4.481164014948081920e-01 +-7.710624833290142810e-01 -3.783953185974556210e-01 5.110746949040202436e-01 1.170392556083209024e-01 +1.530205333202296070e-01 -8.892525057588994697e-01 -4.291281684739150504e-01 8.040240660612197887e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000044.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000044.txt new file mode 100644 index 0000000000000000000000000000000000000000..9456562f990106991c6d239a9e22b8c84e22aeab --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000044.txt @@ -0,0 +1,4 @@ +6.204046110833181249e-01 -2.497305683852975022e-01 7.440155743857794768e-01 -4.483444229189437746e-01 +-7.685206130621954346e-01 -3.808965301911176882e-01 5.136841725020179217e-01 1.170492912677750935e-01 +1.555234158485415963e-01 -8.888367964587695624e-01 -4.290534178327943815e-01 8.033659039447225148e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000045.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000045.txt new file mode 100644 index 0000000000000000000000000000000000000000..b478f8681262cf77e44e414888d72191092b4b5b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000045.txt @@ -0,0 +1,4 @@ +6.218345251681626218e-01 -2.536549697003080972e-01 7.424585085690620367e-01 -4.480195117912690317e-01 +-7.689258294348154665e-01 -3.793582563664741336e-01 5.142056208703279507e-01 1.171124245336024189e-01 +1.514811709142097895e-01 -8.891475501133148107e-01 -4.308417787107233776e-01 8.040885425141489629e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000046.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000046.txt new file mode 100644 index 0000000000000000000000000000000000000000..087223e1186df8178265ad3a1cd784f518c75dc2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000046.txt @@ -0,0 +1,4 @@ +6.162445417546730253e-01 -2.584117172732930956e-01 7.449898656425517629e-01 -4.484874776997579415e-01 +-7.735923243767111046e-01 -3.741270522971973378e-01 5.102886286239897151e-01 1.172924169726940469e-01 +1.472629923306273125e-01 -8.892233734467746009e-01 -4.312652705280180521e-01 8.031744791879962264e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000047.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000047.txt new file mode 100644 index 0000000000000000000000000000000000000000..f5b1c876182d278417749bba1c1f37cdc46d3c84 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000047.txt @@ -0,0 +1,4 @@ +6.186465034340765667e-01 -2.551072814444957371e-01 7.431168316882504898e-01 -4.480977633333456667e-01 +-7.695232590422060870e-01 -3.822868674166591818e-01 5.103716986153803425e-01 1.180855425719621321e-01 +1.545380090689426056e-01 -8.876592152033470073e-01 -4.329854852212035587e-01 8.032252178407653931e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000048.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000048.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ed7cc71e87fcf137855caa9e1e80ed2e4182419 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000048.txt @@ -0,0 +1,4 @@ +6.180924769092245308e-01 -2.486981151106936738e-01 7.468835472879306048e-01 -4.483216236806942812e-01 +-7.700306172224089529e-01 -3.814546347511095226e-01 5.105046160434831837e-01 1.173275561223839775e-01 +1.581654859748279907e-01 -8.890925605470886284e-01 -4.281267475639104481e-01 8.037988549259561522e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000049.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000049.txt new file mode 100644 index 0000000000000000000000000000000000000000..6220d8bd352dcb7e49af458644d90aaba2407d5b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000049.txt @@ -0,0 +1,4 @@ +6.227275714330154921e-01 -2.416166657136511464e-01 7.443299735893234015e-01 -4.474508012897699949e-01 +-7.649127813408245213e-01 -3.871504091943731019e-01 5.149184122420944476e-01 1.176646426059059780e-01 +1.643886727780921042e-01 -8.885656457713337897e-01 -4.264442311856741497e-01 8.034551806326869494e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000050.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000050.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9044aa0315d995ec1e65ae19afb925ba8722490 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000050.txt @@ -0,0 +1,4 @@ +6.211178996831133725e-01 -2.578178795318182837e-01 7.401447029589197646e-01 -4.483427521442234220e-01 +-7.702976198284826603e-01 -3.729125005545457228e-01 5.165526633861635686e-01 1.176564285959250250e-01 +1.433755075781433519e-01 -8.899182655624006122e-01 -4.313072100733814640e-01 8.041949568886900268e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000051.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000051.txt new file mode 100644 index 0000000000000000000000000000000000000000..34084fcaf2f3feeb1c7acfcd7deeb82c3d9dfa89 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000051.txt @@ -0,0 +1,4 @@ +6.177244655854384758e-01 -2.583281565918511546e-01 7.437895441921260620e-01 -4.485135212077262512e-01 +-7.728789951686189097e-01 -3.737619958670100329e-01 5.122847975556785727e-01 1.172535592814822059e-01 +1.461147913319333080e-01 -8.893759021591917113e-01 -4.310561229143408113e-01 8.034448201575863369e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000052.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000052.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a83a865555189577e4c27a30b9fe55986862664 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000052.txt @@ -0,0 +1,4 @@ +6.197986938201220930e-01 -2.565773122799756001e-01 7.426321665804550554e-01 -4.474663478653507220e-01 +-7.704277972518842610e-01 -3.789249050603515356e-01 5.125518299609861383e-01 1.174846477385081550e-01 +1.501029752369690273e-01 -8.881404546419302548e-01 -4.321003401563435209e-01 8.037679976870755194e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000053.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000053.txt new file mode 100644 index 0000000000000000000000000000000000000000..35131ccbf2e33beb1c422dba0b57a5d0c7aceecd --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000053.txt @@ -0,0 +1,4 @@ +6.180377940097493417e-01 -2.586115053669528208e-01 7.433683634732948242e-01 -4.486537299259418243e-01 +-7.723000513077213913e-01 -3.751473042235276556e-01 5.116629402274636140e-01 1.169321404042026197e-01 +1.473212592530535325e-01 -8.892861664212672324e-01 -4.319464895947817129e-01 8.041153943290447748e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000054.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000054.txt new file mode 100644 index 0000000000000000000000000000000000000000..f65635afd9ea75f027eea2e2e33a810093a9e8a0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000054.txt @@ -0,0 +1,4 @@ +6.203658365690366550e-01 -2.568082466406483300e-01 7.425752564618057772e-01 -4.481766364262198543e-01 +-7.707166448557853933e-01 -3.747554747385559715e-01 5.145081961882556065e-01 1.171767793632680077e-01 +1.466945147792453608e-01 -8.898464019435052830e-01 -4.301513361023996951e-01 8.039599896828015790e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000055.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000055.txt new file mode 100644 index 0000000000000000000000000000000000000000..799f5c0080510b2f2ba3681d816e433f79aa61eb --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000055.txt @@ -0,0 +1,4 @@ +6.179788854888600413e-01 -2.615534712537037620e-01 7.426386281413517310e-01 -4.483338231457901779e-01 +-7.735845513638763826e-01 -3.685302590099074904e-01 5.141749068166524550e-01 1.176785260682416123e-01 +1.399838493038308984e-01 -8.909794729359789001e-01 -4.311471705459383741e-01 8.037932003166162742e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000056.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000056.txt new file mode 100644 index 0000000000000000000000000000000000000000..4d3f8abfead65fd5d330736aef4a8505914f9b7e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000056.txt @@ -0,0 +1,4 @@ +6.216763321568434808e-01 -2.546241233413275018e-01 7.415814916463032702e-01 -4.479520848716082582e-01 +-7.688893198381674399e-01 -3.755322182341034321e-01 5.163063960714947553e-01 1.175519555685501372e-01 +1.475456587330895297e-01 -8.907403811283697292e-01 -4.283550315779282580e-01 8.040089759285499182e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000057.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000057.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a853b25b0fc45d9727fb70275bd65eaf0c3305e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000057.txt @@ -0,0 +1,4 @@ +6.188669732976123106e-01 -2.626418674799527730e-01 7.410149913618031547e-01 -4.479883354735414991e-01 +-7.710520304280804593e-01 -3.797635819015484637e-01 5.098629913626082644e-01 1.174414198349000293e-01 +1.481753355832935992e-01 -8.863645684594204655e-01 -4.381832205417362514e-01 8.042196971952099149e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000058.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000058.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c4d144d8afdbb35d0c590242ffa563967c617d0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000058.txt @@ -0,0 +1,4 @@ +6.147545787154793384e-01 -2.535762861567627535e-01 7.475943949670034172e-01 -4.484782832735758618e-01 +-7.728455806998085764e-01 -3.833426100146414273e-01 5.056084208744997532e-01 1.176244346139171809e-01 +1.596697185728551127e-01 -8.871369772683236343e-01 -4.317767563998572977e-01 8.041711429767218755e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000059.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000059.txt new file mode 100644 index 0000000000000000000000000000000000000000..858cbe32053cd6465ae1941f22693fe61aa08b58 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000059.txt @@ -0,0 +1,4 @@ +6.187671965144483366e-01 -2.488084298607581013e-01 7.456176072833697877e-01 -4.486637873297826262e-01 +-7.674218616476103927e-01 -3.927828353179373955e-01 5.056564521675215307e-01 1.175011942406066628e-01 +1.676828229524289504e-01 -8.838994928412200469e-01 -4.345471502693343813e-01 8.041309828394973547e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000060.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000060.txt new file mode 100644 index 0000000000000000000000000000000000000000..9404f2bd9f42a613c93e1d6d768ff70c8c8c45b6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000060.txt @@ -0,0 +1,4 @@ +6.183862747951598404e-01 -2.522987339339110568e-01 7.449632687698826139e-01 -4.478758558416230939e-01 +-7.702853245650437275e-01 -3.807203937867763566e-01 5.108968200367371981e-01 1.181291493302927403e-01 +1.551775455979391150e-01 -8.890272535753243055e-01 -4.296879216844552429e-01 8.040456814553238463e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000061.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000061.txt new file mode 100644 index 0000000000000000000000000000000000000000..b755fce88ca57ea7a5318ca012b7a4deb8c00e7d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000061.txt @@ -0,0 +1,4 @@ +6.218802688475509877e-01 -2.562877461902489662e-01 7.402962303595385096e-01 -4.488666312955218451e-01 +-7.681299764603133351e-01 -3.838068500987346088e-01 5.121942419526124279e-01 1.181632250858962452e-01 +1.536669600963482540e-01 -8.858535823754549732e-01 -4.355922894868100026e-01 8.045744160123292632e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000062.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000062.txt new file mode 100644 index 0000000000000000000000000000000000000000..423a27e64eed6691f7543353826fab8defd7bff3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000062.txt @@ -0,0 +1,4 @@ +6.162833071271056617e-01 -2.489667854473203712e-01 7.483169758655259240e-01 -4.479659288592817701e-01 +-7.686426710039061527e-01 -3.953286817543236742e-01 5.017457083343510593e-01 1.176922094275119207e-01 +1.721047442078332546e-01 -8.833815564085926164e-01 -4.350239344540700048e-01 8.044071447854278523e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000063.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000063.txt new file mode 100644 index 0000000000000000000000000000000000000000..d266267a4d254250b1cb865762127b89b77a4121 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000063.txt @@ -0,0 +1,4 @@ +6.154326396632068263e-01 -2.573237292076049343e-01 7.457414190383406805e-01 -4.484254492764612188e-01 +-7.722793195570800684e-01 -3.859115912375516433e-01 5.039946607343241958e-01 1.182624047637314130e-01 +1.583790662744918587e-01 -8.849774732224736651e-01 -4.361030925216166088e-01 8.046773697125209068e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000064.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000064.txt new file mode 100644 index 0000000000000000000000000000000000000000..48e33b960c06523fb821338db8341a33c4682cb3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000064.txt @@ -0,0 +1,4 @@ +6.119097428606181666e-01 -2.676087272096211445e-01 7.457953367607015327e-01 -4.483527644399351031e-01 +-7.747070657325936249e-01 -3.946772164664905103e-01 4.938598688457902508e-01 1.175602907899776228e-01 +1.626054438447194772e-01 -8.781454766441033621e-01 -4.479774491411535609e-01 8.047956070077473267e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000065.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000065.txt new file mode 100644 index 0000000000000000000000000000000000000000..339d8d3602244c079da2540b994b6e3733c4bdeb --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000065.txt @@ -0,0 +1,4 @@ +6.159675282033189037e-01 -2.694900870406733984e-01 7.414428138459919770e-01 -4.508764850586773343e-01 +-7.720153718402380516e-01 -3.927351936034588764e-01 4.996482444628205233e-01 1.156666902037179201e-01 +1.573194098834923838e-01 -8.790328075275833930e-01 -4.493026281262998967e-01 8.033157476486020299e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000066.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000066.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0cf65939c8094b1a81f9c8b2a1ef77ae9ed0c99 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000066.txt @@ -0,0 +1,4 @@ +6.122716031278804261e-01 -2.743014135255164576e-01 7.418733635104658442e-01 -4.497770796107292690e-01 +-7.745671147940543788e-01 -3.958062700183659355e-01 4.928484437170607135e-01 1.180033675783908886e-01 +1.587585792277520502e-01 -8.758066292500633621e-01 -4.544350804391996679e-01 8.052355733874828614e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000067.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000067.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6c4a97f5e055a145039de27986cf2569de76959 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000067.txt @@ -0,0 +1,4 @@ +6.128761831683174899e-01 -2.709011987998095061e-01 7.425586263382196739e-01 -4.501896015094760117e-01 +-7.738848976126876389e-01 -3.940288965006316091e-01 4.951233847537834243e-01 1.185113199726791494e-01 +1.592438618084911772e-01 -8.771462462056798248e-01 -4.516810715079772609e-01 8.053649771745773345e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000068.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000068.txt new file mode 100644 index 0000000000000000000000000000000000000000..04bf46a81e6778c4c7e3ea90778e34d4a794b66e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000068.txt @@ -0,0 +1,4 @@ +6.129499495473725856e-01 -2.770438908472028228e-01 7.405083985240553668e-01 -4.499982253225332518e-01 +-7.748284503734060857e-01 -3.900156231892630831e-01 4.956824838920868004e-01 1.181672176315014672e-01 +1.519567836174628150e-01 -8.774923959532157092e-01 -4.541654630129965953e-01 8.050934321762902579e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000069.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000069.txt new file mode 100644 index 0000000000000000000000000000000000000000..a06c69273a11acef21f0608b9f998dd117fd9777 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000069.txt @@ -0,0 +1,4 @@ +6.120471237523417152e-01 -2.745768644271907033e-01 7.419396950889900477e-01 -4.502668939135311965e-01 +-7.751597398649899828e-01 -3.903232346528712204e-01 4.954689606853359130e-01 1.180579120511300456e-01 +1.538175417567312353e-01 -8.782676087943488419e-01 -4.521872476024264009e-01 8.050015668178635009e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000070.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000070.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b8c23b847451da74cc724324fd644fe32ea19f9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000070.txt @@ -0,0 +1,4 @@ +6.120973906861044700e-01 -2.782664967999986527e-01 7.404615650158777873e-01 -4.507543908492776530e-01 +-7.768176315471174709e-01 -3.845689696768992416e-01 4.978395250535370686e-01 1.181459056610280473e-01 +1.465820240955154341e-01 -8.792471918490285532e-01 -4.523196603070537281e-01 8.045378025077090101e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000071.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000071.txt new file mode 100644 index 0000000000000000000000000000000000000000..64d44c093f3dfa1e9656781e9a1a27fb11699beb --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000071.txt @@ -0,0 +1,4 @@ +6.111702186760501476e-01 -2.776883100822350459e-01 7.424520640840034380e-01 -4.501152521976772847e-01 +-7.774571580615025068e-01 -3.856079588111048784e-01 4.961367431034972020e-01 1.181433162084125216e-01 +1.488468702896958984e-01 -8.789190073390881208e-01 -4.521697122843806316e-01 8.050530712427725888e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000072.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000072.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6030aefba30deaeed76d31839c31cd36562c6ee --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000072.txt @@ -0,0 +1,4 @@ +6.177046467151354747e-01 -2.693296576736423087e-01 7.388583344406813858e-01 -4.507024167417827409e-01 +-7.702393763044752539e-01 -3.951545964651788645e-01 5.004353846311749843e-01 1.188538465204182909e-01 +1.581135359171997878e-01 -8.769559061676364120e-01 -4.512619411313442686e-01 8.053632343301032614e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000073.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000073.txt new file mode 100644 index 0000000000000000000000000000000000000000..027d9c74872f977b95145d9c76af1cde833fa754 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000073.txt @@ -0,0 +1,4 @@ +6.079765168054266367e-01 -2.872717925392015426e-01 7.405596497520228194e-01 -4.508068049816114642e-01 +-7.812213115267422348e-01 -3.822665104113207035e-01 4.927864213373542301e-01 1.189015624714647029e-01 +1.418496135951744508e-01 -8.768535083998328927e-01 -4.580426897981245693e-01 8.044407903389710901e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000074.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000074.txt new file mode 100644 index 0000000000000000000000000000000000000000..05d57e21c8c986257a3e8c276ea7aa333c00cbcd --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000074.txt @@ -0,0 +1,4 @@ +6.084683627587265109e-01 -2.764040338099105765e-01 7.449671400798273391e-01 -4.507006609461960411e-01 +-7.792526680064787437e-01 -3.851936975664829732e-01 4.938935562171221649e-01 1.186428577946171403e-01 +1.510919506543057789e-01 -8.791312217511677574e-01 -4.495575980696201457e-01 8.047137666713023441e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000075.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000075.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b560f38ec54394244a925a0e313476beeb97aa9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000075.txt @@ -0,0 +1,4 @@ +6.162727179761535723e-01 -2.754004781330836038e-01 7.386230528376201976e-01 -4.500059297686154758e-01 +-7.727290471047861820e-01 -3.919388859377214152e-01 4.990651085996123948e-01 1.179076541204789885e-01 +1.528556991935886844e-01 -8.774021631610493532e-01 -4.541176066577464199e-01 8.045223373716491322e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000076.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000076.txt new file mode 100644 index 0000000000000000000000000000000000000000..0377b379f4f193804503bc83ade7518fd0a5d99b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000076.txt @@ -0,0 +1,4 @@ +6.126993783619258949e-01 -2.771384338872643904e-01 7.404434845086507178e-01 -4.504748137183103296e-01 +-7.760199845084133630e-01 -3.864005208576541950e-01 4.978313087608555176e-01 1.182999146225418574e-01 +1.477236588659219529e-01 -8.793561176298756443e-01 -4.515472493502538098e-01 8.044074867562998055e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000077.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000077.txt new file mode 100644 index 0000000000000000000000000000000000000000..48ecae7c6def6a58a87c53b7e582018cd9eb6d86 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000077.txt @@ -0,0 +1,4 @@ +6.124348647484080255e-01 -2.771251092062751442e-01 7.417346181776217628e-01 -4.499492124034182305e-01 +-7.763857068625414914e-01 -3.888831309442576933e-01 4.960449260558260631e-01 1.186681943803957334e-01 +1.515957003173515061e-01 -8.777113073760061113e-01 -4.527975228543202335e-01 8.046822681316566639e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000078.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000078.txt new file mode 100644 index 0000000000000000000000000000000000000000..f227c4641d1e70463ec4990356026b930f9aa9d9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000078.txt @@ -0,0 +1,4 @@ +6.154190169900077834e-01 -2.750584729507981052e-01 7.395452318018588267e-01 -4.500761430698696497e-01 +-7.747785574202327163e-01 -3.866374123093746507e-01 4.998613896883466468e-01 1.187038960674166310e-01 +1.483411343349198275e-01 -8.795305457161650686e-01 -4.511280342332599225e-01 8.047974049624160298e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000079.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000079.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8014a48ae87150242a5e29d2e2b032a80d46354 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000079.txt @@ -0,0 +1,4 @@ +6.078802490994505980e-01 -2.797446250620816421e-01 7.439435636956278630e-01 -4.504784477630124906e-01 +-7.791631785456876180e-01 -3.857304176405194629e-01 4.933257909520319395e-01 1.180758535551351962e-01 +1.494491718643656819e-01 -8.781680408261606230e-01 -4.519944024671599947e-01 8.045841745176164350e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000083.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000083.txt new file mode 100644 index 0000000000000000000000000000000000000000..009b7ea5bc35fd684b9296a3db280223ac1a6b3c --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000083.txt @@ -0,0 +1,4 @@ +6.154675065526359345e-01 -2.768345047008458626e-01 7.382316558882600077e-01 -4.506343965845268085e-01 +-7.743260008366942282e-01 -3.876206782590140842e-01 4.997125926742416180e-01 1.179936162727771715e-01 +1.489031935388610561e-01 -8.777625509428035322e-01 -4.533843879966145130e-01 8.047696602364147189e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000089.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000089.txt new file mode 100644 index 0000000000000000000000000000000000000000..9e4fe42161a930b71f3aded7f28ab27a3c2cbe9b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000089.txt @@ -0,0 +1,4 @@ +6.138748947613920093e-01 -2.763750481169172102e-01 7.397788283819196620e-01 -4.501568115049406349e-01 +-7.742452621484475772e-01 -3.900348617581068655e-01 4.971374190209205124e-01 1.183402230750050937e-01 +1.518702021939103697e-01 -8.777656078724183075e-01 -4.536840698379816517e-01 8.043243528665607878e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000092.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000092.txt new file mode 100644 index 0000000000000000000000000000000000000000..c900698bcabacf1de1973efbd5a39cfd3d17056c --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000092.txt @@ -0,0 +1,4 @@ +6.148127104832082912e-01 -2.707176288170952683e-01 7.414199456156627122e-01 -4.509919233054788812e-01 +-7.741863843363684383e-01 -3.873050727506328617e-01 5.005946159146662522e-01 1.182532352338258874e-01 +1.520121715332835299e-01 -8.804598298300115866e-01 -4.469984381203632728e-01 8.050769958468699805e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000095.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000095.txt new file mode 100644 index 0000000000000000000000000000000000000000..de7e829906860134b047691b0c10b7a7bb7432c6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000095.txt @@ -0,0 +1,4 @@ +6.164674364774331838e-01 -2.751506465714645411e-01 7.389015197863600948e-01 -4.509770291118341823e-01 +-7.734835095588112885e-01 -3.852452630891243235e-01 5.023437566757578132e-01 1.182457767225308931e-01 +1.463051706628976656e-01 -8.805371750100980943e-01 -4.506986023243695350e-01 8.044691326971548095e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000166.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000166.txt new file mode 100644 index 0000000000000000000000000000000000000000..da2518ae797e473af657f0f9a93c75405f4ce876 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000166.txt @@ -0,0 +1,4 @@ +6.113790577314204278e-01 -2.712727040658808320e-01 7.437413147151213932e-01 -4.504143943482920576e-01 +-7.764745764814685591e-01 -3.882717741106662679e-01 4.965442236161934919e-01 1.182733923781413704e-01 +1.546099380123384937e-01 -8.801888006550184773e-01 -4.481079682723669300e-01 8.047812072166293795e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000167.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000167.txt new file mode 100644 index 0000000000000000000000000000000000000000..917dab1fc5f38292fd9abd02e9b9a8273bf8a950 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000167.txt @@ -0,0 +1,4 @@ +6.151541015368569010e-01 -2.686861745827423542e-01 7.415147749171242531e-01 -4.498150280708955173e-01 +-7.722166839616492195e-01 -3.941595543305588256e-01 4.980119398446042900e-01 1.186426958181244634e-01 +1.588635675296792282e-01 -8.782247322835826653e-01 -4.507708446023301341e-01 8.051041783295382892e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000171.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000171.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ccf152189df91ea46195d3994052657afdfbc75 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000171.txt @@ -0,0 +1,4 @@ +6.154076335333333869e-01 -2.726122584236447266e-01 7.401219917012747951e-01 -4.500363223111688016e-01 +-7.721450742652686827e-01 -3.949859400782103624e-01 4.966694792705961259e-01 1.184889492857844340e-01 +1.570832986227430894e-01 -8.768299832151140727e-01 -4.527123027202215599e-01 8.044691449388614579e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000179.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000179.txt new file mode 100644 index 0000000000000000000000000000000000000000..557694a5dce0f16b84957b580222a0a858f47459 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000179.txt @@ -0,0 +1,4 @@ +6.148405967184749077e-01 -2.754738688023027904e-01 7.393807103820086990e-01 -4.498609407124343207e-01 +-7.751695664612273662e-01 -3.848362875523206328e-01 5.005153699445180626e-01 1.179108009913462790e-01 +1.472868763332091657e-01 -8.798485619314582173e-01 -4.510406155246580728e-01 8.046601760190875696e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000187.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000187.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ae2d13a880c0e9831ebdff01d61021cc8432daf --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000187.txt @@ -0,0 +1,4 @@ +6.129561731955655013e-01 -2.731176857542172987e-01 7.419837083059803717e-01 -4.500145648735839332e-01 +-7.744423704411859122e-01 -3.932666082719427081e-01 4.949707320167128777e-01 1.183525106617968614e-01 +1.577687951958662849e-01 -8.771439464684304133e-01 -4.525060390386315690e-01 8.048266636334789892e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000198.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000198.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed46f1a8e082ff2fb5fe16b2c235997d6acb4bd4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000198.txt @@ -0,0 +1,4 @@ +6.141925424602502348e-01 -2.758868834563515393e-01 7.407151604981321302e-01 -4.500912299715861820e-01 +-7.741644021428892852e-01 -3.899825191898623200e-01 4.967426510485320468e-01 1.180421536767105595e-01 +1.518941626193887617e-01 -8.773887167792217001e-01 -4.532606539548534319e-01 8.046824487723606145e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000201.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000201.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5b9a3fad15d1c54bf90cc21e03100b3f58e9738 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000201.txt @@ -0,0 +1,4 @@ +6.124809666381778595e-01 -2.729481365176285035e-01 7.432358498293814009e-01 -4.501296133384998233e-01 +-7.747034817391036388e-01 -3.934225343468580882e-01 4.945229053321523738e-01 1.177544300531128407e-01 +1.585281899061373456e-01 -8.775676427561068804e-01 -4.518166030713992587e-01 8.052823688432927396e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000202.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000202.txt new file mode 100644 index 0000000000000000000000000000000000000000..5aba37fe72efbcfb529af52462dc96fddc0ac530 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000202.txt @@ -0,0 +1,4 @@ +6.147777808656030851e-01 -2.677401931399103208e-01 7.427920072652942629e-01 -4.507068706246245560e-01 +-7.716824965476496434e-01 -3.949616401647156883e-01 4.975425166992655801e-01 1.177183902157832029e-01 +1.603217178097583739e-01 -8.776669822537501719e-01 -4.497110348290546677e-01 8.046451079173843057e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000203.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000203.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5273095aafd407f7ed95555ebcb1f3cd33248c6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000203.txt @@ -0,0 +1,4 @@ +6.159307725397616951e-01 -2.668759079633128417e-01 7.417172289852783651e-01 -4.508388015929119530e-01 +-7.711615760014711718e-01 -3.932830984897145998e-01 4.996423373479340069e-01 1.181145722946991689e-01 +1.591345173159711135e-01 -8.787442122862193505e-01 -4.475102155257089098e-01 8.046840319758569171e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000204.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000204.txt new file mode 100644 index 0000000000000000000000000000000000000000..f08794e6dc341df7b4a2d9b1e37c8c2977b77589 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000204.txt @@ -0,0 +1,4 @@ +6.133622784269682215e-01 -2.728505865333729630e-01 7.419068157799294516e-01 -4.505322432056635962e-01 +-7.739737766437632116e-01 -3.946406106463181684e-01 4.945076779628602148e-01 1.176127968662675216e-01 +1.587077536783059739e-01 -8.760508454289550606e-01 -4.539427095832577197e-01 8.049155564734585822e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000205.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000205.txt new file mode 100644 index 0000000000000000000000000000000000000000..001608f3368c3227f5e1005240f7af7204aef427 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000205.txt @@ -0,0 +1,4 @@ +6.250620097563150956e-01 -2.479927990399298787e-01 7.401657107462527030e-01 -4.536064029964439470e-01 +-7.570650607419620037e-01 -4.201647962908932610e-01 4.996377363325434917e-01 1.146859572305838210e-01 +1.877234742673475620e-01 -8.726608224431088301e-01 -4.499274093310376976e-01 8.017387160711997307e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000206.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000206.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8f048659c9c9a9e5d75e24eec3891df4920cc9a --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000206.txt @@ -0,0 +1,4 @@ +6.272215435122819871e-01 -2.481253151488794217e-01 7.395200104825546683e-01 -4.540245063703685080e-01 +-7.521994554424227264e-01 -4.382902435929566520e-01 4.914809457134857174e-01 1.101795480611535288e-01 +2.022780745264241009e-01 -8.635346614893192330e-01 -4.614199051460675105e-01 7.997533699969311405e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000207.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000207.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c1394ea2417609ab075bb42ed6bfe4b0046a6d0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000207.txt @@ -0,0 +1,4 @@ +6.016335457164160294e-01 -2.642549860827578811e-01 7.549266617869092588e-01 -4.549547263685652099e-01 +-7.758253131792938184e-01 -4.158076030377155230e-01 4.732781192257757286e-01 9.745750552823789770e-02 +1.889215836279398986e-01 -8.699341830369116124e-01 -4.545128039140818310e-01 7.939619527138108701e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000208.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000208.txt new file mode 100644 index 0000000000000000000000000000000000000000..48c5e84b20c890c56f0be513157caa8a450bedc3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000208.txt @@ -0,0 +1,4 @@ +6.108570922706030304e-01 -2.675457481369847845e-01 7.452656772861766532e-01 -4.579862391379055930e-01 +-7.696303497748786526e-01 -4.187595278250040853e-01 4.809016873359696076e-01 8.519665010314074471e-02 +1.843842027276404449e-01 -8.668420947678882049e-01 -4.617068095798425587e-01 7.834411063334086878e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000209.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000209.txt new file mode 100644 index 0000000000000000000000000000000000000000..eb8ee7e2983a9fa558d551f49cae0bf022c238de --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000209.txt @@ -0,0 +1,4 @@ +6.272197982416531925e-01 -2.459623251304046965e-01 7.401803368771738834e-01 -4.588458302981584525e-01 +-7.461801588437693145e-01 -4.590420859132036679e-01 4.803843499279815132e-01 7.552677185786786651e-02 +2.216870443164842275e-01 -8.526767772845279536e-01 -4.709561573957478098e-01 7.706778729894437907e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000210.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000210.txt new file mode 100644 index 0000000000000000000000000000000000000000..69c02878f7c3f2bb3f046805c6c8af03f6335e62 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000210.txt @@ -0,0 +1,4 @@ +6.406805048129728952e-01 -2.461546108465118288e-01 7.273825652284368060e-01 -4.581603752350275061e-01 +-7.360586319300359559e-01 -4.656086315978493761e-01 4.913854875759218199e-01 6.444050890648760077e-02 +2.177523171568872540e-01 -8.492220100311618225e-01 -4.797410990894161453e-01 7.581866226790815455e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000211.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000211.txt new file mode 100644 index 0000000000000000000000000000000000000000..aed83e2aca4ed7da051f05c4a6cb83e8529a3449 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000211.txt @@ -0,0 +1,4 @@ +6.376476245477716853e-01 -2.580582242707105678e-01 7.260828244868008374e-01 -4.572357937802858929e-01 +-7.471494884357731125e-01 -4.354656529229595785e-01 5.011863633718618427e-01 5.220161365024204164e-02 +1.872957064624939105e-01 -8.609172843149913712e-01 -4.712307048017521649e-01 7.448746438295532624e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000212.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000212.txt new file mode 100644 index 0000000000000000000000000000000000000000..1272c34c509d253a1431498d5037a58aac0ae9a7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0000212.txt @@ -0,0 +1,4 @@ +6.434333489964886299e-01 -2.414919785150724529e-01 7.279136664947901680e-01 -4.583988325424726007e-01 +-7.403350667445504074e-01 -4.366734497535720294e-01 5.104556687777832558e-01 4.168643357295723911e-02 +1.953245760631777961e-01 -8.656696450326935022e-01 -4.597563220443116050e-01 7.322964756475828230e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00