diff --git a/uniforge3d/__init__.py b/uniforge3d/__init__.py deleted file mode 100644 index 31e395e6f254b0d76e2ed5a09c1ac78eb982e474..0000000000000000000000000000000000000000 --- a/uniforge3d/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""UniForge3D multi-view image-to-3D inference.""" - -from .pipelines import UniForge3DImageTo3DPipeline - -__all__ = ["UniForge3DImageTo3DPipeline"] diff --git a/uniforge3d/configs/pipeline.json b/uniforge3d/configs/pipeline.json deleted file mode 100644 index 58a5b54058e77193a8f80046e510810b56e01159..0000000000000000000000000000000000000000 --- a/uniforge3d/configs/pipeline.json +++ /dev/null @@ -1,714 +0,0 @@ -{ - "external_models": { - "dino": "facebook/dinov3-vitl16-pretrain-lvd1689m", - "rembg": "briaai/RMBG-2.0" - }, - "sparse_structure": { - "sampler": { - "args": { - "sigma_min": 1e-05 - }, - "params": { - "steps": 12, - "guidance_strength": 7.5, - "guidance_interval": [ - 0.6, - 1 - ], - "guidance_rescale": 0.7, - "rescale_t": 5 - } - }, - "model": { - "name": "JointDiTVGGTStage1Model", - "args": { - "dit_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 - }, - "dino_image_size": 512, - "vggt_img_size": 518, - "vggt_patch_size": 14, - "anchor_view": 0, - "fusion_vggt_layers": [ - 4, - 7, - 11, - 14, - 17, - 19, - 21, - 23 - ], - "fusion_dit_blocks": [ - 7, - 10, - 13, - 16, - 19, - 22, - 25, - 28 - ], - "cond_fusion_hidden_dim": 1024, - "dit_to_vggt_gate_cap": 1 - } - }, - "decoder": { - "normalization": null, - "checkpoint": { - "repo_id": "microsoft/TRELLIS-image-large", - "filename": "ckpts/ss_dec_conv3d_16l8_fp16", - "revision": "25e0d31ffbebe4b5a97464dd851910efc3002d96" - } - }, - "weights": { - "dit_base": { - "repo_id": "microsoft/TRELLIS.2-4B", - "filename": "ckpts/ss_flow_img_dit_1_3B_64_bf16.safetensors", - "revision": "af44b45f2e35a493886929c6d786e563ec68364d" - }, - "vggt_base": "uniforge3d/vggt/uniforge3d_stage1_structure_vggt_backbone.pt", - "dit_lora": { - "rank": 64, - "alpha": 128, - "target_modules": [ - "blocks.*.self_attn.to_qkv", - "blocks.*.self_attn.to_out", - "blocks.*.cross_attn.to_q", - "blocks.*.cross_attn.to_kv", - "blocks.*.cross_attn.to_out" - ] - }, - "vggt_lora": { - "rank": 32, - "alpha": 32, - "target_modules": [ - "aggregator.frame_blocks.*.attn.qkv", - "aggregator.frame_blocks.*.attn.proj", - "aggregator.frame_blocks.*.mlp.fc1", - "aggregator.frame_blocks.*.mlp.fc2", - "aggregator.global_blocks.*.attn.qkv", - "aggregator.global_blocks.*.attn.proj", - "aggregator.global_blocks.*.mlp.fc1", - "aggregator.global_blocks.*.mlp.fc2", - "point_head*" - ] - }, - "checkpoint": "uniforge3d/stage1/uniforge3d_stage1_structure_joint_model.pt" - } - }, - "structured_latent_512": { - "sampler": { - "name": "cfg", - "args": { - "sigma_min": 1e-05 - }, - "params": { - "steps": 20, - "guidance_strength": 3, - "guidance_rescale": 0, - "rescale_t": 1 - } - }, - "model": { - "name": "VGGTConditionedSLatFlowModel", - "args": { - "denoiser_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, - "routed_layers": [ - 5, - 7, - 10, - 12, - 15, - 17, - 20, - 22, - 25, - 27 - ] - }, - "adapter_args": { - "feature_layers": [ - 4, - 11, - 17, - 23 - ], - "feature_dim": 2048, - "per_layer_dim": 1024, - "hidden_dim": 4096, - "output_dim": 1024 - } - } - }, - "decoder": { - "resolution": 512, - "normalization": { - "mean": [ - 0.781296, - 0.018091, - -0.495192, - -0.558457, - 1.06053, - 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.22078, - 1.621212, - 0.87723, - 0.567247, - -3.175944, - -3.186688, - 1.578665 - ], - "std": [ - 5.972266, - 4.706852, - 5.44501, - 5.209927, - 5.32022, - 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.10393, - 5.41767, - 5.269677, - 5.547194, - 5.634698, - 5.235274, - 6.110351, - 5.511298, - 6.237273, - 4.879207, - 5.347008, - 5.405691 - ] - }, - "checkpoint": { - "repo_id": "microsoft/TRELLIS.2-4B", - "filename": "ckpts/shape_dec_next_dc_f16c32_fp16", - "revision": "af44b45f2e35a493886929c6d786e563ec68364d" - } - }, - "conditioning": { - "image_size": 512, - "grid_resolution": 32 - }, - "weights": { - "checkpoint": "uniforge3d/shape512/uniforge3d_stage2_shape512_denoiser.pt", - "adapter_checkpoint": "uniforge3d/shape512/uniforge3d_stage2_shape512_vggt_adapter.pt", - "lora": { - "r": 128, - "lora_alpha": 256, - "lora_dropout": 0, - "target_modules": [ - "to_q", - "to_kv", - "to_out", - "to_qkv" - ], - "bias": "none" - } - } - }, - "structured_latent_1024": { - "sampler": { - "name": "cfg", - "args": { - "sigma_min": 1e-05 - }, - "params": { - "steps": 20, - "guidance_strength": 6.5, - "guidance_rescale": 0.3, - "rescale_t": 1 - } - }, - "model": { - "name": "VGGTConditionedSLatFlowModel", - "args": { - "denoiser_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, - "routed_layers": [ - 5, - 7, - 10, - 12, - 15, - 17, - 20, - 22, - 25, - 27 - ] - }, - "adapter_args": { - "feature_layers": [ - 4, - 11, - 17, - 23 - ], - "feature_dim": 2048, - "per_layer_dim": 1024, - "hidden_dim": 4096, - "output_dim": 1024, - "input_patch_grid_size": 32, - "upsample_scale": 2 - } - } - }, - "decoder": { - "resolution": 1024, - "normalization": { - "mean": [ - 0.781296, - 0.018091, - -0.495192, - -0.558457, - 1.06053, - 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.22078, - 1.621212, - 0.87723, - 0.567247, - -3.175944, - -3.186688, - 1.578665 - ], - "std": [ - 5.972266, - 4.706852, - 5.44501, - 5.209927, - 5.32022, - 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.10393, - 5.41767, - 5.269677, - 5.547194, - 5.634698, - 5.235274, - 6.110351, - 5.511298, - 6.237273, - 4.879207, - 5.347008, - 5.405691 - ] - }, - "checkpoint": { - "repo_id": "microsoft/TRELLIS.2-4B", - "filename": "ckpts/shape_dec_next_dc_f16c32_fp16", - "revision": "af44b45f2e35a493886929c6d786e563ec68364d" - } - }, - "conditioning": { - "image_size": 1024, - "grid_resolution": 64 - }, - "weights": { - "checkpoint": "uniforge3d/shape1024/uniforge3d_stage2_shape1024_denoiser.pt", - "adapter_checkpoint": "uniforge3d/shape1024/uniforge3d_stage2_shape1024_vggt_adapter.pt", - "lora": { - "r": 128, - "lora_alpha": 256, - "lora_dropout": 0, - "target_modules": [ - "to_q", - "to_kv", - "to_out", - "to_qkv" - ], - "bias": "none" - } - } - }, - "structured_latent_handoff": { - "target_max_side": 0.9998, - "surface_voxel_resolution": 64 - }, - "mesh_postprocess": { - "grid_size": 1024, - "pre_simplify_target": 16777216, - "decimation_target": 1000000, - "remesh_band": 1, - "remesh_project": 0 - }, - "texture": { - "resolution": 1024, - "texture_size": 2048, - "decimation_target": 1000000, - "model": { - "name": "VGGTConditionedSLatFlowModel", - "args": { - "denoiser_args": { - "resolution": 64, - "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, - "routed_layers": [ - 5, - 7, - 10, - 12, - 15, - 17, - 20, - 22, - 25, - 27 - ] - }, - "adapter_args": { - "feature_layers": [ - 4, - 11, - 17, - 23 - ], - "feature_dim": 2048, - "per_layer_dim": 1024, - "hidden_dim": 4096, - "output_dim": 1024, - "input_patch_grid_size": 32, - "upsample_scale": 2 - } - } - }, - "sampler": { - "args": { - "sigma_min": 1e-05 - }, - "params": { - "steps": 20, - "guidance_strength": 2.5, - "guidance_interval": [ - 0, - 1 - ], - "guidance_rescale": 0, - "rescale_t": 1.5 - } - }, - "shape_slat_normalization": { - "mean": [ - 0.781296, - 0.018091, - -0.495192, - -0.558457, - 1.06053, - 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.22078, - 1.621212, - 0.87723, - 0.567247, - -3.175944, - -3.186688, - 1.578665 - ], - "std": [ - 5.972266, - 4.706852, - 5.44501, - 5.209927, - 5.32022, - 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.10393, - 5.41767, - 5.269677, - 5.547194, - 5.634698, - 5.235274, - 6.110351, - 5.511298, - 6.237273, - 4.879207, - 5.347008, - 5.405691 - ] - }, - "texture_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.293, - -1.925608, - -1.217717, - 1.213905, - 0.971588, - -0.023631, - 0.10675, - 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.26014, - 2.874801, - 2.810596, - 3.29272, - 2.674999, - 2.680878, - 2.372054, - 2.451546, - 2.353556, - 2.995195, - 2.379849, - 2.786195, - 2.77519 - ] - }, - "shape_decoder_checkpoint": { - "repo_id": "microsoft/TRELLIS.2-4B", - "filename": "ckpts/shape_dec_next_dc_f16c32_fp16", - "revision": "af44b45f2e35a493886929c6d786e563ec68364d" - }, - "texture_decoder_checkpoint": { - "repo_id": "microsoft/TRELLIS.2-4B", - "filename": "ckpts/tex_dec_next_dc_f16c32_fp16", - "revision": "af44b45f2e35a493886929c6d786e563ec68364d" - }, - "weights": { - "checkpoint": "uniforge3d/texture/uniforge3d_stage3_texture1024_denoiser.pt", - "adapter_checkpoint": "uniforge3d/texture/uniforge3d_stage3_texture1024_vggt_adapter.pt", - "lora": { - "r": 128, - "lora_alpha": 256, - "lora_dropout": 0, - "target_modules": [ - "to_q", - "to_kv", - "to_out", - "to_qkv" - ], - "bias": "none" - } - } - }, - "image_preprocess": { - "alpha_threshold": 0, - "padding_factor": 1, - "rembg_model": "briaai/RMBG-2.0" - }, - "format_version": 1, - "default_seed": 42, - "conditioner": { - "vggt_feature_extractor": { - "feature_layers": [ - 4, - 11, - 17, - 23 - ], - "shape_grid_resolution": 64, - "conditioning_layers": [ - 4, - 7, - 11, - 14, - 17, - 20, - 23 - ], - "dtype": "bfloat16", - "checkpoint_path": "uniforge3d/vggt/uniforge3d_shape_texture_vggt_conditioner.pt" - }, - "voxel_routers": { - "32": { - "confidence_keep_ratio": 0.95, - "component_iterations": 64, - "grid_resolution": 32, - "patch_grid_size": 32, - "image_size": 448 - }, - "64": { - "confidence_keep_ratio": 0.95, - "component_iterations": 64, - "grid_resolution": 64, - "patch_grid_size": 64, - "image_size": 448 - } - } - } -} diff --git a/uniforge3d/models/__init__.py b/uniforge3d/models/__init__.py deleted file mode 100644 index 52493d5e7aa9cfb662d853728c0a68e8530b5e87..0000000000000000000000000000000000000000 --- a/uniforge3d/models/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -"""UniForge3D model architectures and local checkpoint loading.""" - -import importlib - -_MODEL_MODULES = { - "SparseStructureDecoder": "vaes.sparse_structure", - "SparseStructureFlowModel": "sparse_structure_flow", - "JointDiTVGGTStage1Model": "joint_dit_vggt_stage1", - "SLatFlowModel": "structured_latent_flow", - "RoutedFullOnlySLatFlowModel": "structured_latent_flow", - "FlexiDualGridVaeDecoder": "vaes.flexi_dual_grid", - "SparseUnetVaeDecoder": "vaes.sparse_unet", -} - -__all__ = list(_MODEL_MODULES) - - -def __getattr__(name: str): - if name not in _MODEL_MODULES: - raise AttributeError(f"module {__name__} has no attribute {name}") - module = importlib.import_module(f".{_MODEL_MODULES[name]}", __name__) - value = getattr(module, name) - globals()[name] = value - return value diff --git a/uniforge3d/models/conditioning.py b/uniforge3d/models/conditioning.py deleted file mode 100644 index e7560f05ed05f9583f19aee8189317de99a55d43..0000000000000000000000000000000000000000 --- a/uniforge3d/models/conditioning.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Fuse cached DINO features with structure-conditioned VGGT features and select views.""" - -from __future__ import annotations - -from typing import Any - -import torch - -from .vggt_routed_features import FrozenRoutedVGGTFeatureExtractor -from .view_router import GPUVoxelViewRouter - - -class StructuredLatentConditioner: - """Share one frozen VGGT and the 32/64-grid routers across all stages.""" - - def __init__( - self, - *, - vggt_feature_extractor: dict[str, Any], - voxel_routers: dict[int, dict[str, Any]], - ): - extractor_args = dict(vggt_feature_extractor) - extractor_args["device"] = torch.device("cpu") - self.frozen_vggt = FrozenRoutedVGGTFeatureExtractor(**extractor_args) - self.routers = { - int(grid): GPUVoxelViewRouter(**dict(router_config)) - for grid, router_config in voxel_routers.items() - } - - def to(self, device: str | torch.device) -> "StructuredLatentConditioner": - device = torch.device(device) - frozen = self.frozen_vggt - for name in ( - "aggregator", - "shape_encoder", - "backbone_shape_adapters", - "point_head", - "dpt_shape_adapter_32", - ): - module = getattr(frozen, name, None) - if module is not None: - module.to(device) - frozen.device = device - return self - - @torch.no_grad() - def encode( - self, - adapter: torch.nn.Module, - dino_features: torch.Tensor, - vggt_images: torch.Tensor, - structure_conditioned_coords: torch.Tensor, - input_masks: torch.Tensor, - *, - latent_coords: torch.Tensor | None = None, - router_grid: int | None = None, - view_assignment: dict[str, torch.Tensor] | None = None, - ) -> dict[str, Any]: - """Build CFG conditions for one case from [N,4] (batch,x,y,z) coords64. - - A view assignment can be reused from Shape1024; packed attention layouts - are built separately by the denoiser for its exact sparse-row order. - """ - packed = structure_conditioned_coords[:, 1:].to( - device=dino_features.device, dtype=torch.int32 - ).contiguous() - offsets = torch.tensor([0, len(packed)], device=packed.device, dtype=torch.long) - dino_bank = dino_features.contiguous() - cached, patch_start, points, confidence = self.frozen_vggt( - vggt_images, packed, offsets, return_points=view_assignment is None - ) - - with torch.autocast( - device_type=dino_features.device.type, dtype=torch.bfloat16, - ): - vggt_delta = adapter(cached, patch_start) - patch_count = int(vggt_delta.shape[2]) - special_tokens = int(dino_bank.shape[2]) - patch_count - if special_tokens != 5: - raise RuntimeError( - f"Expected five DINO special tokens, got dino={dino_bank.shape[2]} vggt={patch_count}" - ) - dino_patch = dino_bank[:, :, special_tokens:] - fused_bank = dino_bank.clone() - fused_bank[:, :, special_tokens:] = dino_patch + vggt_delta.to( - device=dino_patch.device, dtype=dino_patch.dtype - ) - - if view_assignment is None: - router = self.routers[router_grid] - target_coords = ( - latent_coords - if latent_coords is not None - else structure_conditioned_coords - ).to(device=packed.device, dtype=torch.long) - view_assignment = router( - points, - confidence, - input_masks, - target_coords=target_coords, - ) - else: - view_assignment = {name: value.to(fused_bank.device) for name, value in view_assignment.items()} - positive = {"full_bank": fused_bank, **view_assignment} - negative = { - "full_bank": torch.zeros_like(fused_bank), - "selected_view": torch.zeros_like(view_assignment["selected_view"]), - } - return {"cond": positive, "neg_cond": negative} diff --git a/uniforge3d/models/dino.py b/uniforge3d/models/dino.py deleted file mode 100644 index 4f7afdef60e623c54bd23da6d559d72204de472a..0000000000000000000000000000000000000000 --- a/uniforge3d/models/dino.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Shared frozen DINOv3 encoder for Stage1 and structured-latent conditioning.""" - -from __future__ import annotations - -import torch -import torch.nn as nn -import torch.nn.functional as F -from transformers import DINOv3ViTModel - - -class DinoV3Encoder(nn.Module): - """Run the exact DINOv3 feature path used by the released checkpoints. - - Four-dimensional inputs preserve the model output dtype used by the shape - conditioners. Five-dimensional multiview inputs are restored to - ``[B, V, N, C]`` and converted to float32 as required by Stage1. - """ - - def __init__(self, model_name: str, **download_kwargs): - super().__init__() - self.model = DINOv3ViTModel.from_pretrained( - model_name, torch_dtype=torch.float32, **download_kwargs, - ).eval() - self.register_buffer( - "_mean", - torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1), - persistent=False, - ) - self.register_buffer( - "_std", - torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1), - persistent=False, - ) - self.model.requires_grad_(False) - - @torch.no_grad() - def forward(self, images: torch.Tensor) -> torch.Tensor: - multiview = images.ndim == 5 - if multiview: - batch, views, channels, height, width = images.shape - flat = images.reshape(batch * views, channels, height, width) - elif images.ndim == 4: - batch = views = None - flat = images - height, width = flat.shape[-2:] - else: - raise ValueError(f"Expected DINO images [B,3,H,W] or [B,V,3,H,W], got {tuple(images.shape)}") - - if flat.shape[1] != 3 or height != width: - raise ValueError(f"Expected square RGB DINO input, got {tuple(images.shape)}") - - mean = self._mean.to(device=flat.device, dtype=flat.dtype) - std = self._std.to(device=flat.device, dtype=flat.dtype) - value = ((flat - mean) / std).to(self.model.embeddings.patch_embeddings.weight.dtype) - hidden = self.model.embeddings(value, bool_masked_pos=None) - position = self.model.rope_embeddings(value) - for layer in self.model.layer: - hidden = layer(hidden, position_embeddings=position) - hidden = F.layer_norm(hidden, hidden.shape[-1:]) - - if multiview: - return hidden.reshape(batch, views, hidden.shape[1], hidden.shape[2]).float() - return hidden diff --git a/uniforge3d/models/joint_dit_vggt_stage1.py b/uniforge3d/models/joint_dit_vggt_stage1.py deleted file mode 100644 index 26cde123a59ae5afed351cd37fb87bfe5114b620..0000000000000000000000000000000000000000 --- a/uniforge3d/models/joint_dit_vggt_stage1.py +++ /dev/null @@ -1,383 +0,0 @@ -"""Inference-only Stage1 DiT/VGGT model topology.""" - -from __future__ import annotations - -import math -from typing import Any, Sequence - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from uniforge3d.models.vggt.models.aggregator import slice_expand_and_flatten -from uniforge3d.models.vggt.models.vggt import VGGT - -from ..modules.utils import manual_cast -from .sparse_structure_flow import SparseStructureFlowModel - - -def _square_grid_size(num_tokens: int) -> tuple[int, int]: - size = int(round(math.sqrt(int(num_tokens)))) - if size * size != int(num_tokens): - raise ValueError(f"Expected a square token grid, got {num_tokens} tokens") - return size, size - - -def _vggt_patch_map(tokens: torch.Tensor, patch_start_idx: int) -> torch.Tensor: - batch, views, _token_count, channels = tokens.shape - patch_tokens = tokens[:, :, patch_start_idx:] - height, width = _square_grid_size(patch_tokens.shape[2]) - return ( - patch_tokens.reshape(batch * views, height, width, channels) - .permute(0, 3, 1, 2) - .contiguous() - ) - - -def _align_vggt_condition( - frame_tokens: torch.Tensor, - global_tokens: torch.Tensor, - patch_start_idx: int, - target_hw: tuple[int, int], -) -> torch.Tensor: - frame_map = _vggt_patch_map(frame_tokens, patch_start_idx) - global_map = _vggt_patch_map(global_tokens, patch_start_idx) - if tuple(frame_map.shape[-2:]) != target_hw: - raise ValueError( - f"VGGT patch grid {tuple(frame_map.shape[-2:])} does not match " - f"DINO condition grid {target_hw}" - ) - return torch.cat((frame_map, global_map), dim=1) - - -class BlockDinoCondDeltaMLP(nn.Module): - """Block-specific zero-init residual on DINO patch tokens, predicted from aligned VGGT features.""" - - def __init__(self, dim: int = 1024, hidden_dim: int = 1024, special_tokens: int = 5): - super().__init__() - self.dim = int(dim) - self.special_tokens = int(special_tokens) - self.net = nn.Sequential( - nn.GroupNorm(32, self.dim * 2), - nn.Conv2d(self.dim * 2, int(hidden_dim), kernel_size=1), - nn.GELU(), - nn.Conv2d(int(hidden_dim), int(hidden_dim), kernel_size=3, padding=1, groups=int(hidden_dim)), - nn.GELU(), - nn.Conv2d(int(hidden_dim), self.dim, kernel_size=1), - ) - nn.init.zeros_(self.net[-1].weight) - nn.init.zeros_(self.net[-1].bias) - - def forward(self, dino_cond_bank: torch.Tensor, aligned_vggt: torch.Tensor) -> torch.Tensor: - if dino_cond_bank.ndim != 4: - raise ValueError(f"Expected dino_cond_bank [B,V,N,C], got {tuple(dino_cond_bank.shape)}") - batch, views, cond_tokens, dim = dino_cond_bank.shape - if dim != self.dim: - raise ValueError(f"Expected cond dim={self.dim}, got {dim}") - cond_patch_tokens = int(cond_tokens) - self.special_tokens - cond_hw = _square_grid_size(cond_patch_tokens) - expected_shape = (batch * views, self.dim * 2, cond_hw[0], cond_hw[1]) - if tuple(aligned_vggt.shape) != expected_shape: - raise ValueError(f"Expected aligned_vggt {expected_shape}, got {tuple(aligned_vggt.shape)}") - delta = self.net(aligned_vggt).permute(0, 2, 3, 1).reshape(batch, views, cond_patch_tokens, dim) - out = dino_cond_bank.clone() - out[:, :, self.special_tokens:] = out[:, :, self.special_tokens:] + delta.to(dtype=out.dtype) - return out - - -class DiTToVGGTResidual(nn.Module): - """Inject a timestep-modulated DiT residual into the VGGT token stream.""" - - def __init__( - self, - vggt_dim: int, - dit_dim: int, - t_dim: int, - heads: int = 8, - gate_cap: float = 1.0, - ): - super().__init__() - self.gate_cap = float(gate_cap) - self.norm_q = nn.LayerNorm(vggt_dim) - self.norm_ctx = nn.LayerNorm(dit_dim) - self.attn = nn.MultiheadAttention( - vggt_dim, - heads, - kdim=dit_dim, - vdim=dit_dim, - batch_first=True, - ) - self.delta_proj = nn.Linear(vggt_dim, vggt_dim) - self.t_mod = nn.Sequential(nn.SiLU(), nn.Linear(t_dim, vggt_dim * 3)) - nn.init.zeros_(self.t_mod[-1].weight) - nn.init.zeros_(self.t_mod[-1].bias) - - def forward( - self, - vggt_tokens: torch.Tensor, - dit_tokens: torch.Tensor, - t_emb: torch.Tensor, - ) -> torch.Tensor: - q = self.norm_q(vggt_tokens) - ctx = self.norm_ctx(dit_tokens) - shift, scale, gate = self.t_mod(t_emb).chunk(3, dim=-1) - shift = shift[:, None, :].to(dtype=q.dtype) - scale = scale[:, None, :].to(dtype=q.dtype) - gate = gate[:, None, :].to(dtype=q.dtype) - q = q * (1.0 + scale) + shift - h, _ = self.attn(q, ctx, ctx, need_weights=False) - delta = self.delta_proj(h) - return vggt_tokens + self.gate_cap * gate.to(dtype=delta.dtype) * delta - - -class JointDiTVGGTStage1Model(nn.Module): - """Inference-only Stage1 sparse-structure model with DINO/VGGT fusion.""" - - def __init__( - self, - *, - dit_args: dict[str, Any], - dino_image_size: int, - vggt_img_size: int = 518, - vggt_patch_size: int = 14, - fusion_vggt_layers: Sequence[int] = (2, 5, 8, 11, 14, 17, 20, 23), - fusion_dit_blocks: Sequence[int] = (3, 7, 11, 15, 19, 23, 26, 29), - anchor_view: int = 0, - cond_fusion_hidden_dim: int = 1024, - dit_to_vggt_gate_cap: float = 0.1, - ): - super().__init__() - self.anchor_view = int(anchor_view) - dino_image_size = int(dino_image_size) - self.dino_tokens = (dino_image_size // 16) ** 2 + 5 - self.dit = SparseStructureFlowModel(**dit_args) - self.vggt = VGGT( - img_size=vggt_img_size, - patch_size=vggt_patch_size, - enable_camera=False, - enable_point=True, - ) - # Stage1 never supplies patch masks, so masked-pretraining state is omitted. - self.vggt.aggregator.patch_embed.mask_token = None - - fusion_dit_blocks = tuple(int(index) for index in fusion_dit_blocks) - self.vggt_to_block = dict(zip(fusion_vggt_layers, fusion_dit_blocks)) - t_dim = self.dit.model_channels - z_dim = self.dit.model_channels - f_dim = 1024 - total_dit_blocks = int(len(self.dit.blocks)) - stage_boundaries = (*fusion_dit_blocks, total_dit_blocks) - self.dit_stage_blocks = { - start: tuple(range(start, min(end, total_dit_blocks))) - for start, end in zip(stage_boundaries, stage_boundaries[1:]) - if start < total_dit_blocks - } - all_fusion_dit_blocks = sorted( - {block_idx for stage_blocks in self.dit_stage_blocks.values() for block_idx in stage_blocks} - ) - self.cond_delta_mlps = nn.ModuleDict( - { - str(block_idx): BlockDinoCondDeltaMLP(f_dim, hidden_dim=cond_fusion_hidden_dim) - for block_idx in all_fusion_dit_blocks - } - ) - self.dit_to_vggt = nn.ModuleDict( - { - str(block_idx): DiTToVGGTResidual( - vggt_dim=f_dim, - dit_dim=z_dim, - t_dim=t_dim, - heads=8, - gate_cap=dit_to_vggt_gate_cap, - ) - for block_idx in fusion_dit_blocks - } - ) - - @staticmethod - def _flatten_condition(cond_bank: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: - if cond_bank.ndim != 4: - raise ValueError(f"Expected condition bank [B,V,N,C], got {tuple(cond_bank.shape)}") - batch, views, tokens, channels = cond_bank.shape - return manual_cast(cond_bank.reshape(batch, views * tokens, channels), dtype) - - def _zero_condition( - self, - batch_size: int, - device: torch.device, - dtype: torch.dtype, - ) -> torch.Tensor: - dim = int(getattr(self.dit, "cond_channels", self.dit.model_channels)) - return torch.zeros( - int(batch_size), - self.dino_tokens, - dim, - device=device, - dtype=dtype, - ) - - def forward_unconditional( - self, - x_t: torch.Tensor, - t: torch.Tensor, - ) -> torch.Tensor: - - cond = self._zero_condition( - batch_size=x_t.shape[0], - device=x_t.device, - dtype=x_t.dtype, - ) - return self.dit(x_t, t.to(dtype=torch.float32) * 1000.0, cond) - - def forward( - self, - x_t: torch.Tensor, - t: torch.Tensor, - vggt_images: torch.Tensor, - dino_features: torch.Tensor, - ) -> torch.Tensor: - """Predict velocity conditioned on the input views.""" - if vggt_images.ndim != 5: - raise ValueError("Stage1 VGGT images must be [B,V,3,H,W]") - expected_features = (*vggt_images.shape[:2], self.dino_tokens, 1024) - if tuple(dino_features.shape) != expected_features: - raise ValueError( - f"Expected cached Stage1 DINO features {expected_features}, " - f"got {tuple(dino_features.shape)}" - ) - anchor_idx = min(max(self.anchor_view, 0), vggt_images.shape[1] - 1) - cond = dino_features[:, anchor_idx] - return self.forward_joint_with_fusion( - x_t, - t, - cond, - vggt_images, - dino_cond_bank=dino_features, - ) - - def _init_vggt_tokens(self, images: torch.Tensor): - aggregator = self.vggt.aggregator - bsz, views, channels, height, width = images.shape - if channels != 3: - raise ValueError(f"Expected 3 input channels, got {channels}") - - images = (images - aggregator._resnet_mean) / aggregator._resnet_std - flat_images = images.view(bsz * views, channels, height, width) - patch_tokens = aggregator.patch_embed(flat_images) - if isinstance(patch_tokens, dict): - patch_tokens = patch_tokens["x_norm_patchtokens"] - - camera_token = slice_expand_and_flatten(aggregator.camera_token, bsz, views) - register_token = slice_expand_and_flatten(aggregator.register_token, bsz, views) - tokens = torch.cat([camera_token, register_token, patch_tokens], dim=1) - - pos = None - if aggregator.rope is not None: - pos = aggregator.position_getter( - bsz * views, - height // aggregator.patch_size, - width // aggregator.patch_size, - device=images.device, - ) - - if aggregator.patch_start_idx > 0 and pos is not None: - pos = pos + 1 - pos_special = torch.zeros( - bsz * views, - aggregator.patch_start_idx, - 2, - device=images.device, - dtype=pos.dtype, - ) - pos = torch.cat([pos_special, pos], dim=1) - - _, token_count, embed_dim = tokens.shape - return tokens, pos, bsz, views, token_count, embed_dim, aggregator.patch_start_idx - - def forward_joint_with_fusion( - self, - x: torch.Tensor, - t: torch.Tensor, - cond: torch.Tensor, - vggt_images: torch.Tensor, - dino_cond_bank: torch.Tensor, - ) -> torch.Tensor: - assert [*x.shape] == [x.shape[0], self.dit.in_channels, *[self.dit.resolution] * 3], ( - f"Input shape mismatch, got {x.shape}" - ) - h = x.view(*x.shape[:2], -1).permute(0, 2, 1).contiguous() - h = self.dit.input_layer(h) - if self.dit.pe_mode == "ape": - h = h + self.dit.pos_emb[None] - t_raw = self.dit.t_embedder(t * 1000.0) - t_mod = self.dit.adaLN_modulation(t_raw) if self.dit.share_mod else t_raw - t_mod = manual_cast(t_mod, self.dit.dtype) - h = manual_cast(h, self.dit.dtype) - cond = manual_cast(cond, self.dit.dtype) - - aggregator = self.vggt.aggregator - tokens, pos, bsz, views, token_count, embed_dim, patch_start_idx = self._init_vggt_tokens(vggt_images) - dino_cond_bank = dino_cond_bank[:, :views].to(device=cond.device, dtype=cond.dtype).contiguous() - - frame_idx = 0 - global_idx = 0 - next_dit_block = 0 - - for layer_idx in range(aggregator.depth): - tokens, frame_idx, frame_intermediates = aggregator._process_frame_attention( - tokens, bsz, views, token_count, embed_dim, frame_idx, pos=pos - ) - tokens, global_idx, global_intermediates = aggregator._process_global_attention( - tokens, bsz, views, token_count, embed_dim, global_idx, pos=pos - ) - - frame_tokens = frame_intermediates[-1] - global_tokens = global_intermediates[-1] - if layer_idx in self.vggt_to_block: - stage_start_block = int(self.vggt_to_block[layer_idx]) - stage_blocks = self.dit_stage_blocks[stage_start_block] - global_tokens_raw = global_tokens - while next_dit_block < stage_start_block: - h = self.dit.blocks[next_dit_block](h, t_mod, cond, self.dit.rope_phases) - next_dit_block += 1 - - cond_patch_tokens = int(dino_cond_bank.shape[2]) - 5 - cond_hw = _square_grid_size(cond_patch_tokens) - aligned_vggt = _align_vggt_condition( - frame_tokens, - global_tokens_raw, - patch_start_idx, - cond_hw, - ) - - for block_idx in stage_blocks: - if next_dit_block != block_idx: - raise RuntimeError(f"Expected DiT block {block_idx}, got {next_dit_block}") - fused_cond = self.cond_delta_mlps[str(block_idx)](dino_cond_bank, aligned_vggt) - block_context = self._flatten_condition(fused_cond, self.dit.dtype) - h = self.dit.blocks[block_idx](h, t_mod, block_context, self.dit.rope_phases) - next_dit_block += 1 - - # Write the completed DiT stage back to the VGGT global stream. - f_query_tokens = manual_cast(global_tokens_raw, self.dit.dtype) - batch_q, views_q, query_tokens, dim_q = f_query_tokens.shape - f_query_flat = f_query_tokens.reshape(batch_q, views_q * query_tokens, dim_q) - f_fused_flat = self.dit_to_vggt[str(stage_start_block)]( - f_query_flat, - h, - t_raw, - ) - global_tokens_fused = f_fused_flat.reshape(batch_q, views_q, query_tokens, dim_q) - global_tokens = manual_cast(global_tokens_fused, global_tokens_raw.dtype) - tokens = global_tokens.reshape(bsz * views, token_count, embed_dim) - - while next_dit_block < len(self.dit.blocks): - block = self.dit.blocks[next_dit_block] - h = block(h, t_mod, cond, self.dit.rope_phases) - next_dit_block += 1 - - h = manual_cast(h, x.dtype) - h = F.layer_norm(h, h.shape[-1:]) - h = self.dit.out_layer(h) - h = h.permute(0, 2, 1).view(h.shape[0], h.shape[2], *[self.dit.resolution] * 3).contiguous() - return h diff --git a/uniforge3d/models/loaders.py b/uniforge3d/models/loaders.py deleted file mode 100644 index 64c45df88dab7b73d542c189a3eeaa791bc0f287..0000000000000000000000000000000000000000 --- a/uniforge3d/models/loaders.py +++ /dev/null @@ -1,200 +0,0 @@ -"""Initialize models and load original training weights over their pretrained bases.""" - -import json -import re -from pathlib import Path -from typing import Any - -import torch -from easydict import EasyDict as edict -from huggingface_hub import hf_hub_download, snapshot_download -from safetensors.torch import load_file, load_model - -from . import __getattr__ as get_model_class -from .conditioning import StructuredLatentConditioner -from .dino import DinoV3Encoder -from .lora import attach_stage1_lora -from .structured_latent_flow import VGGTConditionedSLatFlowModel -from .vaes.flexi_dual_grid import FlexiDualGridVaeDecoder -from .vaes.sparse_structure import SparseStructureDecoder -from .vaes.sparse_unet import SparseUnetVaeDecoder - - -def resolve_checkpoint( - checkpoint: str | Path | dict[str, str], - root: Path, - *, - decoder: bool = False, - cache_dir: str | Path | None = None, - local_files_only: bool = False, -) -> str: - """Resolve a local checkpoint or an explicit Hub reference.""" - if isinstance(checkpoint, (str, Path)): - return str(root / Path(checkpoint).expanduser()) - filename = checkpoint["filename"] - options = { - "repo_id": checkpoint["repo_id"], - "revision": checkpoint.get("revision"), - "cache_dir": cache_dir, - "local_files_only": local_files_only, - } - if decoder: - folder = snapshot_download( - **options, - allow_patterns=[f"{filename}.json", f"{filename}.safetensors"], - ) - return str(Path(folder) / filename) - return hf_hub_download(filename=filename, **options) - - -def _decoder_args(checkpoint: str | Path, expected_name: str) -> dict[str, Any]: - """Read and validate the constructor arguments beside a decoder checkpoint.""" - config_path = Path(f"{checkpoint}.json") - config = json.loads(config_path.read_text(encoding="utf-8")) - if config["name"] != expected_name: - raise ValueError( - f"Expected {expected_name} in {config_path}, found {config['name']}" - ) - return config["args"] - -def _load_decoder_weights(model: torch.nn.Module, checkpoint: str | Path) -> None: - """Strictly load the Safetensors file beside a decoder configuration.""" - weights_path = Path(f"{checkpoint}.safetensors") - load_model(model, weights_path, strict=True, device="cpu") - model.eval().requires_grad_(False) - -def load_shape_decoder( - checkpoint: str | Path, - resolution: int, -) -> FlexiDualGridVaeDecoder: - """Construct the shape decoder and load its frozen inference weights.""" - model = FlexiDualGridVaeDecoder( - **_decoder_args(checkpoint, "FlexiDualGridVaeDecoder") - ) - _load_decoder_weights(model, checkpoint) - model.set_resolution(int(resolution)) - return model - -def load_sparse_structure_decoder(checkpoint: str | Path) -> SparseStructureDecoder: - model = SparseStructureDecoder(**_decoder_args(checkpoint, "SparseStructureDecoder")) - _load_decoder_weights(model, checkpoint) - return model - -def load_texture_decoder(checkpoint: str | Path) -> SparseUnetVaeDecoder: - """Construct the PBR decoder and load its frozen inference weights.""" - model = SparseUnetVaeDecoder( - **_decoder_args(checkpoint, "SparseUnetVaeDecoder") - ) - _load_decoder_weights(model, checkpoint) - return model - -def _read_weights(checkpoint: str) -> dict[str, torch.Tensor]: - if str(checkpoint).endswith(".safetensors"): - return load_file(checkpoint, device="cpu") - state = torch.load(checkpoint, map_location="cpu", mmap=True, weights_only=True) - return state["model"] if "model" in state else state - - -def _load_trainable_weights(model: torch.nn.Module, state: dict[str, torch.Tensor]) -> None: - """A compact checkpoint must cover every trainable parameter over its loaded base.""" - required = {name for name, parameter in model.named_parameters() if parameter.requires_grad} - missing = required - state.keys() - if missing: - raise RuntimeError(f"Missing training weights: {sorted(missing)[:20]}") - result = model.load_state_dict(state, strict=False) - if result.unexpected_keys: - raise RuntimeError(f"Unexpected training weights: {result.unexpected_keys[:20]}") - - -def _load_structure_weights(model: torch.nn.Module, weights: dict) -> None: - # Bases are loaded into FP32 modules, just as in the training constructor. - dit = _read_weights(weights["dit_base"]) - # RoPE phases are deterministic buffers, absent from the official base file. - dit.setdefault("rope_phases", model.dit.rope_phases) - model.dit.load_state_dict(dit, strict=True) - vggt = _read_weights(weights["vggt_base"]) - vggt = {name.removeprefix("model."): value for name, value in vggt.items()} - # The published model omits the unused camera head and mask token. - vggt = { - name: value for name, value in vggt.items() - if not name.startswith("camera_head.") and name != "aggregator.patch_embed.mask_token" - } - model.vggt.load_state_dict(vggt, strict=True) - attach_stage1_lora(model.dit, **weights["dit_lora"]) - attach_stage1_lora(model.vggt, **weights["vggt_lora"]) - - state = _read_weights(weights["checkpoint"]) - state = { - re.sub(r"^fusion_groups\.(\d+)\.f_from_z\.", r"dit_to_vggt.\1.", name): value - for name, value in state.items() - if not re.match(r"^fusion_groups\.\d+\.z_from_f\.", name) - } - _load_trainable_weights(model, state) - model.eval().requires_grad_(False) - - -def _load_flow_model(spec: edict, weights: dict): - if spec.name != "VGGTConditionedSLatFlowModel": - raise ValueError(f"Unsupported flow model: {spec.name}") - model = VGGTConditionedSLatFlowModel(**spec.args) - from peft import LoraConfig, get_peft_model - - if "base_checkpoint" in weights: - model.denoiser.load_state_dict(_read_weights(weights["base_checkpoint"]), strict=True) - model.denoiser.requires_grad_(False) - model.denoiser = get_peft_model(model.denoiser, LoraConfig(**weights["lora"])) - state = _read_weights(weights["checkpoint"]) - if "base_checkpoint" in weights: - _load_trainable_weights(model.denoiser, state) - else: - model.denoiser.load_state_dict(state, strict=True) - model.adapter.load_state_dict(_read_weights(weights["adapter_checkpoint"]), strict=True) - model.eval().requires_grad_(False) - return model - - -def load_models( - config: dict[str, Any], *, cache_dir: str | Path | None = None, - local_files_only: bool = False, -) -> dict[str, Any]: - - structure = edict(config["sparse_structure"]) - shape512 = edict(config["structured_latent_512"]) - shape1024 = edict(config["structured_latent_1024"]) - texture = edict(config["texture"]) - - dino = DinoV3Encoder( - config["external_models"]["dino"], - cache_dir=cache_dir, local_files_only=local_files_only, - ).eval().requires_grad_(False) - - spec = structure.model - structure_model = get_model_class(spec.name)(**spec.args) - _load_structure_weights(structure_model, structure.weights) - structure_decoder = load_sparse_structure_decoder(structure.decoder.checkpoint) - - shape512_model = _load_flow_model(shape512.model, shape512.weights) - shape512_decoder = load_shape_decoder( - shape512.decoder.checkpoint, int(shape512.decoder.resolution), - ) - - shape1024_model = _load_flow_model(shape1024.model, shape1024.weights) - texture_model = _load_flow_model(texture.model, texture.weights) - shape1024_decoder = load_shape_decoder( - texture.shape_decoder_checkpoint, int(texture.resolution) - ) - texture_decoder = load_texture_decoder(texture.texture_decoder_checkpoint) - - conditioner = StructuredLatentConditioner(**config["conditioner"]) - return { - "dino": dino, - "conditioner": conditioner, - "structure_model": structure_model, - "structure_decoder": structure_decoder, - "shape512_model": shape512_model, - "shape512_decoder": shape512_decoder, - "shape1024_model": shape1024_model, - "shape1024_decoder": shape1024_decoder, - "texture_model": texture_model, - "texture_decoder": texture_decoder, - } diff --git a/uniforge3d/models/lora.py b/uniforge3d/models/lora.py deleted file mode 100644 index 0d2ce0e9abcf9f882d450370ee502ab1ffe87b31..0000000000000000000000000000000000000000 --- a/uniforge3d/models/lora.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Unmerged Stage1 LoRA, with the same operations and FP32 parameters as training.""" - -from fnmatch import fnmatchcase - -import torch -from torch import nn -from torch.nn import functional as F - - -class LoRALinear(nn.Module): - def __init__(self, base: nn.Linear, rank: int, alpha: float): - super().__init__() - self.base = base - self.scaling = alpha / rank - self.lora_A = nn.Parameter(torch.zeros(rank, base.in_features)) - self.lora_B = nn.Parameter(torch.zeros(base.out_features, rank)) - - def forward(self, x): - result = self.base(x) - update = F.linear(F.linear(x, self.lora_A), self.lora_B) - return result + update * self.scaling - - -class LoRAConv2d(nn.Module): - def __init__(self, base: nn.Conv2d, rank: int, alpha: float): - super().__init__() - self.base = base - self.scaling = alpha / rank - self.lora_A = nn.Parameter(torch.zeros(rank, base.in_channels, *base.kernel_size)) - self.lora_B = nn.Parameter(torch.zeros(base.out_channels, rank, 1, 1)) - - def forward(self, x): - result = self.base(x) - update = F.conv2d( - x, self.lora_A, stride=self.base.stride, - padding=self.base.padding, dilation=self.base.dilation, - ) - update = F.conv2d(update, self.lora_B) - return result + update * self.scaling - - -class LoRAConvTranspose2d(nn.Module): - def __init__(self, base: nn.ConvTranspose2d, rank: int, alpha: float): - super().__init__() - self.base = base - self.scaling = alpha / rank - self.lora_A = nn.Parameter(torch.zeros(base.in_channels, rank, *base.kernel_size)) - self.lora_B = nn.Parameter(torch.zeros(base.out_channels, rank, 1, 1)) - - def forward(self, x): - result = self.base(x) - update = F.conv_transpose2d( - x, self.lora_A, stride=self.base.stride, padding=self.base.padding, - output_padding=self.base.output_padding, dilation=self.base.dilation, - ) - update = F.conv2d(update, self.lora_B) - return result + update * self.scaling - - -def attach_stage1_lora(model: nn.Module, *, rank: int, alpha: float, target_modules: list[str]): - wrappers = {nn.Linear: LoRALinear, nn.Conv2d: LoRAConv2d, nn.ConvTranspose2d: LoRAConvTranspose2d} - model.requires_grad_(False) - selected = [ - (name, module) for name, module in model.named_modules() - if type(module) in wrappers and any(fnmatchcase(name, pattern) for pattern in target_modules) - ] - if not selected: - raise ValueError(f"No Stage1 LoRA modules matched {target_modules}") - for name, module in selected: - if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)) and module.groups != 1: - raise ValueError(f"Stage1 LoRA requires groups=1: {name}") - parent, _, child = name.rpartition(".") - setattr(model.get_submodule(parent), child, wrappers[type(module)](module, rank, alpha)) diff --git a/uniforge3d/models/sparse_structure_flow.py b/uniforge3d/models/sparse_structure_flow.py deleted file mode 100644 index da41705761cd5b97666e50e4c5d9278de18536ed..0000000000000000000000000000000000000000 --- a/uniforge3d/models/sparse_structure_flow.py +++ /dev/null @@ -1,246 +0,0 @@ -from functools import partial -from typing import Literal, Optional, Tuple - -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F - -from ..modules.attention import RotaryPositionEmbedder -from ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlock -from ..modules.utils import convert_module_to, manual_cast, str_to_dtype - - -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', - 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.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_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/uniforge3d/models/structured_latent_flow.py b/uniforge3d/models/structured_latent_flow.py deleted file mode 100644 index 66b819d5d957b8b69f4091509d69ef3a00a1cf44..0000000000000000000000000000000000000000 --- a/uniforge3d/models/structured_latent_flow.py +++ /dev/null @@ -1,369 +0,0 @@ -from functools import partial -from typing import Dict, List, Literal, Optional, Tuple, Union - -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F - -from ..modules import sparse as sp -from ..modules.sparse.attention.routed_full_only_flash import ( - PackedRoutedFullOnlyLayoutBuilder, - RoutedFullOnlyFlashCrossAttention, -) -from ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlock -from ..modules.transformer import AbsolutePositionEmbedder -from ..modules.utils import convert_module_to, manual_cast, str_to_dtype -from .sparse_structure_flow import TimestepEmbedder -from .vggt_adapter import VGGT4LayerDINOAdapter - - -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', - 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.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_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 RoutedFullOnlyCrossBlock(ModulatedSparseTransformerCrossBlock): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - old = self.cross_attn - new = RoutedFullOnlyFlashCrossAttention( - old.channels, - old.ctx_channels, - old.num_heads, - old.to_q.bias is not None, - old.qk_rms_norm, - ) - new.to_q.load_state_dict(old.to_q.state_dict()) - new.to_kv.load_state_dict(old.to_kv.state_dict()) - new.to_out.load_state_dict(old.to_out.state_dict()) - if old.qk_rms_norm: - new.q_rms_norm.load_state_dict(old.q_rms_norm.state_dict()) - new.k_rms_norm.load_state_dict(old.k_rms_norm.state_dict()) - self.cross_attn = new - - def forward(self, x, mod, context): - """Evaluate self-attention, routed cross-attention, and FFN.""" - 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) - ) - - def self_part(value): - h = value.replace(self.norm1(value.feats)) - h = h * (1 + scale_msa) + shift_msa - return value + self.self_attn(h) * gate_msa - - def ffn_part(value): - h = value.replace(self.norm3(value.feats)) - h = h * (1 + scale_mlp) + shift_mlp - return value + self.mlp(h) * gate_mlp - - x = self_part(x) - x = x + self.cross_attn(x.replace(self.norm2(x.feats)), context) - x = ffn_part(x) - return x - - -class RoutedFullOnlySLatFlowModel(SLatFlowModel): - def __init__( - self, - *args, - routed_layers=(5, 7, 10, 12, 15, 17, 20, 22, 25, 27), - **kwargs, - ): - self.routed_layers = tuple(map(int, routed_layers)) - super().__init__(*args, **kwargs) - if self.resolution not in (32, 64): - raise ValueError("Routed shape/texture resolution must be 32 or 64") - self.full_tokens = self.resolution ** 2 + 5 - if len(set(self.routed_layers)) != len(self.routed_layers) or any( - index < 0 or index >= self.num_blocks for index in self.routed_layers - ): - raise ValueError(f"invalid routed_layers={self.routed_layers}") - - for index in self.routed_layers: - old = self.blocks[index] - new = RoutedFullOnlyCrossBlock( - self.model_channels, - self.cond_channels, - num_heads=self.num_heads, - mlp_ratio=self.mlp_ratio, - attn_mode="full", - use_rope=self.pe_mode == "rope", - share_mod=self.share_mod, - qk_rms_norm=self.qk_rms_norm, - qk_rms_norm_cross=self.qk_rms_norm_cross, - ) - missing, unexpected = new.load_state_dict(old.state_dict(), strict=False) - if missing or unexpected: - raise RuntimeError((missing, unexpected)) - self.blocks[index] = new - self.blocks[index].cross_attn.full_tokens = self.full_tokens - - self.route_layout_builder = PackedRoutedFullOnlyLayoutBuilder(grid_resolution=self.resolution) - self.convert_to(self.dtype) - - def prepare_condition( - self, - x: sp.SparseTensor, - cond: Dict[str, torch.Tensor], - ) -> Dict[str, torch.Tensor | int]: - """Prepare per-view routing and all-view tokens once before denoising. - - Reuse only while image features, view assignments and sparse-row order - remain unchanged. CFG's positive and negative conditions are separate. - """ - if not isinstance(cond, dict): - raise TypeError("structured routed condition required") - image_features = manual_cast(cond["full_bank"], self.dtype) - if image_features.ndim != 4 or int(image_features.shape[2]) != self.full_tokens: - raise ValueError( - f"Routed condition must be [B,V,{self.full_tokens},C], " - f"got {tuple(image_features.shape)}" - ) - batch_size, num_views = map(int, image_features.shape[:2]) - attention_layout = self.route_layout_builder.prepare( - x=x, - selected_view=cond["selected_view"], - batch_size=batch_size, - views=num_views, - ) - all_view_tokens = image_features.reshape(batch_size, -1, image_features.shape[-1]).contiguous() - return { - **cond, - "full_bank": image_features, - "all_view_tokens": all_view_tokens, - **attention_layout, - } - - def forward( - self, - x: sp.SparseTensor, - t: torch.Tensor, - cond: Dict[str, torch.Tensor | int], - concat_cond: Optional[sp.SparseTensor] = None, - **kwargs, - ): - if concat_cond is not None: - x = sp.sparse_cat([x, concat_cond], dim=-1) - # Samplers prepare both CFG branches once; direct model calls also work. - if "all_view_tokens" not in cond: - cond = self.prepare_condition(x, cond) - - hidden = manual_cast(self.input_layer(x), self.dtype) - time_condition = self.t_embedder(t) - if self.share_mod: - time_condition = self.adaLN_modulation(time_condition) - time_condition = manual_cast(time_condition, self.dtype) - - for index, block in enumerate(self.blocks): - # Routed layers use one selected view per voxel; others use all views. - block_condition = cond if index in self.routed_layers else cond["all_view_tokens"] - hidden = block(hidden, time_condition, block_condition) - - hidden = manual_cast(hidden, x.dtype) - hidden = hidden.replace(F.layer_norm(hidden.feats, hidden.feats.shape[-1:])) - return self.out_layer(hidden) - - -class VGGTConditionedSLatFlowModel(nn.Module): - """One stage model containing its flow denoiser and VGGT-to-DINO adapter.""" - - def __init__(self, denoiser_args: dict, adapter_args: dict) -> None: - super().__init__() - self.denoiser = RoutedFullOnlySLatFlowModel(**denoiser_args) - self.adapter = VGGT4LayerDINOAdapter(**adapter_args) - - @property - def in_channels(self) -> int: - return self.denoiser.in_channels - - def prepare_condition(self, *args, **kwargs): - return self.denoiser.prepare_condition(*args, **kwargs) - - def forward(self, *args, **kwargs): - return self.denoiser(*args, **kwargs) diff --git a/uniforge3d/models/vaes/__init__.py b/uniforge3d/models/vaes/__init__.py deleted file mode 100644 index 01575a4b2f97a464473832440cdf78f75ac6e09c..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vaes/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""VAE network definitions for sparse structure, geometry and PBR decoding.""" diff --git a/uniforge3d/models/vaes/flexi_dual_grid.py b/uniforge3d/models/vaes/flexi_dual_grid.py deleted file mode 100644 index 93f4b98be72fdced10b0d270995089d0d0ac20dc..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vaes/flexi_dual_grid.py +++ /dev/null @@ -1,67 +0,0 @@ -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 import ( - SparseResBlock3d, - SparseConvNeXtBlock3d, - - SparseResBlockDownsample3d, - SparseResBlockUpsample3d, - SparseResBlockS2C3d, - SparseResBlockC2S3d, -) -from .sparse_unet import ( - SparseUnetVaeDecoder, -) -from ...representations import Mesh -from o_voxel.convert import flexible_dual_grid_to_mesh - - -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, **kwargs): - decoded = super().forward(x, **kwargs) - 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/uniforge3d/models/vaes/sparse_structure.py b/uniforge3d/models/vaes/sparse_structure.py deleted file mode 100644 index 8a25f48cd86fd8593b08e0dd55c402e2607442be..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vaes/sparse_structure.py +++ /dev/null @@ -1,175 +0,0 @@ -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 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 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/uniforge3d/models/vaes/sparse_unet.py b/uniforge3d/models/vaes/sparse_unet.py deleted file mode 100644 index ed0de2e4d958ccf17e085796ff6ded0efa58f558..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vaes/sparse_unet.py +++ /dev/null @@ -1,384 +0,0 @@ -from typing import * -import torch -import torch.nn as nn -import torch.nn.functional as F -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', - ): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - self.downsample = downsample - self.upsample = upsample - self.resample_mode = resample_mode - - 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: - return self._forward(x) - - -class SparseResBlockDownsample3d(nn.Module): - def __init__( - self, - channels: int, - out_channels: Optional[int] = None, - ): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - - 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: - return self._forward(x) - - -class SparseResBlockUpsample3d(nn.Module): - def __init__( - self, - channels: int, - out_channels: Optional[int] = None, - pred_subdiv: bool = True, - ): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - 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: - return self._forward(x) - - -class SparseResBlockS2C3d(nn.Module): - def __init__( - self, - channels: int, - out_channels: Optional[int] = None, - ): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - - 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: - return self._forward(x) - - -class SparseResBlockC2S3d(nn.Module): - def __init__( - self, - channels: int, - out_channels: Optional[int] = None, - pred_subdiv: bool = True, - ): - super().__init__() - self.channels = channels - self.out_channels = out_channels or channels - 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: - return self._forward(x, subdiv) - - -class SparseConvNeXtBlock3d(nn.Module): - def __init__( - self, - channels: int, - mlp_ratio: float = 4.0, - ): - super().__init__() - self.channels = channels - - 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: - return self._forward(x) - - -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 = [] - 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: - 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 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) - diff --git a/uniforge3d/models/vggt/__init__.py b/uniforge3d/models/vggt/__init__.py deleted file mode 100644 index 891568debb7d5e17145c49e5b4533658e452060f..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Local VGGT package for the TRELLIS.2 stage2 joint experiment.""" - - diff --git a/uniforge3d/models/vggt/heads/camera_head.py b/uniforge3d/models/vggt/heads/camera_head.py deleted file mode 100644 index 410d3f80b088ed94fddeb867037f1d06ada86f97..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/heads/camera_head.py +++ /dev/null @@ -1,150 +0,0 @@ -# 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. - -import math -import numpy as np - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from uniforge3d.models.vggt.layers import Mlp -from uniforge3d.models.vggt.layers.block import Block -from uniforge3d.models.vggt.heads.head_act import activate_pose - - -class CameraHead(nn.Module): - """ - CameraHead predicts camera parameters from token representations using iterative refinement. - - It applies a series of transformer blocks (the "trunk") to dedicated camera tokens. - """ - - def __init__( - self, - dim_in: int = 2048, - trunk_depth: int = 4, - pose_encoding_type: str = "absT_quaR_FoV", - num_heads: int = 16, - mlp_ratio: int = 4, - init_values: float = 0.01, - trans_act: str = "linear", - quat_act: str = "linear", - fl_act: str = "relu", # Field of view activations: ensures FOV values are positive. - ): - super().__init__() - - if pose_encoding_type == "absT_quaR_FoV": - self.target_dim = 9 - else: - raise ValueError(f"Unsupported camera encoding type: {pose_encoding_type}") - - self.trans_act = trans_act - self.quat_act = quat_act - self.fl_act = fl_act - self.trunk_depth = trunk_depth - - # Build the trunk using a sequence of transformer blocks. - self.trunk = nn.Sequential( - *[ - Block(dim=dim_in, num_heads=num_heads, mlp_ratio=mlp_ratio, init_values=init_values) - for _ in range(trunk_depth) - ] - ) - - # Normalizations for camera token and trunk output. - self.token_norm = nn.LayerNorm(dim_in) - self.trunk_norm = nn.LayerNorm(dim_in) - - # Learnable empty camera pose token. - self.empty_pose_tokens = nn.Parameter(torch.zeros(1, 1, self.target_dim)) - self.embed_pose = nn.Linear(self.target_dim, dim_in) - - # Module for producing modulation parameters: shift, scale, and a gate. - self.poseLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim_in, 3 * dim_in, bias=True)) - - # Adaptive layer normalization without affine parameters. - self.adaln_norm = nn.LayerNorm(dim_in, elementwise_affine=False, eps=1e-6) - self.pose_branch = Mlp(in_features=dim_in, hidden_features=dim_in // 2, out_features=self.target_dim, drop=0) - - def forward(self, aggregated_tokens_list: list, num_iterations: int = 4) -> list: - """ - Forward pass to predict camera parameters. - - Args: - aggregated_tokens_list (list): List of token tensors from the network; - the last tensor is used for prediction. - num_iterations (int, optional): Number of iterative refinement steps. Defaults to 4. - - Returns: - list: A list of predicted camera encodings (post-activation) from each iteration. - """ - # Use tokens from the last block for camera prediction. - tokens = aggregated_tokens_list[-1] - - # Extract the camera tokens - pose_tokens = tokens[:, :, 0] - pose_tokens = self.token_norm(pose_tokens) - - pred_pose_enc_list = self.trunk_fn(pose_tokens, num_iterations) - return pred_pose_enc_list - - def trunk_fn(self, pose_tokens: torch.Tensor, num_iterations: int) -> list: - """ - Iteratively refine camera pose predictions. - - Args: - pose_tokens (torch.Tensor): Normalized camera tokens with shape [B, S, C]. - num_iterations (int): Number of refinement iterations. - - Returns: - list: List of activated camera encodings from each iteration. - """ - B, S, C = pose_tokens.shape - pred_pose_enc = None - pred_pose_enc_list = [] - - for _ in range(num_iterations): - # Use a learned empty pose for the first iteration. - if pred_pose_enc is None: - module_input = self.embed_pose(self.empty_pose_tokens.expand(B, S, -1)) - else: - # Detach the previous prediction to avoid backprop through time. - pred_pose_enc = pred_pose_enc.detach() - module_input = self.embed_pose(pred_pose_enc) - - # Generate modulation parameters and split them into shift, scale, and gate components. - shift_msa, scale_msa, gate_msa = self.poseLN_modulation(module_input).chunk(3, dim=-1) - - # Adaptive layer normalization and modulation. - pose_tokens_modulated = gate_msa * modulate(self.adaln_norm(pose_tokens), shift_msa, scale_msa) - pose_tokens_modulated = pose_tokens_modulated + pose_tokens - - pose_tokens_modulated = self.trunk(pose_tokens_modulated) - # Compute the delta update for the pose encoding. - pred_pose_enc_delta = self.pose_branch(self.trunk_norm(pose_tokens_modulated)) - - if pred_pose_enc is None: - pred_pose_enc = pred_pose_enc_delta - else: - pred_pose_enc = pred_pose_enc + pred_pose_enc_delta - - # Apply final activation functions for translation, quaternion, and field-of-view. - activated_pose = activate_pose( - pred_pose_enc, trans_act=self.trans_act, quat_act=self.quat_act, fl_act=self.fl_act - ) - pred_pose_enc_list.append(activated_pose) - - return pred_pose_enc_list - - -def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: - """ - Modulate the input tensor using scaling and shifting parameters. - """ - # modified from https://github.com/facebookresearch/DiT/blob/796c29e532f47bba17c5b9c5eb39b9354b8b7c64/models.py#L19 - return x * (1 + scale) + shift - diff --git a/uniforge3d/models/vggt/heads/dpt_head.py b/uniforge3d/models/vggt/heads/dpt_head.py deleted file mode 100644 index da0289989db1955e63d23eb6a3040b9a05ef233d..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/heads/dpt_head.py +++ /dev/null @@ -1,485 +0,0 @@ -# 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. - - -# Inspired by https://github.com/DepthAnything/Depth-Anything-V2 - - -import os -from typing import List, Dict, Tuple, Union - -import torch -import torch.nn as nn -import torch.nn.functional as F -from .head_act import activate_head -from .utils import create_uv_grid, position_grid_to_embed - - -class DPTHead(nn.Module): - """ - DPT Head for dense prediction tasks. - - This implementation follows the architecture described in "Vision Transformers for Dense Prediction" - (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer - backbone and produces dense predictions by fusing multi-scale features. - - Args: - dim_in (int): Input dimension (channels). - patch_size (int, optional): Patch size. Default is 14. - output_dim (int, optional): Number of output channels. Default is 4. - activation (str, optional): Activation type. Default is "inv_log". - conf_activation (str, optional): Confidence activation type. Default is "expp1". - features (int, optional): Feature channels for intermediate representations. Default is 256. - out_channels (List[int], optional): Output channels for each intermediate layer. - intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT. - pos_embed (bool, optional): Whether to use positional embedding. Default is True. - feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False. - down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1. - """ - - def __init__( - self, - dim_in: int, - patch_size: int = 14, - output_dim: int = 4, - activation: str = "inv_log", - conf_activation: str = "expp1", - features: int = 256, - out_channels: List[int] = [256, 512, 1024, 1024], - intermediate_layer_idx: List[int] = [4, 11, 17, 23], - pos_embed: bool = True, - feature_only: bool = False, - down_ratio: int = 1, - ) -> None: - super(DPTHead, self).__init__() - self.patch_size = patch_size - self.activation = activation - self.conf_activation = conf_activation - self.pos_embed = pos_embed - self.feature_only = feature_only - self.down_ratio = down_ratio - self.intermediate_layer_idx = intermediate_layer_idx - - self.norm = nn.LayerNorm(dim_in) - - # Projection layers for each output channel from tokens. - self.projects = nn.ModuleList( - [nn.Conv2d(in_channels=dim_in, out_channels=oc, kernel_size=1, stride=1, padding=0) for oc in out_channels] - ) - - # Resize layers for upsampling feature maps. - self.resize_layers = nn.ModuleList( - [ - nn.ConvTranspose2d( - in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0 - ), - nn.ConvTranspose2d( - in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0 - ), - nn.Identity(), - nn.Conv2d( - in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1 - ), - ] - ) - - self.scratch = _make_scratch(out_channels, features, expand=False) - - # Attach additional modules to scratch. - self.scratch.stem_transpose = None - self.scratch.refinenet1 = _make_fusion_block(features) - self.scratch.refinenet2 = _make_fusion_block(features) - self.scratch.refinenet3 = _make_fusion_block(features) - self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False) - - head_features_1 = features - head_features_2 = 32 - - if feature_only: - self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1) - else: - self.scratch.output_conv1 = nn.Conv2d( - head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 - ) - conv2_in_channels = head_features_1 // 2 - - self.scratch.output_conv2 = nn.Sequential( - nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1), - nn.ReLU(inplace=True), - nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), - ) - - def forward( - self, - aggregated_tokens_list: List[torch.Tensor], - images: torch.Tensor, - patch_start_idx: int, - frames_chunk_size: int = 8, - ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: - """ - Forward pass through the DPT head, supports processing by chunking frames. - Args: - aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. - images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. - patch_start_idx (int): Starting index for patch tokens in the token sequence. - Used to separate patch tokens from other tokens (e.g., camera or register tokens). - frames_chunk_size (int, optional): Number of frames to process in each chunk. - If None or larger than S, all frames are processed at once. Default: 8. - - Returns: - Tensor or Tuple[Tensor, Tensor]: - - If feature_only=True: Feature maps with shape [B, S, C, H, W] - - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W] - """ - B, S, _, H, W = images.shape - - # If frames_chunk_size is not specified or greater than S, process all frames at once - if frames_chunk_size is None or frames_chunk_size >= S: - return self._forward_impl(aggregated_tokens_list, images, patch_start_idx) - - # Otherwise, process frames in chunks to manage memory usage - assert frames_chunk_size > 0 - - # Process frames in batches - all_preds = [] - all_conf = [] - - for frames_start_idx in range(0, S, frames_chunk_size): - frames_end_idx = min(frames_start_idx + frames_chunk_size, S) - - # Process batch of frames - if self.feature_only: - chunk_output = self._forward_impl( - aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx - ) - all_preds.append(chunk_output) - else: - chunk_preds, chunk_conf = self._forward_impl( - aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx - ) - all_preds.append(chunk_preds) - all_conf.append(chunk_conf) - - # Concatenate results along the sequence dimension - if self.feature_only: - return torch.cat(all_preds, dim=1) - else: - return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1) - - def _forward_impl( - self, - aggregated_tokens_list: List[torch.Tensor], - images: torch.Tensor, - patch_start_idx: int, - frames_start_idx: int = None, - frames_end_idx: int = None, - ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: - """ - Implementation of the forward pass through the DPT head. - - This method processes a specific chunk of frames from the sequence. - - Args: - aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. - images (Tensor): Input images with shape [B, S, 3, H, W]. - patch_start_idx (int): Starting index for patch tokens. - frames_start_idx (int, optional): Starting index for frames to process. - frames_end_idx (int, optional): Ending index for frames to process. - - Returns: - Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence). - """ - if frames_start_idx is not None and frames_end_idx is not None: - images = images[:, frames_start_idx:frames_end_idx].contiguous() - - B, S, _, H, W = images.shape - - patch_h, patch_w = H // self.patch_size, W // self.patch_size - - out = [] - dpt_idx = 0 - - for layer_idx in self.intermediate_layer_idx: - x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:] - - # Select frames if processing a chunk - if frames_start_idx is not None and frames_end_idx is not None: - x = x[:, frames_start_idx:frames_end_idx] - - x = x.reshape(B * S, -1, x.shape[-1]) - - x = self.norm(x) - - x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) - - x = self.projects[dpt_idx](x) - if self.pos_embed: - x = self._apply_pos_embed(x, W, H) - x = self.resize_layers[dpt_idx](x) - - out.append(x) - dpt_idx += 1 - - # Fuse features from multiple layers. - out = self.scratch_forward(out) - # Interpolate fused output to match target image resolution. - out = custom_interpolate( - out, - (int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)), - mode="bilinear", - align_corners=True, - ) - - if self.pos_embed: - out = self._apply_pos_embed(out, W, H) - - if self.feature_only: - return out.view(B, S, *out.shape[1:]) - - out = self.scratch.output_conv2(out) - preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation) - - preds = preds.view(B, S, *preds.shape[1:]) - conf = conf.view(B, S, *conf.shape[1:]) - return preds, conf - - def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: - """ - Apply positional embedding to tensor x. - """ - patch_w = x.shape[-1] - patch_h = x.shape[-2] - pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device) - pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) - pos_embed = pos_embed * ratio - pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) - return x + pos_embed - - def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor: - """ - Forward pass through the fusion blocks. - - Args: - features (List[Tensor]): List of feature maps from different layers. - - Returns: - Tensor: Fused feature map. - """ - layer_1, layer_2, layer_3, layer_4 = features - - 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) - - out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) - del layer_4_rn, layer_4 - - out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:]) - del layer_3_rn, layer_3 - - out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:]) - del layer_2_rn, layer_2 - - out = self.scratch.refinenet1(out, layer_1_rn) - del layer_1_rn, layer_1 - - out = self.scratch.output_conv1(out) - return out - - -################################################################################ -# Modules -################################################################################ - - -def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module: - return FeatureFusionBlock( - features, - nn.ReLU(inplace=True), - deconv=False, - bn=False, - expand=False, - align_corners=True, - size=size, - has_residual=has_residual, - groups=groups, - ) - - -def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module: - 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 - - -class ResidualConvUnit(nn.Module): - """Residual convolution module.""" - - def __init__(self, features, activation, bn, groups=1): - """Init. - - Args: - features (int): number of features - """ - super().__init__() - - self.bn = bn - self.groups = groups - 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) - - self.norm1 = None - self.norm2 = None - - 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.norm1 is not None: - out = self.norm1(out) - - out = self.activation(out) - out = self.conv2(out) - if self.norm2 is not None: - out = self.norm2(out) - - return self.skip_add.add(out, x) - - -class FeatureFusionBlock(nn.Module): - """Feature fusion block.""" - - def __init__( - self, - features, - activation, - deconv=False, - bn=False, - expand=False, - align_corners=True, - size=None, - has_residual=True, - groups=1, - ): - """Init. - - Args: - features (int): number of features - """ - super(FeatureFusionBlock, self).__init__() - - self.deconv = deconv - self.align_corners = align_corners - self.groups = groups - 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=self.groups - ) - - if has_residual: - self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups) - - self.has_residual = has_residual - self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups) - - self.skip_add = nn.quantized.FloatFunctional() - self.size = size - - def forward(self, *xs, size=None): - """Forward pass. - - Returns: - tensor: output - """ - output = xs[0] - - if self.has_residual: - res = self.resConfUnit1(xs[1]) - output = self.skip_add.add(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 = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners) - output = self.out_conv(output) - - return output - - -def custom_interpolate( - x: torch.Tensor, - size: Tuple[int, int] = None, - scale_factor: float = None, - mode: str = "bilinear", - align_corners: bool = True, -) -> torch.Tensor: - """ - Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate. - """ - if size is None: - size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor)) - - INT_MAX = 1610612736 - - input_elements = size[0] * size[1] * x.shape[0] * x.shape[1] - - if input_elements > INT_MAX: - chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0) - interpolated_chunks = [ - nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks - ] - x = torch.cat(interpolated_chunks, dim=0) - return x.contiguous() - else: - return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners) - diff --git a/uniforge3d/models/vggt/heads/head_act.py b/uniforge3d/models/vggt/heads/head_act.py deleted file mode 100644 index aeac338feadb689acba922cf1402996dacb09ca6..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/heads/head_act.py +++ /dev/null @@ -1,126 +0,0 @@ -# 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. - - -import torch -import torch.nn.functional as F - - -def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"): - """ - Activate pose parameters with specified activation functions. - - Args: - pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length] - trans_act: Activation type for translation component - quat_act: Activation type for quaternion component - fl_act: Activation type for focal length component - - Returns: - Activated pose parameters tensor - """ - T = pred_pose_enc[..., :3] - quat = pred_pose_enc[..., 3:7] - fl = pred_pose_enc[..., 7:] # or fov - - T = base_pose_act(T, trans_act) - quat = base_pose_act(quat, quat_act) - fl = base_pose_act(fl, fl_act) # or fov - - pred_pose_enc = torch.cat([T, quat, fl], dim=-1) - - return pred_pose_enc - - -def base_pose_act(pose_enc, act_type="linear"): - """ - Apply basic activation function to pose parameters. - - Args: - pose_enc: Tensor containing encoded pose parameters - act_type: Activation type ("linear", "inv_log", "exp", "relu") - - Returns: - Activated pose parameters - """ - if act_type == "linear": - return pose_enc - elif act_type == "inv_log": - return inverse_log_transform(pose_enc) - elif act_type == "exp": - return torch.exp(pose_enc) - elif act_type == "relu": - return F.relu(pose_enc) - else: - raise ValueError(f"Unknown act_type: {act_type}") - - -def activate_head(out, activation="norm_exp", conf_activation="expp1"): - """ - Process network output to extract 3D points and confidence values. - - Args: - out: Network output tensor (B, C, H, W) - activation: Activation type for 3D points - conf_activation: Activation type for confidence values - - Returns: - Tuple of (3D points tensor, confidence tensor) - """ - # Move channels from last dim to the 4th dimension => (B, H, W, C) - fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected - - # Split into xyz (first C-1 channels) and confidence (last channel) - xyz = fmap[:, :, :, :-1] - conf = fmap[:, :, :, -1] - - if activation == "norm_exp": - d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8) - xyz_normed = xyz / d - pts3d = xyz_normed * torch.expm1(d) - elif activation == "norm": - pts3d = xyz / xyz.norm(dim=-1, keepdim=True) - elif activation == "exp": - pts3d = torch.exp(xyz) - elif activation == "relu": - pts3d = F.relu(xyz) - elif activation == "inv_log": - pts3d = inverse_log_transform(xyz) - elif activation == "xy_inv_log": - xy, z = xyz.split([2, 1], dim=-1) - z = inverse_log_transform(z) - pts3d = torch.cat([xy * z, z], dim=-1) - elif activation == "sigmoid": - pts3d = torch.sigmoid(xyz) - elif activation == "linear": - pts3d = xyz - else: - raise ValueError(f"Unknown activation: {activation}") - - if conf_activation == "expp1": - conf_out = 1 + conf.exp() - elif conf_activation == "expp0": - conf_out = conf.exp() - elif conf_activation == "sigmoid": - conf_out = torch.sigmoid(conf) - else: - raise ValueError(f"Unknown conf_activation: {conf_activation}") - - return pts3d, conf_out - - -def inverse_log_transform(y): - """ - Apply inverse log transform: sign(y) * (exp(|y|) - 1) - - Args: - y: Input tensor - - Returns: - Transformed tensor - """ - return torch.sign(y) * (torch.expm1(torch.abs(y))) - diff --git a/uniforge3d/models/vggt/heads/utils.py b/uniforge3d/models/vggt/heads/utils.py deleted file mode 100644 index 27f0e97a4d9cde59366e376f4ca741caa7334dd4..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/heads/utils.py +++ /dev/null @@ -1,110 +0,0 @@ -# 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. - -import torch -import torch.nn as nn - - -def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor: - """ - Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC) - - Args: - pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates - embed_dim: Output channel dimension for embeddings - - Returns: - Tensor of shape (H, W, embed_dim) with positional embeddings - """ - H, W, grid_dim = pos_grid.shape - assert grid_dim == 2 - pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2) - - # Process x and y coordinates separately - emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2] - emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2] - - # Combine and reshape - emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D] - - return emb.view(H, W, embed_dim) # [H, W, D] - - -def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor: - """ - This function generates a 1D positional embedding from a given grid using sine and cosine functions. - - Args: - - embed_dim: The embedding dimension. - - pos: The position to generate the embedding from. - - Returns: - - emb: The generated 1D positional embedding. - """ - assert embed_dim % 2 == 0 - device = pos.device - omega = torch.arange(embed_dim // 2, dtype=torch.float32 if device.type == "mps" else torch.double, device=device) - omega /= embed_dim / 2.0 - omega = 1.0 / omega_0**omega # (D/2,) - - pos = pos.reshape(-1) # (M,) - out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product - - emb_sin = torch.sin(out) # (M, D/2) - emb_cos = torch.cos(out) # (M, D/2) - - emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) - return emb.float() - - -# Inspired by https://github.com/microsoft/moge - - -def create_uv_grid( - width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None -) -> torch.Tensor: - """ - Create a normalized UV grid of shape (width, height, 2). - - The grid spans horizontally and vertically according to an aspect ratio, - ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right - corner is at (x_span, y_span), normalized by the diagonal of the plane. - - Args: - width (int): Number of points horizontally. - height (int): Number of points vertically. - aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height. - dtype (torch.dtype, optional): Data type of the resulting tensor. - device (torch.device, optional): Device on which the tensor is created. - - Returns: - torch.Tensor: A (width, height, 2) tensor of UV coordinates. - """ - # Derive aspect ratio if not explicitly provided - if aspect_ratio is None: - aspect_ratio = float(width) / float(height) - - # Compute normalized spans for X and Y - diag_factor = (aspect_ratio**2 + 1.0) ** 0.5 - span_x = aspect_ratio / diag_factor - span_y = 1.0 / diag_factor - - # Establish the linspace boundaries - left_x = -span_x * (width - 1) / width - right_x = span_x * (width - 1) / width - top_y = -span_y * (height - 1) / height - bottom_y = span_y * (height - 1) / height - - # Generate 1D coordinates - x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device) - y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device) - - # Create 2D meshgrid (width x height) and stack into UV - uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy") - uv_grid = torch.stack((uu, vv), dim=-1) - - return uv_grid - diff --git a/uniforge3d/models/vggt/layers/__init__.py b/uniforge3d/models/vggt/layers/__init__.py deleted file mode 100644 index 94651fdc3863440e244d7fdc6cd943be68e1d04b..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# 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. - -from .mlp import Mlp -from .patch_embed import PatchEmbed -from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused -from .block import NestedTensorBlock -from .attention import MemEffAttention - diff --git a/uniforge3d/models/vggt/layers/attention.py b/uniforge3d/models/vggt/layers/attention.py deleted file mode 100644 index a3a9a96ed36f4a627859f980ff692208582b7cd0..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/attention.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -# References: -# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py -# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py - -import logging -import os -import warnings - -from torch import Tensor -from torch import nn -import torch.nn.functional as F - -XFORMERS_AVAILABLE = False - - -class Attention(nn.Module): - def __init__( - self, - dim: int, - num_heads: int = 8, - qkv_bias: bool = True, - proj_bias: bool = True, - attn_drop: float = 0.0, - proj_drop: float = 0.0, - norm_layer: nn.Module = nn.LayerNorm, - qk_norm: bool = False, - fused_attn: bool = True, # use F.scaled_dot_product_attention or not - rope=None, - ) -> None: - super().__init__() - assert dim % num_heads == 0, "dim should be divisible by num_heads" - self.num_heads = num_heads - self.head_dim = dim // num_heads - self.scale = self.head_dim**-0.5 - self.fused_attn = fused_attn - - self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) - self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() - self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() - self.attn_drop = nn.Dropout(attn_drop) - self.proj = nn.Linear(dim, dim, bias=proj_bias) - self.proj_drop = nn.Dropout(proj_drop) - self.rope = rope - - def forward(self, x: Tensor, pos=None) -> Tensor: - B, N, C = x.shape - qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) - q, k, v = qkv.unbind(0) - q, k = self.q_norm(q), self.k_norm(k) - - if self.rope is not None: - q = self.rope(q, pos) - k = self.rope(k, pos) - - if self.fused_attn: - x = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0) - else: - q = q * self.scale - attn = q @ k.transpose(-2, -1) - attn = attn.softmax(dim=-1) - attn = self.attn_drop(attn) - x = attn @ v - - x = x.transpose(1, 2).reshape(B, N, C) - x = self.proj(x) - x = self.proj_drop(x) - return x - - -class MemEffAttention(Attention): - def forward(self, x: Tensor, attn_bias=None, pos=None) -> Tensor: - assert pos is None - if not XFORMERS_AVAILABLE: - if attn_bias is not None: - raise AssertionError("xFormers is required for using nested tensors") - return super().forward(x) - - B, N, C = x.shape - qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) - - q, k, v = unbind(qkv, 2) - - x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) - x = x.reshape([B, N, C]) - - x = self.proj(x) - x = self.proj_drop(x) - return x - diff --git a/uniforge3d/models/vggt/layers/block.py b/uniforge3d/models/vggt/layers/block.py deleted file mode 100644 index bb55a5288f1dd93d40d7187dfb39a6a30dfac5bc..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/block.py +++ /dev/null @@ -1,135 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -# References: -# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py -# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py - -from typing import Callable, List, Any, Tuple, Dict - -import torch -from torch import nn, Tensor - -from .attention import Attention -from .layer_scale import LayerScale -from .mlp import Mlp - - -XFORMERS_AVAILABLE = False - - -class Block(nn.Module): - def __init__( - self, - dim: int, - num_heads: int, - mlp_ratio: float = 4.0, - qkv_bias: bool = True, - proj_bias: bool = True, - ffn_bias: bool = True, - drop: float = 0.0, - attn_drop: float = 0.0, - init_values=None, - act_layer: Callable[..., nn.Module] = nn.GELU, - norm_layer: Callable[..., nn.Module] = nn.LayerNorm, - attn_class: Callable[..., nn.Module] = Attention, - ffn_layer: Callable[..., nn.Module] = Mlp, - qk_norm: bool = False, - fused_attn: bool = True, # use F.scaled_dot_product_attention or not - rope=None, - ) -> None: - super().__init__() - - self.norm1 = norm_layer(dim) - - self.attn = attn_class( - dim, - num_heads=num_heads, - qkv_bias=qkv_bias, - proj_bias=proj_bias, - attn_drop=attn_drop, - proj_drop=drop, - qk_norm=qk_norm, - fused_attn=fused_attn, - rope=rope, - ) - - self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() - - self.norm2 = norm_layer(dim) - mlp_hidden_dim = int(dim * mlp_ratio) - self.mlp = ffn_layer( - in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, bias=ffn_bias - ) - self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() - - - def forward(self, x: Tensor, pos=None) -> Tensor: - def attn_residual_func(x: Tensor, pos=None) -> Tensor: - return self.ls1(self.attn(self.norm1(x), pos=pos)) - - def ffn_residual_func(x: Tensor) -> Tensor: - return self.ls2(self.mlp(self.norm2(x))) - - x = x + attn_residual_func(x, pos=pos) - x = x + ffn_residual_func(x) - return x - - -attn_bias_cache: Dict[Tuple, Any] = {} - - -def get_attn_bias_and_cat(x_list, branges=None): - """ - this will perform the index select, cat the tensors, and provide the attn_bias from cache - """ - batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] - all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) - if all_shapes not in attn_bias_cache.keys(): - seqlens = [] - for b, x in zip(batch_sizes, x_list): - for _ in range(b): - seqlens.append(x.shape[1]) - attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) - attn_bias._batch_sizes = batch_sizes - attn_bias_cache[all_shapes] = attn_bias - - if branges is not None: - cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1]) - else: - tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) - cat_tensors = torch.cat(tensors_bs1, dim=1) - - return attn_bias_cache[all_shapes], cat_tensors - - -class NestedTensorBlock(Block): - def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: - """ - x_list contains a list of tensors to nest together and run - """ - assert isinstance(self.attn, MemEffAttention) - - def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: - return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) - - def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: - return self.ls2(self.mlp(self.norm2(x))) - - attn_bias, x = get_attn_bias_and_cat(x_list) - x = x + attn_residual_func(x, attn_bias=attn_bias) - x = x + ffn_residual_func(x) - return attn_bias.split(x) - - def forward(self, x_or_x_list): - if isinstance(x_or_x_list, Tensor): - return super().forward(x_or_x_list) - elif isinstance(x_or_x_list, list): - if not XFORMERS_AVAILABLE: - raise AssertionError("xFormers is required for using nested tensors") - return self.forward_nested(x_or_x_list) - else: - raise AssertionError - diff --git a/uniforge3d/models/vggt/layers/layer_scale.py b/uniforge3d/models/vggt/layers/layer_scale.py deleted file mode 100644 index 166f8ca7945dc95780d2f76cb2695607e599771d..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/layer_scale.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 - -from typing import Union - -import torch -from torch import Tensor -from torch import nn - - -class LayerScale(nn.Module): - def __init__(self, dim: int, init_values: Union[float, Tensor] = 1e-5, inplace: bool = False) -> None: - super().__init__() - self.inplace = inplace - self.gamma = nn.Parameter(init_values * torch.ones(dim)) - - def forward(self, x: Tensor) -> Tensor: - return x.mul_(self.gamma) if self.inplace else x * self.gamma - diff --git a/uniforge3d/models/vggt/layers/mlp.py b/uniforge3d/models/vggt/layers/mlp.py deleted file mode 100644 index f2395d25a21d02c2e714879097e7706a918b2686..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/mlp.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -# References: -# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py -# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py - - -from typing import Callable, Optional - -from torch import Tensor, nn - - -class Mlp(nn.Module): - def __init__( - self, - in_features: int, - hidden_features: Optional[int] = None, - out_features: Optional[int] = None, - act_layer: Callable[..., nn.Module] = nn.GELU, - drop: float = 0.0, - bias: bool = True, - ) -> None: - super().__init__() - out_features = out_features or in_features - hidden_features = hidden_features or in_features - self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) - self.act = act_layer() - self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) - self.drop = nn.Dropout(drop) - - def forward(self, x: Tensor) -> Tensor: - x = self.fc1(x) - x = self.act(x) - x = self.drop(x) - x = self.fc2(x) - x = self.drop(x) - return x - diff --git a/uniforge3d/models/vggt/layers/patch_embed.py b/uniforge3d/models/vggt/layers/patch_embed.py deleted file mode 100644 index 187ec0f07af3afdea521e6736dafa599aee20df2..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/patch_embed.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -# References: -# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py -# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py - -from typing import Callable, Optional, Tuple, Union - -from torch import Tensor -import torch.nn as nn - - -def make_2tuple(x): - if isinstance(x, tuple): - assert len(x) == 2 - return x - - assert isinstance(x, int) - return (x, x) - - -class PatchEmbed(nn.Module): - """ - 2D image to patch embedding: (B,C,H,W) -> (B,N,D) - - Args: - img_size: Image size. - patch_size: Patch token size. - in_chans: Number of input image channels. - embed_dim: Number of linear projection output channels. - norm_layer: Normalization layer. - """ - - def __init__( - self, - img_size: Union[int, Tuple[int, int]] = 224, - patch_size: Union[int, Tuple[int, int]] = 16, - in_chans: int = 3, - embed_dim: int = 768, - norm_layer: Optional[Callable] = None, - flatten_embedding: bool = True, - ) -> None: - super().__init__() - - image_HW = make_2tuple(img_size) - patch_HW = make_2tuple(patch_size) - patch_grid_size = (image_HW[0] // patch_HW[0], image_HW[1] // patch_HW[1]) - - self.img_size = image_HW - self.patch_size = patch_HW - self.patches_resolution = patch_grid_size - self.num_patches = patch_grid_size[0] * patch_grid_size[1] - - self.in_chans = in_chans - self.embed_dim = embed_dim - - self.flatten_embedding = flatten_embedding - - self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) - self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() - - def forward(self, x: Tensor) -> Tensor: - _, _, H, W = x.shape - patch_H, patch_W = self.patch_size - - assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}" - assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}" - - x = self.proj(x) # B C H W - H, W = x.size(2), x.size(3) - x = x.flatten(2).transpose(1, 2) # B HW C - x = self.norm(x) - if not self.flatten_embedding: - x = x.reshape(-1, H, W, self.embed_dim) # B H W C - return x - - def flops(self) -> float: - Ho, Wo = self.patches_resolution - flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) - if self.norm is not None: - flops += Ho * Wo * self.embed_dim - return flops - diff --git a/uniforge3d/models/vggt/layers/rope.py b/uniforge3d/models/vggt/layers/rope.py deleted file mode 100644 index 4e0de1aab9ae170e0455da449d9b8247fe5692e4..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/rope.py +++ /dev/null @@ -1,189 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - - -# Implementation of 2D Rotary Position Embeddings (RoPE). - -# This module provides a clean implementation of 2D Rotary Position Embeddings, -# which extends the original RoPE concept to handle 2D spatial positions. - -# Inspired by: -# https://github.com/meta-llama/codellama/blob/main/llama/model.py -# https://github.com/naver-ai/rope-vit - - -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F -from typing import Dict, Tuple - - -class PositionGetter: - """Generates and caches 2D spatial positions for patches in a grid. - - This class efficiently manages the generation of spatial coordinates for patches - in a 2D grid, caching results to avoid redundant computations. - - Attributes: - position_cache: Dictionary storing precomputed position tensors for different - grid dimensions. - """ - - def __init__(self): - """Initializes the position generator with an empty cache.""" - self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {} - - def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor: - """Generates spatial positions for a batch of patches. - - Args: - batch_size: Number of samples in the batch. - height: Height of the grid in patches. - width: Width of the grid in patches. - device: Target device for the position tensor. - - Returns: - Tensor of shape (batch_size, height*width, 2) containing y,x coordinates - for each position in the grid, repeated for each batch item. - """ - if (height, width) not in self.position_cache: - y_coords = torch.arange(height, device=device) - x_coords = torch.arange(width, device=device) - positions = torch.cartesian_prod(y_coords, x_coords) - self.position_cache[height, width] = positions - - cached_positions = self.position_cache[height, width] - return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone() - - -class RotaryPositionEmbedding2D(nn.Module): - """2D Rotary Position Embedding implementation. - - This module applies rotary position embeddings to input tokens based on their - 2D spatial positions. It handles the position-dependent rotation of features - separately for vertical and horizontal dimensions. - - Args: - frequency: Base frequency for the position embeddings. Default: 100.0 - scaling_factor: Scaling factor for frequency computation. Default: 1.0 - - Attributes: - base_frequency: Base frequency for computing position embeddings. - scaling_factor: Factor to scale the computed frequencies. - frequency_cache: Cache for storing precomputed frequency components. - """ - - def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0): - """Initializes the 2D RoPE module.""" - super().__init__() - self.base_frequency = frequency - self.scaling_factor = scaling_factor - self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {} - - def _compute_frequency_components( - self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Computes frequency components for rotary embeddings. - - Args: - dim: Feature dimension (must be even). - seq_len: Maximum sequence length. - device: Target device for computations. - dtype: Data type for the computed tensors. - - Returns: - Tuple of (cosine, sine) tensors for frequency components. - """ - cache_key = (dim, seq_len, device, dtype) - if cache_key not in self.frequency_cache: - # Compute frequency bands - exponents = torch.arange(0, dim, 2, device=device).float() / dim - inv_freq = 1.0 / (self.base_frequency**exponents) - - # Generate position-dependent frequencies - positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) - angles = torch.einsum("i,j->ij", positions, inv_freq) - - # Compute and cache frequency components - angles = angles.to(dtype) - angles = torch.cat((angles, angles), dim=-1) - cos_components = angles.cos().to(dtype) - sin_components = angles.sin().to(dtype) - self.frequency_cache[cache_key] = (cos_components, sin_components) - - return self.frequency_cache[cache_key] - - @staticmethod - def _rotate_features(x: torch.Tensor) -> torch.Tensor: - """Performs feature rotation by splitting and recombining feature dimensions. - - Args: - x: Input tensor to rotate. - - Returns: - Rotated feature tensor. - """ - feature_dim = x.shape[-1] - x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :] - return torch.cat((-x2, x1), dim=-1) - - def _apply_1d_rope( - self, tokens: torch.Tensor, positions: torch.Tensor, cos_comp: torch.Tensor, sin_comp: torch.Tensor - ) -> torch.Tensor: - """Applies 1D rotary position embeddings along one dimension. - - Args: - tokens: Input token features. - positions: Position indices. - cos_comp: Cosine components for rotation. - sin_comp: Sine components for rotation. - - Returns: - Tokens with applied rotary position embeddings. - """ - # Embed positions with frequency components - cos = F.embedding(positions, cos_comp)[:, None, :, :] - sin = F.embedding(positions, sin_comp)[:, None, :, :] - - # Apply rotation - return (tokens * cos) + (self._rotate_features(tokens) * sin) - - def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: - """Applies 2D rotary position embeddings to input tokens. - - Args: - tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim). - The feature dimension (dim) must be divisible by 4. - positions: Position tensor of shape (batch_size, n_tokens, 2) containing - the y and x coordinates for each token. - - Returns: - Tensor of same shape as input with applied 2D rotary position embeddings. - - Raises: - AssertionError: If input dimensions are invalid or positions are malformed. - """ - # Validate inputs - assert tokens.size(-1) % 2 == 0, "Feature dimension must be even" - assert positions.ndim == 3 and positions.shape[-1] == 2, "Positions must have shape (batch_size, n_tokens, 2)" - - # Compute feature dimension for each spatial direction - feature_dim = tokens.size(-1) // 2 - - # Get frequency components - max_position = int(positions.max()) + 1 - cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype) - - # Split features for vertical and horizontal processing - vertical_features, horizontal_features = tokens.chunk(2, dim=-1) - - # Apply RoPE separately for each dimension - vertical_features = self._apply_1d_rope(vertical_features, positions[..., 0], cos_comp, sin_comp) - horizontal_features = self._apply_1d_rope(horizontal_features, positions[..., 1], cos_comp, sin_comp) - - # Combine processed features - return torch.cat((vertical_features, horizontal_features), dim=-1) - diff --git a/uniforge3d/models/vggt/layers/swiglu_ffn.py b/uniforge3d/models/vggt/layers/swiglu_ffn.py deleted file mode 100644 index 60a05cebdd6f17433cd9399cbcbc0884a2022cc2..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/swiglu_ffn.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -import os -from typing import Callable, Optional -import warnings - -from torch import Tensor, nn -import torch.nn.functional as F - - -class SwiGLUFFN(nn.Module): - def __init__( - self, - in_features: int, - hidden_features: Optional[int] = None, - out_features: Optional[int] = None, - act_layer: Callable[..., nn.Module] = None, - drop: float = 0.0, - bias: bool = True, - ) -> None: - super().__init__() - out_features = out_features or in_features - hidden_features = hidden_features or in_features - self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) - self.w3 = nn.Linear(hidden_features, out_features, bias=bias) - - def forward(self, x: Tensor) -> Tensor: - x12 = self.w12(x) - x1, x2 = x12.chunk(2, dim=-1) - hidden = F.silu(x1) * x2 - return self.w3(hidden) - - -XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None -# try: -# if XFORMERS_ENABLED: -# from xformers.ops import SwiGLU - -# XFORMERS_AVAILABLE = True -# warnings.warn("xFormers is available (SwiGLU)") -# else: -# warnings.warn("xFormers is disabled (SwiGLU)") -# raise ImportError -# except ImportError: -SwiGLU = SwiGLUFFN -XFORMERS_AVAILABLE = False - -# warnings.warn("xFormers is not available (SwiGLU)") - - -class SwiGLUFFNFused(SwiGLU): - def __init__( - self, - in_features: int, - hidden_features: Optional[int] = None, - out_features: Optional[int] = None, - act_layer: Callable[..., nn.Module] = None, - drop: float = 0.0, - bias: bool = True, - ) -> None: - out_features = out_features or in_features - hidden_features = hidden_features or in_features - hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 - super().__init__(in_features=in_features, hidden_features=hidden_features, out_features=out_features, bias=bias) - diff --git a/uniforge3d/models/vggt/layers/vision_transformer.py b/uniforge3d/models/vggt/layers/vision_transformer.py deleted file mode 100644 index 4a2c7db5d03717a48fbb17e4416e03f6fdd6061a..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/layers/vision_transformer.py +++ /dev/null @@ -1,368 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the Apache License, Version 2.0 -# found in the LICENSE file in the root directory of this source tree. - -# References: -# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py -# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py - -from functools import partial -import math -from typing import Sequence, Tuple, Union, Callable - -import torch -import torch.nn as nn -from torch.nn.init import trunc_normal_ -from . import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block - -def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module: - if not depth_first and include_root: - fn(module=module, name=name) - for child_name, child_module in module.named_children(): - child_name = ".".join((name, child_name)) if name else child_name - named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True) - if depth_first and include_root: - fn(module=module, name=name) - return module - - -class BlockChunk(nn.ModuleList): - def forward(self, x): - for b in self: - x = b(x) - return x - - -class DinoVisionTransformer(nn.Module): - def __init__( - self, - img_size=224, - patch_size=16, - in_chans=3, - embed_dim=768, - depth=12, - num_heads=12, - mlp_ratio=4.0, - qkv_bias=True, - ffn_bias=True, - proj_bias=True, - init_values=None, # for layerscale: None or 0 => no layerscale - embed_layer=PatchEmbed, - act_layer=nn.GELU, - block_fn=Block, - ffn_layer="mlp", - block_chunks=1, - num_register_tokens=0, - interpolate_antialias=False, - interpolate_offset=0.1, - qk_norm=False, - ): - """ - Args: - img_size (int, tuple): input image size - patch_size (int, tuple): patch size - in_chans (int): number of input channels - embed_dim (int): embedding dimension - depth (int): depth of transformer - num_heads (int): number of attention heads - mlp_ratio (int): ratio of mlp hidden dim to embedding dim - qkv_bias (bool): enable bias for qkv if True - proj_bias (bool): enable bias for proj in attn if True - ffn_bias (bool): enable bias for ffn if True - weight_init (str): weight init scheme - init_values (float): layer-scale init values - embed_layer (nn.Module): patch embedding layer - act_layer (nn.Module): MLP activation layer - block_fn (nn.Module): transformer block class - ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" - block_chunks: (int) split block sequence into block_chunks units for FSDP wrap - num_register_tokens: (int) number of extra cls tokens (so-called "registers") - interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings - interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings - """ - super().__init__() - norm_layer = partial(nn.LayerNorm, eps=1e-6) - - self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models - self.num_tokens = 1 - self.n_blocks = depth - self.num_heads = num_heads - self.patch_size = patch_size - self.num_register_tokens = num_register_tokens - self.interpolate_antialias = interpolate_antialias - self.interpolate_offset = interpolate_offset - - self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) - num_patches = self.patch_embed.num_patches - - self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) - self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) - assert num_register_tokens >= 0 - self.register_tokens = ( - nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None - ) - - if ffn_layer == "mlp": - ffn_layer = Mlp - elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": - ffn_layer = SwiGLUFFNFused - elif ffn_layer == "identity": - - def f(*args, **kwargs): - return nn.Identity() - - ffn_layer = f - else: - raise NotImplementedError - - blocks_list = [ - block_fn( - dim=embed_dim, - num_heads=num_heads, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, - proj_bias=proj_bias, - ffn_bias=ffn_bias, - norm_layer=norm_layer, - act_layer=act_layer, - ffn_layer=ffn_layer, - init_values=init_values, - qk_norm=qk_norm, - ) - for i in range(depth) - ] - if block_chunks > 0: - self.chunked_blocks = True - chunked_blocks = [] - chunksize = depth // block_chunks - for i in range(0, depth, chunksize): - # this is to keep the block index consistent if we chunk the block list - chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize]) - self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) - else: - self.chunked_blocks = False - self.blocks = nn.ModuleList(blocks_list) - - self.norm = norm_layer(embed_dim) - self.head = nn.Identity() - - self.mask_token = nn.Parameter(torch.zeros(1, embed_dim)) - - self.init_weights() - - def init_weights(self): - trunc_normal_(self.pos_embed, std=0.02) - nn.init.normal_(self.cls_token, std=1e-6) - if self.register_tokens is not None: - nn.init.normal_(self.register_tokens, std=1e-6) - named_apply(init_weights_vit_timm, self) - - def interpolate_pos_encoding(self, x, w, h): - previous_dtype = x.dtype - npatch = x.shape[1] - 1 - N = self.pos_embed.shape[1] - 1 - if npatch == N and w == h: - return self.pos_embed - pos_embed = self.pos_embed.float() - class_pos_embed = pos_embed[:, 0] - patch_pos_embed = pos_embed[:, 1:] - dim = x.shape[-1] - w0 = w // self.patch_size - h0 = h // self.patch_size - M = int(math.sqrt(N)) # Recover the number of patches in each dimension - assert N == M * M - kwargs = {} - if self.interpolate_offset: - # Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8 - # Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors - sx = float(w0 + self.interpolate_offset) / M - sy = float(h0 + self.interpolate_offset) / M - kwargs["scale_factor"] = (sx, sy) - else: - # Simply specify an output size instead of a scale factor - kwargs["size"] = (w0, h0) - patch_pos_embed = nn.functional.interpolate( - patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2), - mode="bicubic", - antialias=self.interpolate_antialias, - **kwargs, - ) - assert (w0, h0) == patch_pos_embed.shape[-2:] - patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) - return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype) - - def prepare_tokens_with_masks(self, x, masks=None): - B, nc, w, h = x.shape - x = self.patch_embed(x) - if masks is not None: - x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x) - - x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) - x = x + self.interpolate_pos_encoding(x, w, h) - - if self.register_tokens is not None: - x = torch.cat((x[:, :1], self.register_tokens.expand(x.shape[0], -1, -1), x[:, 1:]), dim=1) - - return x - - def forward_features_list(self, x_list, masks_list): - x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)] - - for blk in self.blocks: - x = blk(x) - - all_x = x - output = [] - for x, masks in zip(all_x, masks_list): - x_norm = self.norm(x) - output.append( - { - "x_norm_clstoken": x_norm[:, 0], - "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], - "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], - "x_prenorm": x, - "masks": masks, - } - ) - return output - - def forward_features(self, x, masks=None): - if isinstance(x, list): - return self.forward_features_list(x, masks) - - x = self.prepare_tokens_with_masks(x, masks) - - for blk in self.blocks: - x = blk(x) - - x_norm = self.norm(x) - return { - "x_norm_clstoken": x_norm[:, 0], - "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], - "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], - "x_prenorm": x, - "masks": masks, - } - - def _get_intermediate_layers_not_chunked(self, x, n=1): - x = self.prepare_tokens_with_masks(x) - # If n is an int, take the n last blocks. If it's a list, take them - output, total_block_len = [], len(self.blocks) - blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n - for i, blk in enumerate(self.blocks): - x = blk(x) - if i in blocks_to_take: - output.append(x) - assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" - return output - - def _get_intermediate_layers_chunked(self, x, n=1): - x = self.prepare_tokens_with_masks(x) - output, i, total_block_len = [], 0, len(self.blocks[-1]) - # If n is an int, take the n last blocks. If it's a list, take them - blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n - for block_chunk in self.blocks: - for blk in block_chunk[i:]: # Passing the nn.Identity() - x = blk(x) - if i in blocks_to_take: - output.append(x) - i += 1 - assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" - return output - - def get_intermediate_layers( - self, - x: torch.Tensor, - n: Union[int, Sequence] = 1, # Layers or n last layers to take - reshape: bool = False, - return_class_token: bool = False, - norm=True, - ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: - if self.chunked_blocks: - outputs = self._get_intermediate_layers_chunked(x, n) - else: - outputs = self._get_intermediate_layers_not_chunked(x, n) - if norm: - outputs = [self.norm(out) for out in outputs] - class_tokens = [out[:, 0] for out in outputs] - outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs] - if reshape: - B, _, w, h = x.shape - outputs = [ - out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous() - for out in outputs - ] - if return_class_token: - return tuple(zip(outputs, class_tokens)) - return tuple(outputs) - - def forward(self, *args, **kwargs): - return self.forward_features(*args, **kwargs) - - -def init_weights_vit_timm(module: nn.Module, name: str = ""): - """ViT weight initialization, original timm impl (for reproducibility)""" - if isinstance(module, nn.Linear): - trunc_normal_(module.weight, std=0.02) - if module.bias is not None: - nn.init.zeros_(module.bias) - - -def vit_small(patch_size=16, num_register_tokens=0, **kwargs): - model = DinoVisionTransformer( - patch_size=patch_size, - embed_dim=384, - depth=12, - num_heads=6, - mlp_ratio=4, - block_fn=partial(Block, attn_class=MemEffAttention), - num_register_tokens=num_register_tokens, - **kwargs, - ) - return model - - -def vit_base(patch_size=16, num_register_tokens=0, **kwargs): - model = DinoVisionTransformer( - patch_size=patch_size, - embed_dim=768, - depth=12, - num_heads=12, - mlp_ratio=4, - block_fn=partial(Block, attn_class=MemEffAttention), - num_register_tokens=num_register_tokens, - **kwargs, - ) - return model - - -def vit_large(patch_size=16, num_register_tokens=0, **kwargs): - model = DinoVisionTransformer( - patch_size=patch_size, - embed_dim=1024, - depth=24, - num_heads=16, - mlp_ratio=4, - block_fn=partial(Block, attn_class=MemEffAttention), - num_register_tokens=num_register_tokens, - **kwargs, - ) - return model - - -def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs): - """ - Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 - """ - model = DinoVisionTransformer( - patch_size=patch_size, - embed_dim=1536, - depth=40, - num_heads=24, - mlp_ratio=4, - block_fn=partial(Block, attn_class=MemEffAttention), - num_register_tokens=num_register_tokens, - **kwargs, - ) - return model diff --git a/uniforge3d/models/vggt/models/aggregator.py b/uniforge3d/models/vggt/models/aggregator.py deleted file mode 100644 index 11c8ab1cc2dec33ddf523ddd9de48d94feb4c8d7..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/models/aggregator.py +++ /dev/null @@ -1,330 +0,0 @@ -# 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. - -import logging -import torch -import torch.nn as nn -import torch.nn.functional as F -from typing import Optional, Tuple, Union, List, Dict, Any - -from uniforge3d.models.vggt.layers import PatchEmbed -from uniforge3d.models.vggt.layers.block import Block -from uniforge3d.models.vggt.layers.rope import RotaryPositionEmbedding2D, PositionGetter -from uniforge3d.models.vggt.layers.vision_transformer import vit_small, vit_base, vit_large, vit_giant2 - -logger = logging.getLogger(__name__) - -_RESNET_MEAN = [0.485, 0.456, 0.406] -_RESNET_STD = [0.229, 0.224, 0.225] - - -class Aggregator(nn.Module): - """ - The Aggregator applies alternating-attention over input frames, - as described in VGGT: Visual Geometry Grounded Transformer. - - - Args: - img_size (int): Image size in pixels. - patch_size (int): Size of each patch for PatchEmbed. - embed_dim (int): Dimension of the token embeddings. - depth (int): Number of blocks. - num_heads (int): Number of attention heads. - mlp_ratio (float): Ratio of MLP hidden dim to embedding dim. - num_register_tokens (int): Number of register tokens. - block_fn (nn.Module): The block type used for attention (Block by default). - qkv_bias (bool): Whether to include bias in QKV projections. - proj_bias (bool): Whether to include bias in the output projection. - ffn_bias (bool): Whether to include bias in MLP layers. - patch_embed (str): Type of patch embed. e.g., "conv" or "dinov2_vitl14_reg". - aa_order (list[str]): The order of alternating attention, e.g. ["frame", "global"]. - aa_block_size (int): How many blocks to group under each attention type before switching. If not necessary, set to 1. - qk_norm (bool): Whether to apply QK normalization. - rope_freq (int): Base frequency for rotary embedding. -1 to disable. - init_values (float): Init scale for layer scale. - """ - - def __init__( - self, - img_size=518, - patch_size=14, - embed_dim=1024, - depth=24, - num_heads=16, - mlp_ratio=4.0, - num_register_tokens=4, - block_fn=Block, - qkv_bias=True, - proj_bias=True, - ffn_bias=True, - patch_embed="dinov2_vitl14_reg", - aa_order=["frame", "global"], - aa_block_size=1, - qk_norm=True, - rope_freq=100, - init_values=0.01, - cached_layer_indices: Tuple[int, ...] = (4, 11, 17, 23), - ): - super().__init__() - - self.__build_patch_embed__(patch_embed, img_size, patch_size, num_register_tokens, embed_dim=embed_dim) - - # Initialize rotary position embedding if frequency > 0 - self.rope = RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None - self.position_getter = PositionGetter() if self.rope is not None else None - - self.frame_blocks = nn.ModuleList( - [ - block_fn( - dim=embed_dim, - num_heads=num_heads, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, - proj_bias=proj_bias, - ffn_bias=ffn_bias, - init_values=init_values, - qk_norm=qk_norm, - rope=self.rope, - ) - for _ in range(depth) - ] - ) - - self.global_blocks = nn.ModuleList( - [ - block_fn( - dim=embed_dim, - num_heads=num_heads, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, - proj_bias=proj_bias, - ffn_bias=ffn_bias, - init_values=init_values, - qk_norm=qk_norm, - rope=self.rope, - ) - for _ in range(depth) - ] - ) - - self.depth = depth - self.aa_order = aa_order - self.patch_size = patch_size - self.aa_block_size = aa_block_size - self.cached_layer_indices = set(cached_layer_indices) - self.cached_layer_indices.add(depth - 1) - - # Validate that depth is divisible by aa_block_size - if self.depth % self.aa_block_size != 0: - raise ValueError(f"depth ({depth}) must be divisible by aa_block_size ({aa_block_size})") - - self.aa_block_num = self.depth // self.aa_block_size - - # Note: We have two camera tokens, one for the first frame and one for the rest - # The same applies for register tokens - self.camera_token = nn.Parameter(torch.randn(1, 2, 1, embed_dim)) - self.register_token = nn.Parameter(torch.randn(1, 2, num_register_tokens, embed_dim)) - - # The patch tokens start after the camera and register tokens - self.patch_start_idx = 1 + num_register_tokens - - # Initialize parameters with small values - nn.init.normal_(self.camera_token, std=1e-6) - nn.init.normal_(self.register_token, std=1e-6) - - # Register normalization constants as buffers - for name, value in (("_resnet_mean", _RESNET_MEAN), ("_resnet_std", _RESNET_STD)): - self.register_buffer(name, torch.FloatTensor(value).view(1, 1, 3, 1, 1), persistent=False) - - - def __build_patch_embed__( - self, - patch_embed, - img_size, - patch_size, - num_register_tokens, - interpolate_antialias=True, - interpolate_offset=0.0, - block_chunks=0, - init_values=1.0, - embed_dim=1024, - ): - """ - Build the patch embed layer. If 'conv', we use a - simple PatchEmbed conv layer. Otherwise, we use a vision transformer. - """ - - if "conv" in patch_embed: - self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=3, embed_dim=embed_dim) - else: - vit_models = { - "dinov2_vitl14_reg": vit_large, - "dinov2_vitb14_reg": vit_base, - "dinov2_vits14_reg": vit_small, - "dinov2_vitg2_reg": vit_giant2, - } - - self.patch_embed = vit_models[patch_embed]( - img_size=img_size, - patch_size=patch_size, - num_register_tokens=num_register_tokens, - interpolate_antialias=interpolate_antialias, - interpolate_offset=interpolate_offset, - block_chunks=block_chunks, - init_values=init_values, - ) - - # Disable gradient updates for mask token - if hasattr(self.patch_embed, "mask_token"): - self.patch_embed.mask_token.requires_grad_(False) - - def forward(self, images: torch.Tensor) -> Tuple[List[Optional[torch.Tensor]], int]: - """ - Args: - images (torch.Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. - B: batch size, S: sequence length, 3: RGB channels, H: height, W: width - - Returns: - (list[torch.Tensor | None], int): - The list of cached outputs from the attention blocks. Entries for - uncached layers are None so layer indices remain stable. - and the patch_start_idx indicating where patch tokens begin. - """ - B, S, C_in, H, W = images.shape - - if C_in != 3: - raise ValueError(f"Expected 3 input channels, got {C_in}") - - # Normalize images and reshape for patch embed - images = (images - self._resnet_mean) / self._resnet_std - - # Reshape to [B*S, C, H, W] for patch embedding - images = images.view(B * S, C_in, H, W) - patch_tokens = self.patch_embed(images) - - if isinstance(patch_tokens, dict): - patch_tokens = patch_tokens["x_norm_patchtokens"] - - _, P, C = patch_tokens.shape - - # Expand camera and register tokens to match batch size and sequence length - camera_token = slice_expand_and_flatten(self.camera_token, B, S) - register_token = slice_expand_and_flatten(self.register_token, B, S) - - # Concatenate special tokens with patch tokens - tokens = torch.cat([camera_token, register_token, patch_tokens], dim=1) - - pos = None - if self.rope is not None: - pos = self.position_getter(B * S, H // self.patch_size, W // self.patch_size, device=images.device) - - if self.patch_start_idx > 0: - # do not use position embedding for special tokens (camera and register tokens) - # so set pos to 0 for the special tokens - pos = pos + 1 - pos_special = torch.zeros(B * S, self.patch_start_idx, 2).to(images.device).to(pos.dtype) - pos = torch.cat([pos_special, pos], dim=1) - - # update P because we added special tokens - _, P, C = tokens.shape - - frame_idx = 0 - global_idx = 0 - output_list = [] - - for _ in range(self.aa_block_num): - for attn_type in self.aa_order: - if attn_type == "frame": - tokens, frame_idx, frame_intermediates = self._process_frame_attention( - tokens, B, S, P, C, frame_idx, pos=pos - ) - elif attn_type == "global": - tokens, global_idx, global_intermediates = self._process_global_attention( - tokens, B, S, P, C, global_idx, pos=pos - ) - else: - raise ValueError(f"Unknown attention type: {attn_type}") - - for i in range(len(frame_intermediates)): - layer_idx = len(output_list) - if layer_idx in self.cached_layer_indices: - # concat frame and global intermediates, [B x S x P x 2C] - concat_inter = torch.cat([frame_intermediates[i], global_intermediates[i]], dim=-1) - output_list.append(concat_inter) - else: - output_list.append(None) - - del frame_intermediates - del global_intermediates - return output_list, self.patch_start_idx - - def _process_frame_attention(self, tokens, B, S, P, C, frame_idx, pos=None): - """ - Process frame attention blocks. We keep tokens in shape (B*S, P, C). - """ - # If needed, reshape tokens or positions: - if tokens.shape != (B * S, P, C): - tokens = tokens.view(B, S, P, C).view(B * S, P, C) - - if pos is not None and pos.shape != (B * S, P, 2): - pos = pos.view(B, S, P, 2).view(B * S, P, 2) - - intermediates = [] - - # by default, self.aa_block_size=1, which processes one block at a time - for _ in range(self.aa_block_size): - tokens = self.frame_blocks[frame_idx](tokens, pos=pos) - frame_idx += 1 - intermediates.append(tokens.view(B, S, P, C)) - - return tokens, frame_idx, intermediates - - def _process_global_attention(self, tokens, B, S, P, C, global_idx, pos=None): - """ - Process global attention blocks. We keep tokens in shape (B, S*P, C). - """ - if tokens.shape != (B, S * P, C): - tokens = tokens.view(B, S, P, C).view(B, S * P, C) - - if pos is not None and pos.shape != (B, S * P, 2): - pos = pos.view(B, S, P, 2).view(B, S * P, 2) - - intermediates = [] - - # by default, self.aa_block_size=1, which processes one block at a time - for _ in range(self.aa_block_size): - tokens = self.global_blocks[global_idx](tokens, pos=pos) - global_idx += 1 - intermediates.append(tokens.view(B, S, P, C)) - - return tokens, global_idx, intermediates - - -def slice_expand_and_flatten(token_tensor, B, S): - """ - Processes specialized tokens with shape (1, 2, X, C) for multi-frame processing: - 1) Uses the first position (index=0) for the first frame only - 2) Uses the second position (index=1) for all remaining frames (S-1 frames) - 3) Expands both to match batch size B - 4) Concatenates to form (B, S, X, C) where each sequence has 1 first-position token - followed by (S-1) second-position tokens - 5) Flattens to (B*S, X, C) for processing - - Returns: - torch.Tensor: Processed tokens with shape (B*S, X, C) - """ - - # Slice out the "query" tokens => shape (1, 1, ...) - query = token_tensor[:, 0:1, ...].expand(B, 1, *token_tensor.shape[2:]) - # Slice out the "other" tokens => shape (1, S-1, ...) - others = token_tensor[:, 1:, ...].expand(B, S - 1, *token_tensor.shape[2:]) - # Concatenate => shape (B, S, ...) - combined = torch.cat([query, others], dim=1) - - # Finally flatten => shape (B*S, ...) - combined = combined.view(B * S, *combined.shape[2:]) - return combined - diff --git a/uniforge3d/models/vggt/models/vggt.py b/uniforge3d/models/vggt/models/vggt.py deleted file mode 100644 index 22c273ea94e660a8d3070c47b5c60fe36270355c..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/models/vggt.py +++ /dev/null @@ -1,64 +0,0 @@ -# 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. - -import torch -import torch.nn as nn -from huggingface_hub import PyTorchModelHubMixin - -from uniforge3d.models.vggt.heads.camera_head import CameraHead -from uniforge3d.models.vggt.heads.dpt_head import DPTHead -from uniforge3d.models.vggt.models.aggregator import Aggregator - - -class VGGT(nn.Module, PyTorchModelHubMixin): - """Inference-only VGGT backbone with the camera and point heads we use.""" - - def __init__( - self, - img_size=518, - patch_size=14, - embed_dim=1024, - enable_camera=True, - enable_point=True, - ): - super().__init__() - self.aggregator = Aggregator( - img_size=img_size, - patch_size=patch_size, - embed_dim=embed_dim, - ) - self.camera_head = CameraHead(dim_in=2 * embed_dim) if enable_camera else None - self.point_head = ( - DPTHead( - dim_in=2 * embed_dim, - output_dim=4, - activation="inv_log", - conf_activation="expp1", - ) - if enable_point - else None - ) - - def forward(self, images: torch.Tensor) -> dict[str, torch.Tensor]: - if images.ndim == 4: - images = images.unsqueeze(0) - aggregated_tokens, patch_start = self.aggregator(images) - predictions: dict[str, torch.Tensor] = {} - with torch.autocast(device_type=images.device.type, enabled=False): - if self.camera_head is not None: - poses = self.camera_head(aggregated_tokens) - predictions["pose_enc"] = poses[-1] - predictions["pose_enc_list"] = poses - if self.point_head is not None: - points, confidence = self.point_head( - aggregated_tokens, - images=images, - patch_start_idx=patch_start, - ) - predictions["world_points"] = points - predictions["world_points_conf"] = confidence - predictions["images"] = images - return predictions diff --git a/uniforge3d/models/vggt/utils/pose_enc.py b/uniforge3d/models/vggt/utils/pose_enc.py deleted file mode 100644 index b75f0326afb4dce1b3b82d2e2c83799afa3b8f2f..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/utils/pose_enc.py +++ /dev/null @@ -1,125 +0,0 @@ -# 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. - -import torch -from .rotation import quat_to_mat, mat_to_quat - - -def extri_intri_to_pose_encoding( - extrinsics, intrinsics, image_size_hw=None, pose_encoding_type="absT_quaR_FoV" # e.g., (256, 512) -): - """Convert camera extrinsics and intrinsics to a compact pose encoding. - - This function transforms camera parameters into a unified pose encoding format, - which can be used for various downstream tasks like pose prediction or representation. - - Args: - extrinsics (torch.Tensor): Camera extrinsic parameters with shape BxSx3x4, - where B is batch size and S is sequence length. - In OpenCV coordinate system (x-right, y-down, z-forward), representing camera from world transformation. - The format is [R|t] where R is a 3x3 rotation matrix and t is a 3x1 translation vector. - intrinsics (torch.Tensor): Camera intrinsic parameters with shape BxSx3x3. - Defined in pixels, with format: - [[fx, 0, cx], - [0, fy, cy], - [0, 0, 1]] - where fx, fy are focal lengths and (cx, cy) is the principal point - image_size_hw (tuple): Tuple of (height, width) of the image in pixels. - Required for computing field of view values. For example: (256, 512). - pose_encoding_type (str): Type of pose encoding to use. Currently only - supports "absT_quaR_FoV" (absolute translation, quaternion rotation, field of view). - - Returns: - torch.Tensor: Encoded camera pose parameters with shape BxSx9. - For "absT_quaR_FoV" type, the 9 dimensions are: - - [:3] = absolute translation vector T (3D) - - [3:7] = rotation as quaternion quat (4D) - - [7:] = field of view (2D) - """ - - # extrinsics: BxSx3x4 - # intrinsics: BxSx3x3 - - if pose_encoding_type == "absT_quaR_FoV": - R = extrinsics[:, :, :3, :3] # BxSx3x3 - T = extrinsics[:, :, :3, 3] # BxSx3 - - quat = mat_to_quat(R) - # Note the order of h and w here - H, W = image_size_hw - fov_h = 2 * torch.atan((H / 2) / intrinsics[..., 1, 1]) - fov_w = 2 * torch.atan((W / 2) / intrinsics[..., 0, 0]) - pose_encoding = torch.cat([T, quat, fov_h[..., None], fov_w[..., None]], dim=-1).float() - else: - raise NotImplementedError - - return pose_encoding - - -def pose_encoding_to_extri_intri( - pose_encoding, image_size_hw=None, pose_encoding_type="absT_quaR_FoV", build_intrinsics=True # e.g., (256, 512) -): - """Convert a pose encoding back to camera extrinsics and intrinsics. - - This function performs the inverse operation of extri_intri_to_pose_encoding, - reconstructing the full camera parameters from the compact encoding. - - Args: - pose_encoding (torch.Tensor): Encoded camera pose parameters with shape BxSx9, - where B is batch size and S is sequence length. - For "absT_quaR_FoV" type, the 9 dimensions are: - - [:3] = absolute translation vector T (3D) - - [3:7] = rotation as quaternion quat (4D) - - [7:] = field of view (2D) - image_size_hw (tuple): Tuple of (height, width) of the image in pixels. - Required for reconstructing intrinsics from field of view values. - For example: (256, 512). - pose_encoding_type (str): Type of pose encoding used. Currently only - supports "absT_quaR_FoV" (absolute translation, quaternion rotation, field of view). - build_intrinsics (bool): Whether to reconstruct the intrinsics matrix. - If False, only extrinsics are returned and intrinsics will be None. - - Returns: - tuple: (extrinsics, intrinsics) - - extrinsics (torch.Tensor): Camera extrinsic parameters with shape BxSx3x4. - In OpenCV coordinate system (x-right, y-down, z-forward), representing camera from world - transformation. The format is [R|t] where R is a 3x3 rotation matrix and t is - a 3x1 translation vector. - - intrinsics (torch.Tensor or None): Camera intrinsic parameters with shape BxSx3x3, - or None if build_intrinsics is False. Defined in pixels, with format: - [[fx, 0, cx], - [0, fy, cy], - [0, 0, 1]] - where fx, fy are focal lengths and (cx, cy) is the principal point, - assumed to be at the center of the image (W/2, H/2). - """ - - intrinsics = None - - if pose_encoding_type == "absT_quaR_FoV": - T = pose_encoding[..., :3] - quat = pose_encoding[..., 3:7] - fov_h = pose_encoding[..., 7] - fov_w = pose_encoding[..., 8] - - R = quat_to_mat(quat) - extrinsics = torch.cat([R, T[..., None]], dim=-1) - - if build_intrinsics: - H, W = image_size_hw - fy = (H / 2.0) / torch.tan(fov_h / 2.0) - fx = (W / 2.0) / torch.tan(fov_w / 2.0) - intrinsics = torch.zeros(pose_encoding.shape[:2] + (3, 3), device=pose_encoding.device) - intrinsics[..., 0, 0] = fx - intrinsics[..., 1, 1] = fy - intrinsics[..., 0, 2] = W / 2 - intrinsics[..., 1, 2] = H / 2 - intrinsics[..., 2, 2] = 1.0 # Set the homogeneous coordinate to 1 - else: - raise NotImplementedError - - return extrinsics, intrinsics - diff --git a/uniforge3d/models/vggt/utils/rotation.py b/uniforge3d/models/vggt/utils/rotation.py deleted file mode 100644 index 7b009b537fac4f83c9b4626624d768e4164d3447..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt/utils/rotation.py +++ /dev/null @@ -1,133 +0,0 @@ -# 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. - -# Modified from PyTorch3D, https://github.com/facebookresearch/pytorch3d - -import torch -import numpy as np -import torch.nn.functional as F - - -def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor: - """ - Quaternion Order: XYZW or say ijkr, scalar-last - - Convert rotations given as quaternions to rotation matrices. - Args: - quaternions: quaternions with real part last, - as tensor of shape (..., 4). - - Returns: - Rotation matrices as tensor of shape (..., 3, 3). - """ - i, j, k, r = torch.unbind(quaternions, -1) - # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`. - two_s = 2.0 / (quaternions * quaternions).sum(-1) - - o = torch.stack( - ( - 1 - two_s * (j * j + k * k), - two_s * (i * j - k * r), - two_s * (i * k + j * r), - two_s * (i * j + k * r), - 1 - two_s * (i * i + k * k), - two_s * (j * k - i * r), - two_s * (i * k - j * r), - two_s * (j * k + i * r), - 1 - two_s * (i * i + j * j), - ), - -1, - ) - return o.reshape(quaternions.shape[:-1] + (3, 3)) - - -def mat_to_quat(matrix: torch.Tensor) -> torch.Tensor: - """ - Convert rotations given as rotation matrices to quaternions. - - Args: - matrix: Rotation matrices as tensor of shape (..., 3, 3). - - Returns: - quaternions with real part last, as tensor of shape (..., 4). - Quaternion Order: XYZW or say ijkr, scalar-last - """ - if matrix.size(-1) != 3 or matrix.size(-2) != 3: - raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") - - batch_dim = matrix.shape[:-2] - m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.reshape(batch_dim + (9,)), dim=-1) - - q_abs = _sqrt_positive_part( - torch.stack( - [1.0 + m00 + m11 + m22, 1.0 + m00 - m11 - m22, 1.0 - m00 + m11 - m22, 1.0 - m00 - m11 + m22], dim=-1 - ) - ) - - # we produce the desired quaternion multiplied by each of r, i, j, k - quat_by_rijk = torch.stack( - [ - # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and - # `int`. - torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), - # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and - # `int`. - torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), - # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and - # `int`. - torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), - # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and - # `int`. - torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), - ], - dim=-2, - ) - - # We floor here at 0.1 but the exact level is not important; if q_abs is small, - # the candidate won't be picked. - flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) - quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) - - # if not for numerical problems, quat_candidates[i] should be same (up to a sign), - # forall i; we pick the best-conditioned one (with the largest denominator) - out = quat_candidates[F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape(batch_dim + (4,)) - - # Convert from rijk to ijkr - out = out[..., [1, 2, 3, 0]] - - out = standardize_quaternion(out) - - return out - - -def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: - """ - Returns torch.sqrt(torch.max(0, x)) - but with a zero subgradient where x is 0. - """ - ret = torch.zeros_like(x) - positive_mask = x > 0 - if torch.is_grad_enabled(): - ret[positive_mask] = torch.sqrt(x[positive_mask]) - else: - ret = torch.where(positive_mask, torch.sqrt(x), ret) - return ret - - -def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: - """ - Convert a unit quaternion to a standard form: one in which the real - part is non negative. - - Args: - quaternions: Quaternions with real part last, - as tensor of shape (..., 4). - - Returns: - Standardized quaternions as tensor of shape (..., 4). - """ - return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) - diff --git a/uniforge3d/models/vggt_adapter.py b/uniforge3d/models/vggt_adapter.py deleted file mode 100644 index c21ed7b84c0e520168bd4119e0f1874e65ccf9a2..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt_adapter.py +++ /dev/null @@ -1,508 +0,0 @@ -"""Frozen VGGT feature extraction and four-layer DINO residual adapter.""" - -from __future__ import annotations - -import math -from collections import OrderedDict -from pathlib import Path -from typing import Dict, List, Mapping, Sequence, Tuple - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from uniforge3d.models.vggt.models.aggregator import Aggregator - -FUSION_LAYERS = (4, 7, 11, 14, 17, 20, 23) - -_DTYPES = { - "float32": torch.float32, - "fp32": torch.float32, - "float16": torch.float16, - "fp16": torch.float16, - "bfloat16": torch.bfloat16, - "bf16": torch.bfloat16, -} - - -def load_prefixed_state(module: nn.Module, state: Mapping, prefix: str, label: str) -> None: - """Strictly load one named submodule from a composite VGGT checkpoint.""" - module_state = OrderedDict( - (str(key)[len(prefix) :], value) for key, value in state.items() if str(key).startswith(prefix) - ) - expected, actual = set(module.state_dict()), set(module_state) - missing, unexpected = sorted(expected - actual), sorted(actual - expected) - if missing or unexpected: - raise RuntimeError( - f"{label} checkpoint mismatch: missing={missing[:20]} unexpected={unexpected[:20]}" - ) - module.load_state_dict(module_state, strict=True) - - -class TwoLayerMLP(nn.Module): - def __init__(self, in_dim: int, hidden_dim: int, out_dim: int) -> None: - super().__init__() - self.net = nn.Sequential( - nn.Linear(in_dim, hidden_dim), - nn.GELU(), - nn.Linear(hidden_dim, out_dim), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.net(x) - - -class ShapeCoordEncoder(nn.Module): - """Exact coords64 encoder used to train the source ShapeConditionedVGGT.""" - - def __init__(self, grid_resolution: int = 64) -> None: - super().__init__() - self.grid_resolution = int(grid_resolution) - self.coord_mlp = TwoLayerMLP(63, 512, 1024) - self.token_mlp = TwoLayerMLP(1024, 1024, 1024) - - def positional_encoding(self, coords: torch.Tensor) -> torch.Tensor: - xyz = (coords.float() + 0.5) / float(self.grid_resolution) - 0.5 - freqs = 2.0 ** torch.arange(10, device=xyz.device, dtype=xyz.dtype) - phase = 2.0 * math.pi * xyz[..., None] * freqs - return torch.cat((xyz, phase.sin().flatten(-2), phase.cos().flatten(-2)), dim=-1) - - def forward(self, coords: torch.Tensor) -> torch.Tensor: - if coords.ndim != 2 or coords.shape[-1] != 3: - raise ValueError(f"Expected packed coords64 [sumN,3], got {tuple(coords.shape)}") - return self.token_mlp(self.coord_mlp(self.positional_encoding(coords))) - - -class PackedCrossAttention(nn.Module): - """Exact ragged shape-token cross-attention used by the source checkpoint.""" - - def __init__(self, q_dim: int, kv_dim: int, attn_dim: int, heads: int) -> None: - super().__init__() - if attn_dim % heads: - raise ValueError("attn_dim must be divisible by heads") - self.heads = int(heads) - self.head_dim = int(attn_dim) // self.heads - self.q_norm = nn.LayerNorm(q_dim) - self.k_norm = nn.LayerNorm(kv_dim) - self.to_q = nn.Linear(q_dim, attn_dim) - self.to_k = nn.Linear(kv_dim, attn_dim) - self.to_v = nn.Linear(kv_dim, attn_dim) - self.out_proj = nn.Linear(attn_dim, q_dim) - - def _attention(self, query: torch.Tensor, key_value: torch.Tensor) -> torch.Tensor: - num_query, num_key = query.shape[0], key_value.shape[0] - query_heads = self.to_q(self.q_norm(query)).view(num_query, self.heads, self.head_dim).transpose(0, 1) - key_heads = self.to_k(self.k_norm(key_value)).view(num_key, self.heads, self.head_dim).transpose(0, 1) - value_heads = self.to_v(key_value).view(num_key, self.heads, self.head_dim).transpose(0, 1) - output = F.scaled_dot_product_attention( - query_heads[None], key_heads[None], value_heads[None], dropout_p=0.0 - ) - return output[0].transpose(0, 1).reshape(num_query, -1) - - def forward( - self, - query: torch.Tensor, - shape_tokens: torch.Tensor, - shape_offsets: torch.Tensor, - ) -> torch.Tensor: - if query.ndim != 3 or query.shape[0] + 1 != shape_offsets.numel(): - raise ValueError("Query batch and packed shape_offsets disagree") - chunks = [] - for batch_idx in range(query.shape[0]): - lo = int(shape_offsets[batch_idx]) - hi = int(shape_offsets[batch_idx + 1]) - if hi <= lo: - raise ValueError(f"Sample {batch_idx} has no coords64 condition tokens") - residual = self.out_proj(self._attention(query[batch_idx], shape_tokens[lo:hi])) - chunks.append(query[batch_idx] + residual) - return torch.stack(chunks, dim=0) - - -def _load_checkpoint_payload(path: str): - kwargs = { - "map_location": "cpu", - "weights_only": True, - } - try: - return torch.load(path, mmap=True, **kwargs) - except TypeError: - return torch.load(path, **kwargs) - - -def _unwrap_model_state(payload) -> Tuple[Mapping[str, torch.Tensor], Dict[str, object]]: - if not isinstance(payload, Mapping): - raise TypeError(f"Expected a mapping checkpoint, got {type(payload)}") - if "model" in payload: - state = payload["model"] - metadata = {key: value for key, value in payload.items() if key != "model"} - else: - state = payload - metadata = {} - if not isinstance(state, Mapping): - raise TypeError(f"Expected checkpoint model state to be a mapping, got {type(state)}") - return state, metadata - - -class FrozenVGGTFeatureExtractor: - """Frozen coords64-conditioned VGGT backbone outside optimizer/DDP/checkpoints.""" - - def __init__( - self, - checkpoint_path: str, - *, - feature_layers: Sequence[int] = (4, 11, 17, 23), - shape_grid_resolution: int = 64, - conditioning_layers: Sequence[int] = FUSION_LAYERS, - dtype: str = "bfloat16", - device: str | torch.device = "cuda", - ) -> None: - self.checkpoint_path = str(checkpoint_path) - if not Path(self.checkpoint_path).is_file(): - raise FileNotFoundError(f"VGGT checkpoint not found: {self.checkpoint_path}") - - self.feature_layers = tuple(int(layer) for layer in feature_layers) - if self.feature_layers != (4, 11, 17, 23): - raise ValueError( - f"Frozen VGGT point-head features must use layers (4, 11, 17, 23), got {self.feature_layers}" - ) - dtype_key = str(dtype).lower() - if dtype_key not in _DTYPES: - raise ValueError(f"Unsupported frozen VGGT dtype {dtype!r}; choose from {sorted(_DTYPES)}") - self.dtype = _DTYPES[dtype_key] - self.device = torch.device(device) - self.shape_grid_resolution = int(shape_grid_resolution) - if self.shape_grid_resolution != 64: - raise ValueError( - "The source ShapeConditionedVGGT checkpoint requires coords64, " - f"got grid resolution {self.shape_grid_resolution}" - ) - self.conditioning_layers = tuple(int(layer) for layer in conditioning_layers) - if self.conditioning_layers != FUSION_LAYERS: - raise ValueError( - f"Conditioning layers must match source training {FUSION_LAYERS}, " - f"got {self.conditioning_layers}" - ) - - aggregator = Aggregator(cached_layer_indices=self.feature_layers) - shape_encoder = ShapeCoordEncoder(grid_resolution=self.shape_grid_resolution) - backbone_shape_adapters = nn.ModuleDict( - { - str(layer_idx): PackedCrossAttention(1024, 1024, 1024, 16) - for layer_idx in self.conditioning_layers - } - ) - payload = _load_checkpoint_payload(self.checkpoint_path) - state, metadata = _unwrap_model_state(payload) - - load_prefixed_state(aggregator, state, "aggregator.", "VGGT aggregator") - load_prefixed_state(shape_encoder, state, "shape_encoder.", "ShapeCoordEncoder") - load_prefixed_state( - backbone_shape_adapters, - state, - "backbone_shape_adapters.", - "VGGT backbone shape adapters", - ) - checkpoint_grid_resolution = metadata.get("shape_grid_resolution") - if checkpoint_grid_resolution is not None and int(checkpoint_grid_resolution) != 64: - raise ValueError(f"Checkpoint shape_grid_resolution must be 64, got {checkpoint_grid_resolution}") - - del state, payload - for module in (aggregator, shape_encoder, backbone_shape_adapters): - module.requires_grad_(False) - module.eval() - module.to(device=self.device, dtype=self.dtype) - self.aggregator = aggregator - self.shape_encoder = shape_encoder - self.backbone_shape_adapters = backbone_shape_adapters - - def _conditioned_aggregate( - self, - images: torch.Tensor, - shape_tokens: torch.Tensor, - shape_offsets: torch.Tensor, - ): - aggregator = self.aggregator - batch, views, channels, height, width = images.shape - normalized = (images - aggregator._resnet_mean) / aggregator._resnet_std - flat_images = normalized.view(batch * views, channels, height, width) - patch = aggregator.patch_embed(flat_images) - if isinstance(patch, dict): - patch = patch["x_norm_patchtokens"] - - camera = aggregator.camera_token[:, :1].expand(batch, 1, 1, -1) - if views > 1: - camera = torch.cat( - (camera, aggregator.camera_token[:, 1:2].expand(batch, views - 1, 1, -1)), - dim=1, - ) - register = aggregator.register_token[:, :1].expand(batch, 1, -1, -1) - if views > 1: - register = torch.cat( - ( - register, - aggregator.register_token[:, 1:2].expand(batch, views - 1, -1, -1), - ), - dim=1, - ) - tokens = torch.cat( - ( - camera.reshape(batch * views, 1, -1), - register.reshape(batch * views, 4, -1), - patch, - ), - dim=1, - ) - token_count, token_dim = tokens.shape[1:] - position = aggregator.position_getter( - batch * views, - height // aggregator.patch_size, - width // aggregator.patch_size, - device=images.device, - ) - position = torch.cat( - ( - torch.zeros( - batch * views, - aggregator.patch_start_idx, - 2, - device=images.device, - dtype=position.dtype, - ), - position + 1, - ), - dim=1, - ) - - frame_idx = 0 - global_idx = 0 - outputs = [] - for layer_idx in range(aggregator.depth): - tokens, frame_idx, frame_intermediate = aggregator._process_frame_attention( - tokens, - batch, - views, - token_count, - token_dim, - frame_idx, - pos=position, - ) - tokens, global_idx, global_intermediate = aggregator._process_global_attention( - tokens, - batch, - views, - token_count, - token_dim, - global_idx, - pos=position, - ) - global_value = global_intermediate[-1] - if layer_idx in self.conditioning_layers: - conditioned = self.backbone_shape_adapters[str(layer_idx)]( - global_value.reshape(batch, views * token_count, token_dim), - shape_tokens, - shape_offsets, - ) - global_value = conditioned.view(batch, views, token_count, token_dim) - tokens = global_value.reshape(batch * views, token_count, token_dim) - if layer_idx in self.feature_layers: - outputs.append(torch.cat((frame_intermediate[-1], global_value), dim=-1)) - else: - outputs.append(None) - return outputs, aggregator.patch_start_idx - - def __call__( - self, - images: torch.Tensor, - shape_coords: torch.Tensor, - shape_offsets: torch.Tensor, - ): - if images.ndim != 5: - raise ValueError(f"Expected VGGT images [B,V,3,H,W], got {tuple(images.shape)}") - if images.shape[2] != 3: - raise ValueError(f"Expected RGB VGGT images, got {tuple(images.shape)}") - if tuple(images.shape[-2:]) != (448, 448): - raise ValueError(f"Expected 448x448 VGGT images, got {tuple(images.shape[-2:])}") - if shape_coords.ndim != 2 or shape_coords.shape[-1] != 3: - raise ValueError(f"Expected packed coords64 [sumN,3], got {tuple(shape_coords.shape)}") - if shape_offsets.ndim != 1 or shape_offsets.numel() != images.shape[0] + 1: - raise ValueError( - f"Expected shape_offsets [B+1]={images.shape[0] + 1}, got {tuple(shape_offsets.shape)}" - ) - if int(shape_offsets[0]) != 0 or int(shape_offsets[-1]) != shape_coords.shape[0]: - raise ValueError("shape_offsets must start at 0 and end at packed coords64 length") - if bool((shape_offsets[1:] <= shape_offsets[:-1]).any()): - raise ValueError("Every sample must contain at least one coords64 token") - if shape_coords.numel() == 0: - raise ValueError("Packed coords64 condition cannot be empty") - coord_min = int(shape_coords.min()) - coord_max = int(shape_coords.max()) - if coord_min < 0 or coord_max >= self.shape_grid_resolution: - raise ValueError(f"coords64 values must be in [0,63], got min={coord_min} max={coord_max}") - autocast_enabled = self.device.type == "cuda" and self.dtype != torch.float32 - with ( - torch.no_grad(), - torch.autocast( - device_type=self.device.type, - dtype=self.dtype, - enabled=autocast_enabled, - ), - ): - shape_tokens = self.shape_encoder(shape_coords.to(device=self.device, non_blocking=True)) - tokens, patch_start_idx = self._conditioned_aggregate( - images.to(device=self.device, dtype=self.dtype, non_blocking=True), - shape_tokens, - shape_offsets.to(device=self.device, dtype=torch.long, non_blocking=True), - ) - return tokens, int(patch_start_idx) - - -class VGGT4LayerDINOAdapter(nn.Module): - """Map four conditioned-VGGT layers to a DINO-width spatial residual. - - Shape512 keeps the native 32x32 patch layout. Shape1024 requests a 2x - nearest-neighbour expansion followed by a zero-initialized refinement. - """ - - def __init__( - self, - feature_layers: List[int] = (4, 11, 17, 23), - feature_dim: int = 2048, - per_layer_dim: int = 1024, - hidden_dim: int = 4096, - output_dim: int = 1024, - input_patch_grid_size: int = 32, - upsample_scale: int = 1, - ) -> None: - super().__init__() - self.feature_layers = tuple(int(layer) for layer in feature_layers) - if self.feature_layers != (4, 11, 17, 23): - raise ValueError( - f"Frozen VGGT point-head features must use layers (4, 11, 17, 23), got {self.feature_layers}" - ) - self.feature_dim = int(feature_dim) - self.per_layer_dim = int(per_layer_dim) - self.hidden_dim = int(hidden_dim) - self.output_dim = int(output_dim) - self.input_patch_grid_size = int(input_patch_grid_size) - self.upsample_scale = int(upsample_scale) - if self.input_patch_grid_size <= 0: - raise ValueError("input_patch_grid_size must be positive") - if self.upsample_scale not in (1, 2): - raise ValueError(f"upsample_scale must be 1 or 2, got {self.upsample_scale}") - expected_hidden = len(self.feature_layers) * self.per_layer_dim - if self.hidden_dim != expected_hidden: - raise ValueError( - f"hidden_dim must equal four-layer concat width {expected_hidden}, got {self.hidden_dim}" - ) - - # Four independent, newly initialized LayerNorm -> Linear projections. - # No point_head.* parameter is loaded from the VGGT checkpoint. - self.input_norms = nn.ModuleList([nn.LayerNorm(self.feature_dim) for _ in self.feature_layers]) - self.input_projections = nn.ModuleList( - [nn.Linear(self.feature_dim, self.per_layer_dim) for _ in self.feature_layers] - ) - - # First MLP: mix the four concatenated VGGT layers while preserving width. - self.hidden_norm = nn.LayerNorm(self.hidden_dim) - self.hidden_fc1 = nn.Linear(self.hidden_dim, self.hidden_dim) - self.hidden_fc2 = nn.Linear(self.hidden_dim, self.hidden_dim) - - # Second MLP: produce the DINO-width residual. Its last layer is zero-init. - self.output_norm = nn.LayerNorm(self.hidden_dim) - self.output_fc1 = nn.Linear(self.hidden_dim, self.hidden_dim) - self.output_fc2 = nn.Linear(self.hidden_dim, self.output_dim) - nn.init.zeros_(self.output_fc2.weight) - nn.init.zeros_(self.output_fc2.bias) - - self.up_refine = None - if self.upsample_scale == 2: - self.up_refine = nn.Sequential( - nn.Conv2d( - self.output_dim, - self.output_dim, - kernel_size=3, - padding=1, - groups=self.output_dim, - ), - nn.GELU(), - nn.Conv2d(self.output_dim, self.output_dim, kernel_size=1), - ) - nn.init.zeros_(self.up_refine[-1].weight) - nn.init.zeros_(self.up_refine[-1].bias) - - def forward(self, aggregated_tokens, patch_start_idx: int) -> torch.Tensor: - projected = [] - patch_count = None - for norm, projection, layer_idx in zip( - self.input_norms, - self.input_projections, - self.feature_layers, - ): - if layer_idx >= len(aggregated_tokens) or aggregated_tokens[layer_idx] is None: - raise RuntimeError(f"VGGT aggregator did not cache requested layer {layer_idx}") - layer_tokens = aggregated_tokens[layer_idx] - patch_tokens = layer_tokens[:, :, int(patch_start_idx) :] - if patch_tokens.shape[-1] != self.feature_dim: - raise RuntimeError( - f"Layer {layer_idx} feature width is {patch_tokens.shape[-1]}, " - f"expected {self.feature_dim}" - ) - if patch_count is None: - patch_count = int(patch_tokens.shape[2]) - elif int(patch_tokens.shape[2]) != patch_count: - raise RuntimeError( - f"Inconsistent VGGT patch counts: {patch_count} vs {patch_tokens.shape[2]}" - ) - projected.append(projection(norm(patch_tokens))) - - hidden_input = torch.cat(projected, dim=-1) - if hidden_input.shape[-1] != self.hidden_dim: - raise RuntimeError( - f"Concatenated VGGT width is {hidden_input.shape[-1]}, expected {self.hidden_dim}" - ) - - hidden_delta = self.hidden_fc2(F.gelu(self.hidden_fc1(self.hidden_norm(hidden_input)))) - hidden = hidden_input + hidden_delta - output_hidden = F.gelu(self.output_fc1(self.output_norm(hidden))) - delta = self.output_fc2(output_hidden) - - batch, views, patch_count, channels = delta.shape - expected_patch_count = self.input_patch_grid_size**2 - if patch_count != expected_patch_count: - raise RuntimeError( - "Expected native VGGT patch grid " - f"{self.input_patch_grid_size}x{self.input_patch_grid_size}=" - f"{expected_patch_count}, got {patch_count} patches" - ) - if channels != self.output_dim: - raise RuntimeError(f"Adapter output width is {channels}, expected {self.output_dim}") - if self.upsample_scale == 1: - return delta - - delta_map = ( - delta.reshape( - batch * views, - self.input_patch_grid_size, - self.input_patch_grid_size, - channels, - ) - .permute(0, 3, 1, 2) - .contiguous() - ) - repeated = F.interpolate( - delta_map, - scale_factor=self.upsample_scale, - mode="nearest", - ) - aligned = repeated + self.up_refine(repeated) - output_grid_size = self.input_patch_grid_size * self.upsample_scale - return ( - aligned.permute(0, 2, 3, 1) - .reshape( - batch, - views, - output_grid_size**2, - channels, - ) - .contiguous() - ) diff --git a/uniforge3d/models/vggt_routed_features.py b/uniforge3d/models/vggt_routed_features.py deleted file mode 100644 index 1d4f85085ac9cc9a6cf4ffa032e58b743c18e9a5..0000000000000000000000000000000000000000 --- a/uniforge3d/models/vggt_routed_features.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Frozen coords64 VGGT backbone and its full-precision point/DPT head.""" - -from __future__ import annotations - -import torch -import torch.nn as nn - -from .vggt.heads.dpt_head import DPTHead, custom_interpolate -from .vggt.heads.head_act import activate_head -from .vggt_adapter import ( - FrozenVGGTFeatureExtractor, - PackedCrossAttention, - _load_checkpoint_payload, - _unwrap_model_state, - load_prefixed_state, -) - - -class DPTShapeAdapter32(nn.Module): - def __init__(self) -> None: - super().__init__() - self.attn = PackedCrossAttention(256, 1024, 256, 8) - - def forward(self, feature, batch, views, shape_tokens, shape_offsets): - batch_views, channels, height, width = feature.shape - if batch_views != batch * views or channels != 256: - raise ValueError(f"Invalid DPT feature shape: {feature.shape}") - tokens = feature.view(batch, views, channels, height * width) - tokens = tokens.permute(0, 1, 3, 2).reshape(batch, views * height * width, channels) - tokens = self.attn(tokens, shape_tokens, shape_offsets) - return tokens.view(batch, views, height * width, channels).permute(0, 1, 3, 2).reshape_as(feature) - - -class FrozenRoutedVGGTFeatureExtractor(FrozenVGGTFeatureExtractor): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.point_head = DPTHead(dim_in=2048, output_dim=4, activation="inv_log", conf_activation="expp1") - self.dpt_shape_adapter_32 = DPTShapeAdapter32() - payload = _load_checkpoint_payload(self.checkpoint_path) - state, _ = _unwrap_model_state(payload) - load_prefixed_state(self.point_head, state, "point_head.", "point head") - load_prefixed_state( - self.dpt_shape_adapter_32, state, "dpt_shape_adapter_32.", "DPT shape adapter" - ) - for module in (self.point_head, self.dpt_shape_adapter_32): - module.requires_grad_(False) - module.eval() - module.to(device=self.device, dtype=torch.float32) - del state, payload - - def _point_forward(self, cached, images, patch_start, shape_tokens, shape_offsets): - head = self.point_head - batch, views, _, height, width = images.shape - patch_height, patch_width = height // head.patch_size, width // head.patch_size - features = [] - for dpt_index, layer_index in enumerate(head.intermediate_layer_idx): - value = cached[layer_index][:, :, patch_start:].reshape(batch * views, -1, 2048).float() - value = head.norm(value).permute(0, 2, 1).reshape(batch * views, 2048, patch_height, patch_width) - value = head.projects[dpt_index](value) - if head.pos_embed: - value = head._apply_pos_embed(value, width, height) - features.append(head.resize_layers[dpt_index](value)) - layer1, layer2, layer3, layer4 = features - layer1, layer2 = head.scratch.layer1_rn(layer1), head.scratch.layer2_rn(layer2) - layer3, layer4 = head.scratch.layer3_rn(layer3), head.scratch.layer4_rn(layer4) - output = head.scratch.refinenet4(layer4, size=layer3.shape[2:]) - output = self.dpt_shape_adapter_32(output, batch, views, shape_tokens.float(), shape_offsets) - output = head.scratch.refinenet3(output, layer3, size=layer2.shape[2:]) - output = head.scratch.refinenet2(output, layer2, size=layer1.shape[2:]) - output = head.scratch.refinenet1(output, layer1) - output = head.scratch.output_conv1(output) - output = custom_interpolate(output, (height, width), mode="bilinear", align_corners=True) - if head.pos_embed: - output = head._apply_pos_embed(output, width, height) - points, confidence = activate_head( - head.scratch.output_conv2(output), head.activation, head.conf_activation - ) - return points.view(batch, views, *points.shape[1:]), confidence.view( - batch, views, *confidence.shape[1:] - ) - - def __call__(self, images, shape_coords, shape_offsets, *, return_points: bool = True): - cached, patch_start = super().__call__(images, shape_coords, shape_offsets) - if not return_points: - return cached, patch_start, None, None - with torch.no_grad(), torch.autocast(device_type="cuda", dtype=self.dtype, enabled=True): - shape_tokens = self.shape_encoder(shape_coords.to(self.device)) - with torch.no_grad(), torch.autocast(device_type="cuda", enabled=False): - points, confidence = self._point_forward( - cached, - images.to(self.device), - patch_start, - shape_tokens.float(), - shape_offsets.to(self.device), - ) - return cached, patch_start, points.float(), confidence.float() diff --git a/uniforge3d/models/view_router.py b/uniforge3d/models/view_router.py deleted file mode 100644 index 96ea59a70ac31d0fb5ce4304fdd03fdca18c2104..0000000000000000000000000000000000000000 --- a/uniforge3d/models/view_router.py +++ /dev/null @@ -1,293 +0,0 @@ -"""Full-image view routing shared by the 32^3 shape and 64^3 shape/PBR stages.""" - -from __future__ import annotations - -import math - -import torch - - -class GPUVoxelViewRouter: - """Route each target voxel to one full image, without local-window computation. - - Shape512 uses a 32^3 query grid and a 32x32 patch grid. Shape1024 and - texture use 64^3 / 64x64. Both consume the same 448x448 point-map format; - the VGGT structure-conditioning grid is configured separately. - """ - - def __init__( - self, - confidence_keep_ratio: float = 0.95, - component_iterations: int = 64, - grid_resolution: int = 64, - patch_grid_size: int = 64, - image_size: int = 448, - ) -> None: - self.keep = float(confidence_keep_ratio) - self.iters = int(component_iterations) - self.grid = int(grid_resolution) - self.patch_grid = int(patch_grid_size) - self.image_size = int(image_size) - self.volume = self.grid**3 - self.patch_count = self.patch_grid**2 - if not 0.0 < self.keep <= 1.0: - raise ValueError("confidence_keep_ratio must be in (0,1]") - if self.iters <= 0: - raise ValueError("component_iterations must be positive") - if (self.grid, self.patch_grid) not in ((32, 32), (64, 64)) or self.image_size != 448: - raise ValueError("Router requires (grid, patch_grid)=(32,32) or (64,64), image_size=448") - if self.image_size % self.patch_grid: - raise ValueError("image_size must be divisible by patch_grid_size") - - @staticmethod - def _sum(src: torch.Tensor, idx: torch.Tensor, size: int) -> torch.Tensor: - return torch.zeros(size, dtype=src.dtype, device=src.device).scatter_add_(0, idx, src) - - def _top_confidence(self, confidence: torch.Tensor, valid: torch.Tensor) -> torch.Tensor: - keep = torch.zeros_like(valid) - batch, views, _ = valid.shape - for batch_idx in range(batch): - for view_idx in range(views): - ids = torch.nonzero(valid[batch_idx, view_idx]).flatten() - if ids.numel() == 0: - continue - count = math.ceil(ids.numel() * self.keep) - order = torch.argsort( - confidence[batch_idx, view_idx, ids], - descending=True, - stable=True, - ) - keep[batch_idx, view_idx, ids[order[:count]]] = True - return keep - - def _entries( - self, - points: torch.Tensor, - confidence: torch.Tensor, - input_masks: torch.Tensor, - ): - batch, views, height, width, _ = points.shape - if (height, width) != (self.image_size, self.image_size): - raise ValueError( - f"router expects {self.image_size}x{self.image_size} points, got {(height, width)}" - ) - flat_points = points.reshape(batch, views, -1, 3).float() - flat_conf = confidence.reshape(batch, views, -1).float() - valid = ( - input_masks.reshape(batch, views, -1).bool() - & torch.isfinite(flat_points).all(-1) - & torch.isfinite(flat_conf) - & ((flat_points >= -0.5) & (flat_points < 0.5)).all(-1) - ) - valid &= self._top_confidence(flat_conf, valid) - - pixels = torch.arange(height * width, device=points.device).view(1, 1, -1) - patch_pixels = self.image_size // self.patch_grid - patch = ((pixels // width) // patch_pixels) * self.patch_grid + ((pixels % width) // patch_pixels) - xyz = torch.floor((flat_points + 0.5) * self.grid).long() - voxel = xyz[..., 0] * self.grid * self.grid + xyz[..., 1] * self.grid + xyz[..., 2] - batch_ids = torch.arange(batch, device=points.device).view(batch, 1, 1) - batch_ids = batch_ids.expand_as(valid) - view_ids = torch.arange(views, device=points.device).view(1, views, 1) - view_ids = view_ids.expand_as(valid) - key = ( - ((batch_ids * views + view_ids) * self.volume + voxel) * self.patch_count + patch.expand_as(valid) - )[valid] - conf = flat_conf[valid] - if key.numel() == 0: - return None - - order = torch.argsort(key, stable=True) - key, conf = key[order], conf[order] - unique, inverse, counts = torch.unique_consecutive(key, return_inverse=True, return_counts=True) - return { - "key": unique, - "group": unique // self.patch_count, - "patch": unique % self.patch_count, - "count": counts.long(), - "conf": self._sum(conf, inverse, unique.numel()), - } - - def _summaries(self, entries): - if entries is None: - return None - key = entries["key"] - group = entries["group"] - patch = entries["patch"] - count = entries["count"] - conf_sum = entries["conf"] - num_entries = key.numel() - unique_groups, entry_group_ids = torch.unique_consecutive(group, return_inverse=True) - num_groups = unique_groups.numel() - - # 8-connected components on the configured patch grid. The early exit only - # checks convergence; it does not alter the deterministic update rule. - labels = torch.arange(num_entries, device=key.device) - patch_y, patch_x = patch // self.patch_grid, patch % self.patch_grid - for _ in range(self.iters): - old_labels = labels - choices = [labels] - for delta_y in (-1, 0, 1): - for delta_x in (-1, 0, 1): - if delta_x == 0 and delta_y == 0: - continue - neighbor_y = patch_y + delta_y - neighbor_x = patch_x + delta_x - inside = ( - (neighbor_y >= 0) - & (neighbor_y < self.patch_grid) - & (neighbor_x >= 0) - & (neighbor_x < self.patch_grid) - ) - neighbor_key = ( - group * self.patch_count - + neighbor_y.clamp(0, self.patch_grid - 1) * self.patch_grid - + neighbor_x.clamp(0, self.patch_grid - 1) - ) - position = torch.searchsorted(key, neighbor_key) - safe = position.clamp(max=num_entries - 1) - found = inside & (position < num_entries) & (key[safe] == neighbor_key) - choices.append(torch.where(found, labels[safe], labels)) - labels = torch.stack(choices).amin(0) - labels = labels[labels] - if torch.equal(labels, old_labels): - break - - component_pixels = self._sum(count, labels, num_entries) - component_conf = self._sum(conf_sum, labels, num_entries) - all_ids = torch.arange(num_entries, device=key.device) - roots = torch.nonzero(labels == all_ids).flatten() - root_group_ids = entry_group_ids[roots] - - root_support = component_pixels[roots] - max_support = torch.full((num_groups,), -1, dtype=root_support.dtype, device=key.device) - max_support.scatter_reduce_(0, root_group_ids, root_support, reduce="amax", include_self=True) - support_winner = root_support == max_support[root_group_ids] - - root_mean = component_conf[roots] / root_support.clamp_min(1) - max_mean = torch.full((num_groups,), float("-inf"), dtype=root_mean.dtype, device=key.device) - max_mean.scatter_reduce_( - 0, - root_group_ids, - torch.where(support_winner, root_mean, torch.full_like(root_mean, float("-inf"))), - reduce="amax", - include_self=True, - ) - root_winner = support_winner & (root_mean == max_mean[root_group_ids]) - root_sentinel = torch.full_like(roots, num_entries) - chosen_roots = torch.full((num_groups,), num_entries, dtype=roots.dtype, device=key.device) - chosen_roots.scatter_reduce_( - 0, - root_group_ids, - torch.where(root_winner, roots, root_sentinel), - reduce="amin", - include_self=True, - ) - - return { - "group": unique_groups, - "support": component_pixels[chosen_roots], - "mean": component_conf[chosen_roots] / component_pixels[chosen_roots].clamp_min(1), - } - - def __call__( - self, - points: torch.Tensor, - confidence: torch.Tensor, - input_masks: torch.Tensor, - target_coords: torch.Tensor, - ) -> dict[str, torch.Tensor]: - batch, views = points.shape[:2] - device = points.device - total = batch * self.volume - selected_view = torch.zeros(total, dtype=torch.long, device=device) - summary = self._summaries(self._entries(points, confidence, input_masks)) - if summary is None: - return {"selected_view": selected_view.view(batch, self.grid, self.grid, self.grid).detach()} - - # Direct support: most pixels, then anchor, confidence, and lowest view index. - group = summary["group"] - voxel = group % self.volume - batch_view = group // self.volume - view = batch_view % views - sample = batch_view // views - dense = sample * self.volume + voxel - source_support = summary["support"] - source_conf = summary["mean"] - source_anchor = (view == 0).long() - - support = torch.zeros(total, dtype=source_support.dtype, device=device) - support.scatter_reduce_(0, dense, source_support, reduce="amax", include_self=True) - support_winner = source_support == support[dense] - - anchor = torch.full((total,), -1, dtype=source_anchor.dtype, device=device) - anchor.scatter_reduce_( - 0, dense, - torch.where(support_winner, source_anchor, torch.full_like(source_anchor, -1)), - reduce="amax", include_self=True, - ) - anchor_winner = support_winner & (source_anchor == anchor[dense]) - - mean_conf = torch.full((total,), float("-inf"), dtype=source_conf.dtype, device=device) - mean_conf.scatter_reduce_( - 0, dense, - torch.where(anchor_winner, source_conf, torch.full_like(source_conf, float("-inf"))), - reduce="amax", include_self=True, - ) - conf_winner = anchor_winner & (source_conf == mean_conf[dense]) - selected_view.fill_(views) - selected_view.scatter_reduce_( - 0, dense, - torch.where(conf_winner, view, torch.full_like(view, views)), - reduce="amin", include_self=True, - ) - has_support = selected_view < views - - # Unsupported voxels default to the anchor; only missing targets need neighbors. - selected_view.masked_fill_(~has_support, 0) - target_batch = target_coords[:, 0] - xyz = target_coords[:, 1:4] - if bool(((xyz < 0) | (xyz >= self.grid)).any()): - raise ValueError(f"target_coords contain values outside the {self.grid}^3 grid") - target_voxel = xyz[:, 0] * self.grid * self.grid + xyz[:, 1] * self.grid + xyz[:, 2] - target_dense = target_batch * self.volume + target_voxel - missing = ~has_support[target_dense] - xyz, target_batch, target_dense = xyz[missing], target_batch[missing], target_dense[missing] - - # Single-hop inheritance from directly supported 26-neighbors, with the same priorities. - offset_axis = torch.arange(-1, 2, device=device, dtype=xyz.dtype) - offsets = torch.stack( - torch.meshgrid(offset_axis, offset_axis, offset_axis, indexing="ij"), -1, - ).reshape(-1, 3) - offsets = offsets[(offsets != 0).any(-1)] - neighbor_xyz = xyz[:, None, :] + offsets[None] - inside = ((neighbor_xyz >= 0) & (neighbor_xyz < self.grid)).all(-1) - safe_xyz = neighbor_xyz.clamp(0, self.grid - 1) - neighbor_voxel = ( - safe_xyz[..., 0] * self.grid * self.grid + safe_xyz[..., 1] * self.grid + safe_xyz[..., 2] - ) - source_dense = target_batch[:, None] * self.volume + neighbor_voxel - valid = inside & has_support[source_dense] - - candidate_support = support[source_dense] - max_support = torch.where( - valid, candidate_support, torch.full_like(candidate_support, -1), - ).amax(1) - support_winner = valid & (candidate_support == max_support[:, None]) - candidate_anchor = anchor[source_dense] - max_anchor = torch.where( - support_winner, candidate_anchor, torch.full_like(candidate_anchor, -1), - ).amax(1) - anchor_winner = support_winner & (candidate_anchor == max_anchor[:, None]) - candidate_conf = mean_conf[source_dense] - max_conf = torch.where( - anchor_winner, candidate_conf, torch.full_like(candidate_conf, float("-inf")), - ).amax(1) - conf_winner = anchor_winner & (candidate_conf == max_conf[:, None]) - candidate_view = selected_view[source_dense] - neighbor_view = torch.where( - conf_winner, candidate_view, torch.full_like(candidate_view, views), - ).amin(1) - chosen_neighbor = neighbor_view < views - selected_view[target_dense[chosen_neighbor]] = neighbor_view[chosen_neighbor] - return {"selected_view": selected_view.view(batch, self.grid, self.grid, self.grid).detach()} diff --git a/uniforge3d/modules/attention/__init__.py b/uniforge3d/modules/attention/__init__.py deleted file mode 100644 index 6a083a226a225020235da359511ce02142ed0ec6..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/attention/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .full_attn import * -from .modules import * -from .rope import * - diff --git a/uniforge3d/modules/attention/config.py b/uniforge3d/modules/attention/config.py deleted file mode 100644 index e231917b5d584645724fcf0121b4541cb0cf884e..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/attention/config.py +++ /dev/null @@ -1,30 +0,0 @@ -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' - - -__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/uniforge3d/modules/attention/full_attn.py b/uniforge3d/modules/attention/full_attn.py deleted file mode 100644 index 4e98f414cf4baaa1602ed754c768599204ffde68..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/attention/full_attn.py +++ /dev/null @@ -1,146 +0,0 @@ -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/uniforge3d/modules/attention/modules.py b/uniforge3d/modules/attention/modules.py deleted file mode 100644 index 2810624970e70b99de16ebfb0af3595df9013934..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/attention/modules.py +++ /dev/null @@ -1,103 +0,0 @@ -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/uniforge3d/modules/attention/rope.py b/uniforge3d/modules/attention/rope.py deleted file mode 100644 index 75d8e475af20b309a1a50d77484ad706551fa4d0..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/attention/rope.py +++ /dev/null @@ -1,48 +0,0 @@ -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 diff --git a/uniforge3d/modules/norm.py b/uniforge3d/modules/norm.py deleted file mode 100644 index e84d98c90f9be642b0c31373ea658106e7975f44..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/norm.py +++ /dev/null @@ -1,32 +0,0 @@ -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 - diff --git a/uniforge3d/modules/sparse/__init__.py b/uniforge3d/modules/sparse/__init__.py deleted file mode 100644 index 90ea8436af469b029f1ba0d4482e67a3942dbc7b..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/__init__.py +++ /dev/null @@ -1,66 +0,0 @@ -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', - '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', -} - -__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/uniforge3d/modules/sparse/attention/__init__.py b/uniforge3d/modules/sparse/attention/__init__.py deleted file mode 100644 index 1b1136b5946e7f5f35b234d6057d032c8099343d..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/attention/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .full_attn import * -from .windowed_attn import * -from .modules import * - diff --git a/uniforge3d/modules/sparse/attention/full_attn.py b/uniforge3d/modules/sparse/attention/full_attn.py deleted file mode 100644 index 4bf6d8203e4e595d4a90782567155dbd02b7ec7c..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/attention/full_attn.py +++ /dev/null @@ -1,221 +0,0 @@ -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/uniforge3d/modules/sparse/attention/modules.py b/uniforge3d/modules/sparse/attention/modules.py deleted file mode 100644 index 47a21962f49dff65b610ded34049131a7abf3abb..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/attention/modules.py +++ /dev/null @@ -1,142 +0,0 @@ -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/uniforge3d/modules/sparse/attention/rope.py b/uniforge3d/modules/sparse/attention/rope.py deleted file mode 100644 index 5f5efeebba9b2974dd5c063645345314a7892148..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/attention/rope.py +++ /dev/null @@ -1,58 +0,0 @@ -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 diff --git a/uniforge3d/modules/sparse/attention/routed_full_only_flash.py b/uniforge3d/modules/sparse/attention/routed_full_only_flash.py deleted file mode 100644 index 4aa9edc7ad28a70a211ed2df736ce5168f958ff9..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/attention/routed_full_only_flash.py +++ /dev/null @@ -1,196 +0,0 @@ -"""Packed Full-only routed cross-attention backed by FlashAttention varlen.""" -from __future__ import annotations - -from typing import Dict - -import torch -import torch.nn as nn - -from ..basic import SparseTensor -from .modules import SparseMultiHeadRMSNorm - -try: - from flash_attn import flash_attn_varlen_func -except Exception as exc: # pragma: no cover - validated at startup on production nodes - flash_attn_varlen_func = None - _FLASH_IMPORT_ERROR = exc -else: - _FLASH_IMPORT_ERROR = None - - -class PackedRoutedFullOnlyLayoutBuilder: - """Build one packed selected-view query layout shared by all routed layers.""" - - def __init__(self, grid_resolution: int = 64) -> None: - self.grid_resolution = int(grid_resolution) - - @staticmethod - def _gather_grid(grid: torch.Tensor, coords: torch.Tensor) -> torch.Tensor: - if grid.ndim != 4: - raise ValueError(f"Expected routed grid [B,R,R,R], got {tuple(grid.shape)}") - return grid[ - coords[:, 0].long(), - coords[:, 1].long(), - coords[:, 2].long(), - coords[:, 3].long(), - ] - - def prepare( - self, - *, - x: SparseTensor, - selected_view: torch.Tensor, - batch_size: int, - views: int, - ) -> Dict[str, torch.Tensor | int]: - """Return the packed-query fields consumed directly by routed attention.""" - coords = x.coords - if coords.ndim != 2 or coords.shape[1] != 4: - raise ValueError(f"Expected sparse coords [N,4], got {tuple(coords.shape)}") - xyz = coords[:, 1:].long() - if xyz.numel() and ( - int(xyz.min().item()) < 0 or int(xyz.max().item()) >= self.grid_resolution - ): - raise ValueError( - f"Sparse coords must be in [0,{self.grid_resolution - 1}]" - ) - batch_id = coords[:, 0].long() - if batch_id.numel() and ( - int(batch_id.min().item()) < 0 or int(batch_id.max().item()) >= batch_size - ): - raise ValueError("Sparse query batch id is out of range") - - selected = self._gather_grid(selected_view, coords).long() - if selected.numel() and ( - int(selected.min().item()) < 0 or int(selected.max().item()) >= views - ): - raise ValueError("selected_view contains a non-existent view") - - group_id = batch_id * int(views) + selected - group_count = int(batch_size) * int(views) - counts = torch.bincount(group_id, minlength=group_count) - active_groups = torch.nonzero(counts > 0, as_tuple=False).flatten() - if active_groups.numel() == 0: - raise ValueError("Routed attention received no sparse queries") - - try: - order = torch.argsort(group_id, stable=True) - except TypeError: - order = torch.argsort(group_id) - inverse = torch.empty_like(order) - inverse[order] = torch.arange(order.numel(), device=order.device) - - query_lengths = counts[active_groups].to(torch.int32) - cu_q = torch.zeros( - active_groups.numel() + 1, dtype=torch.int32, device=coords.device - ) - cu_q[1:] = torch.cumsum(query_lengths, dim=0) - full_tokens = self.grid_resolution ** 2 + 5 - cu_k = ( - torch.arange( - active_groups.numel() + 1, dtype=torch.int32, device=coords.device - ) - * full_tokens - ) - return { - "routed_query_order": order, - "routed_query_inverse": inverse, - "routed_active_groups": active_groups.long(), - "routed_cu_seqlens_q": cu_q, - "routed_cu_seqlens_k": cu_k, - "routed_max_seqlen_q": int(query_lengths.max().item()), - } - - -class RoutedFullOnlyFlashCrossAttention(nn.Module): - """Each query attends to all tokens of exactly one selected real view.""" - - full_tokens = 4101 - - def __init__( - self, - channels: int, - ctx_channels: int, - num_heads: int, - qkv_bias: bool = True, - qk_rms_norm: bool = False, - ) -> None: - super().__init__() - if channels % num_heads: - raise ValueError("channels must be divisible by num_heads") - self.channels = int(channels) - self.ctx_channels = int(ctx_channels) - self.num_heads = int(num_heads) - self.head_dim = self.channels // self.num_heads - self.qk_rms_norm = bool(qk_rms_norm) - if self.num_heads != 12 or self.head_dim != 128: - raise ValueError("production Full-only Flash path requires 12 heads x 128") - if flash_attn_varlen_func is None: - raise RuntimeError( - "flash_attn_varlen_func is required for routed Full-only attention" - ) from _FLASH_IMPORT_ERROR - - self.to_q = nn.Linear(channels, channels, bias=qkv_bias) - self.to_kv = nn.Linear(ctx_channels, channels * 2, bias=qkv_bias) - self.to_out = nn.Linear(channels, channels) - 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) - - def forward( - self, - x: SparseTensor, - context: Dict[str, torch.Tensor], - ) -> SparseTensor: - full = context["full_bank"] - if full.ndim != 4 or int(full.shape[2]) != self.full_tokens: - raise ValueError( - f"Expected Full bank [B,V,{self.full_tokens},C], got {tuple(full.shape)}" - ) - batch, views, _, width = full.shape - if int(width) != self.ctx_channels: - raise ValueError( - f"Expected Full width {self.ctx_channels}, got {int(width)}" - ) - - q = self.to_q(x.feats).view(-1, self.num_heads, self.head_dim) - if self.qk_rms_norm: - q = self.q_rms_norm(q) - order = context["routed_query_order"] - inverse = context["routed_query_inverse"] - q = q[order].contiguous() - - active_groups = context["routed_active_groups"] - flat_full = full.reshape( - int(batch) * int(views), self.full_tokens, width - ) - active_full = flat_full.index_select(0, active_groups).contiguous() - kv = self.to_kv(active_full).view( - active_groups.numel(), - self.full_tokens, - 2, - self.num_heads, - self.head_dim, - ) - k, v = kv.unbind(dim=2) - if self.qk_rms_norm: - k = self.k_rms_norm(k) - k = k.contiguous() - v = v.contiguous() - - k_packed = k.reshape(-1, self.num_heads, self.head_dim) - v_packed = v.reshape(-1, self.num_heads, self.head_dim) - out_grouped = flash_attn_varlen_func( - q, - k_packed, - v_packed, - context["routed_cu_seqlens_q"], - context["routed_cu_seqlens_k"], - int(context["routed_max_seqlen_q"]), - self.full_tokens, - dropout_p=0.0, - softmax_scale=None, - causal=False, - ) - out = out_grouped[inverse] - return x.replace(self.to_out(out.reshape(-1, self.channels))) diff --git a/uniforge3d/modules/sparse/attention/windowed_attn.py b/uniforge3d/modules/sparse/attention/windowed_attn.py deleted file mode 100644 index 1560f53d67105cfd7bc51a446f6dedf06446b8a8..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/attention/windowed_attn.py +++ /dev/null @@ -1,191 +0,0 @@ -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/uniforge3d/modules/sparse/basic.py b/uniforge3d/modules/sparse/basic.py deleted file mode 100644 index 7bd72c833c75e1ed673a0a865bd802306a07e1de..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/basic.py +++ /dev/null @@ -1,837 +0,0 @@ -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/uniforge3d/modules/sparse/config.py b/uniforge3d/modules/sparse/config.py deleted file mode 100644 index 1857a83c5d47f50520fe7e460117ef47b229d836..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/config.py +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Literal - -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 not in (None, 'flex_gemm'): - raise ValueError( - 'This RecGen inference package only includes SPARSE_CONV_BACKEND=flex_gemm; ' - f'got {env_sparse_conv_backend!r}' - ) - 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 - - -__from_env() - - -def set_conv_backend(backend: Literal['flex_gemm']): - global CONV - if backend != 'flex_gemm': - raise ValueError('RecGen only includes the flex_gemm sparse-convolution backend') - 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/uniforge3d/modules/sparse/conv/__init__.py b/uniforge3d/modules/sparse/conv/__init__.py deleted file mode 100644 index 505768b178bb782b8067539b8a3e36cdd847c98e..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/conv/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .conv import SparseConv3d, SparseInverseConv3d -from . import config - diff --git a/uniforge3d/modules/sparse/conv/config.py b/uniforge3d/modules/sparse/conv/config.py deleted file mode 100644 index 6d443111a1662ca68685c3c29c338db867203cbc..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/conv/config.py +++ /dev/null @@ -1,4 +0,0 @@ -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/uniforge3d/modules/sparse/conv/conv.py b/uniforge3d/modules/sparse/conv/conv.py deleted file mode 100644 index e68cfedc63f92cc101cec49e93e812a1c7900089..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/conv/conv.py +++ /dev/null @@ -1,31 +0,0 @@ -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/uniforge3d/modules/sparse/conv/conv_flex_gemm.py b/uniforge3d/modules/sparse/conv/conv_flex_gemm.py deleted file mode 100644 index d88d777cad1691a9bc5994bf12f1efa6a54281b0..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/conv/conv_flex_gemm.py +++ /dev/null @@ -1,69 +0,0 @@ -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/uniforge3d/modules/sparse/linear.py b/uniforge3d/modules/sparse/linear.py deleted file mode 100644 index f877fbb2df45b1a7064bb5916d3c061f1caacf34..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/linear.py +++ /dev/null @@ -1,16 +0,0 @@ -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/uniforge3d/modules/sparse/nonlinearity.py b/uniforge3d/modules/sparse/nonlinearity.py deleted file mode 100644 index 189f5dc11e137c4bb9974d8b67bafa9339643e13..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/nonlinearity.py +++ /dev/null @@ -1,36 +0,0 @@ -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/uniforge3d/modules/sparse/norm.py b/uniforge3d/modules/sparse/norm.py deleted file mode 100644 index ebd7e4ac8064ec037d6f629ba5b7fac6e496073f..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/norm.py +++ /dev/null @@ -1,65 +0,0 @@ -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/uniforge3d/modules/sparse/spatial/__init__.py b/uniforge3d/modules/sparse/spatial/__init__.py deleted file mode 100644 index 5d8bbcc1365e6648243c59bc7860424254a78c4e..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/spatial/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .basic import * -from .spatial2channel import * - diff --git a/uniforge3d/modules/sparse/spatial/basic.py b/uniforge3d/modules/sparse/spatial/basic.py deleted file mode 100644 index 49d4764fae6d419a1bdfa1c70021d40dd8cde2ba..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/spatial/basic.py +++ /dev/null @@ -1,103 +0,0 @@ -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)) - - 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 - diff --git a/uniforge3d/modules/sparse/spatial/spatial2channel.py b/uniforge3d/modules/sparse/spatial/spatial2channel.py deleted file mode 100644 index 1b37b24d0fb55f62c59d4300ea6d1bf3571df3f0..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/spatial/spatial2channel.py +++ /dev/null @@ -1,90 +0,0 @@ -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)) - - 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/uniforge3d/modules/sparse/transformer/__init__.py b/uniforge3d/modules/sparse/transformer/__init__.py deleted file mode 100644 index 92deb200ea54da8f150354f1e7baff1931c2df1b..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/transformer/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .blocks import * -from .modulated import * diff --git a/uniforge3d/modules/sparse/transformer/blocks.py b/uniforge3d/modules/sparse/transformer/blocks.py deleted file mode 100644 index 61cf14344469a8ccffd378bfb0c7b11cf50e383a..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/transformer/blocks.py +++ /dev/null @@ -1,136 +0,0 @@ -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_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.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: - 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_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.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: - return self._forward(x, context) - diff --git a/uniforge3d/modules/sparse/transformer/modulated.py b/uniforge3d/modules/sparse/transformer/modulated.py deleted file mode 100644 index a74bda97f661d4b95ab04900b4c4e37e3582b08f..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/sparse/transformer/modulated.py +++ /dev/null @@ -1,157 +0,0 @@ -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_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.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: - 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_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.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: - return self._forward(x, mod, context) - diff --git a/uniforge3d/modules/spatial.py b/uniforge3d/modules/spatial.py deleted file mode 100644 index 8e93cc1f3f85cff446a27fbac8bbf54b342b9552..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/spatial.py +++ /dev/null @@ -1,49 +0,0 @@ -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/uniforge3d/modules/transformer/__init__.py b/uniforge3d/modules/transformer/__init__.py deleted file mode 100644 index 92deb200ea54da8f150354f1e7baff1931c2df1b..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/transformer/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .blocks import * -from .modulated import * diff --git a/uniforge3d/modules/transformer/blocks.py b/uniforge3d/modules/transformer/blocks.py deleted file mode 100644 index 23b0c901a9955b902681e2a76d14bc5ff6593e72..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/transformer/blocks.py +++ /dev/null @@ -1,176 +0,0 @@ -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_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.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: - 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_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.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: - return self._forward(x, context, phases) - diff --git a/uniforge3d/modules/transformer/modulated.py b/uniforge3d/modules/transformer/modulated.py deleted file mode 100644 index 14685f8c60a635e14c1319485b089d83638ffd87..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/transformer/modulated.py +++ /dev/null @@ -1,165 +0,0 @@ -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_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.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: - 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_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.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) - if context.ndim == 4: - view_count = int(context.shape[1]) - if view_count <= 0: - raise ValueError("Expected at least one view for per-view cross-attention") - h_sum = None - for view_idx in range(view_count): - h_view = self.cross_attn(h, context[:, view_idx]) - h_sum = h_view if h_sum is None else h_sum + h_view - h = h_sum / float(view_count) - else: - 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: - return self._forward(x, mod, context, phases) - diff --git a/uniforge3d/modules/utils.py b/uniforge3d/modules/utils.py deleted file mode 100644 index 44ee5b60c62e3bf1befa83e13d5aeaebb227ca95..0000000000000000000000000000000000000000 --- a/uniforge3d/modules/utils.py +++ /dev/null @@ -1,88 +0,0 @@ -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/uniforge3d/pipelines/__init__.py b/uniforge3d/pipelines/__init__.py deleted file mode 100644 index bb2afe1bd7f85b7c4d182c5f964ddc6305c60ae6..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ - - -from .uniforge3d_image_to_3d import UniForge3DImageTo3DPipeline - -__all__ = ["UniForge3DImageTo3DPipeline"] diff --git a/uniforge3d/pipelines/samplers/__init__.py b/uniforge3d/pipelines/samplers/__init__.py deleted file mode 100644 index a4661899866cadb74052301cb4e5979fb69f7e1a..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/samplers/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .flow_euler import FlowEulerSampler, model_predictor - -__all__ = ["FlowEulerSampler", "model_predictor"] diff --git a/uniforge3d/pipelines/samplers/flow_euler.py b/uniforge3d/pipelines/samplers/flow_euler.py deleted file mode 100644 index 40b84020066e0c67374da0e095d8839bcf3c42d4..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/samplers/flow_euler.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Shared flow-matching Euler sampler for every cascade stage.""" - -from collections.abc import Callable -from typing import Any - -import numpy as np -import torch -from easydict import EasyDict as edict -from tqdm import tqdm - - -Prediction = Callable[[Any, float, bool], Any] - - -def model_predictor( - model: torch.nn.Module, - cond: Any, - neg_cond: Any, - *, - timestep_scale: float = 1000.0, - **model_kwargs, -) -> Prediction: - """Adapt a standard conditioned flow model to the shared sampler.""" - - def predict(sample, time: float, conditioned: bool): - timestep = torch.full( - (sample.shape[0],), - timestep_scale * time, - device=sample.device, - dtype=torch.float32, - ) - condition = cond if conditioned else neg_cond - return model(sample, timestep, condition, **model_kwargs) - - return predict - - -class FlowEulerSampler: - """Euler/CFG sampling shared by sparse structure, shape, and texture.""" - - def __init__(self, sigma_min: float): - self.sigma_min = sigma_min - - def _prediction_to_xstart(self, x_t, t: float, prediction): - return ( - (1 - self.sigma_min) * x_t - - (self.sigma_min + (1 - self.sigma_min) * t) * prediction - ) - - def _xstart_to_prediction(self, x_t, t: float, x_start): - return ( - (1 - self.sigma_min) * x_t - x_start - ) / (self.sigma_min + (1 - self.sigma_min) * t) - - def _guided_prediction( - self, - predict: Prediction, - sample, - t: float, - guidance_strength: float, - guidance_interval: tuple[float, float], - guidance_rescale: float, - guidance_as_difference: bool, - ): - strength = ( - guidance_strength - if guidance_interval[0] <= t <= guidance_interval[1] - else 1.0 - ) - if strength == 1: - return predict(sample, t, True) - if strength == 0: - return predict(sample, t, False) - - positive = predict(sample, t, True) - negative = predict(sample, t, False) - if guidance_as_difference: - guided = negative + strength * (positive - negative) - else: - guided = strength * positive + (1 - strength) * negative - if guidance_rescale <= 0: - return guided - - x0_positive = self._prediction_to_xstart(sample, t, positive) - x0_guided = self._prediction_to_xstart(sample, t, guided) - dimensions = list(range(1, x0_guided.ndim)) - positive_std = x0_positive.float().std(dim=dimensions, keepdim=True) - guided_std = x0_guided.float().std(dim=dimensions, keepdim=True).clamp_min(1e-6) - scale = (positive_std / guided_std).to(x0_guided.dtype) - x0_rescaled = x0_guided * scale - x0 = guidance_rescale * x0_rescaled + (1 - guidance_rescale) * x0_guided - return self._xstart_to_prediction(sample, t, x0) - - @torch.no_grad() - def sample( - self, - noise, - predict: Prediction, - *, - steps: int = 50, - rescale_t: float = 1.0, - guidance_strength: float = 3.0, - guidance_interval: tuple[float, float] = (0.0, 1.0), - guidance_rescale: float = 0.0, - guidance_as_difference: bool = False, - verbose: bool = True, - tqdm_desc: str = "Sampling", - ): - """Run the common Euler/CFG update using a stage-specific predictor.""" - sample = noise - times = np.linspace(1, 0, steps + 1) - times = rescale_t * times / (1 + (rescale_t - 1) * times) - time_pairs = list(zip(times[:-1].tolist(), times[1:].tolist())) - for current, previous in tqdm( - time_pairs, - desc=tqdm_desc, - disable=not verbose, - bar_format="{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt}", - ): - prediction = self._guided_prediction( - predict, - sample, - current, - guidance_strength, - guidance_interval, - guidance_rescale, - guidance_as_difference, - ) - sample = sample - (current - previous) * prediction - return edict(samples=sample) diff --git a/uniforge3d/pipelines/shape.py b/uniforge3d/pipelines/shape.py deleted file mode 100644 index c84dac43df662b60b105f793c5b56f9f0cf877b9..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/shape.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Sparse shape latent sampling and mesh decoding.""" - -from __future__ import annotations - -from typing import Any - -import torch - -from ..models.vaes.flexi_dual_grid import FlexiDualGridVaeDecoder -from ..modules import sparse as sp -from .samplers import FlowEulerSampler, model_predictor - - -@torch.no_grad() -def sample_shape_latent( - model: torch.nn.Module, - latent_coords: torch.Tensor, - condition: dict[str, Any], - sampling: dict[str, Any], - *, - description: str = "Shape sampling", -) -> sp.SparseTensor: - """Sample latent features at fixed coordinates using an encoded condition.""" - # Keep noise on the CPU RNG stream used by the original inference path. - features = torch.randn(len(latent_coords), int(model.in_channels), device="cpu") - features = features.to(latent_coords.device) - noise = sp.SparseTensor(feats=features, coords=latent_coords) - condition["cond"] = model.prepare_condition(noise, condition["cond"]) - condition["neg_cond"] = model.prepare_condition(noise, condition["neg_cond"]) - - sampler = FlowEulerSampler(**sampling["args"]) - predict = model_predictor(model, condition["cond"], condition["neg_cond"]) - - with torch.autocast(device_type=latent_coords.device.type, dtype=torch.bfloat16): - return sampler.sample( - noise, - predict, - **sampling["params"], - verbose=True, - tqdm_desc=description, - ).samples - - -@torch.no_grad() -def decode_shape_latent( - decoder: FlexiDualGridVaeDecoder, - normalized_latent, - normalization: dict[str, Any] | None, -): - """Denormalize and decode meshes; the pipeline places the decoder.""" - value = normalized_latent - if normalization is not None: - mean = torch.tensor(normalization["mean"], dtype=torch.float32, device="cpu") - std = torch.tensor(normalization["std"], dtype=torch.float32, device="cpu") - mean = mean.to(value.device).view(1, -1) - std = std.to(value.device).view(1, -1) - value = value.replace(value.feats * std + mean) - return decoder(value) diff --git a/uniforge3d/pipelines/sparse_structure.py b/uniforge3d/pipelines/sparse_structure.py deleted file mode 100644 index 0886d78eb53983296a2a5897a309cd77ff2aacb6..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/sparse_structure.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Stage1 model adaptation and occupancy decoding.""" - -from __future__ import annotations - -from typing import Any - -import torch -import torch.nn.functional as F - -from ..models.vaes.sparse_structure import SparseStructureDecoder -from .samplers import FlowEulerSampler - - -def decoded_coordinates(occupancy_logits: torch.Tensor): - """Threshold decoder logits and return occupied coords32 and coords64.""" - decoded64 = occupancy_logits > 0 - if decoded64.shape[-1] != 64: - if decoded64.shape[-1] < 64 or decoded64.shape[-1] % 64: - raise RuntimeError(f"Cannot reduce Stage1 decoder output {tuple(decoded64.shape)} to 64^3") - ratio = decoded64.shape[-1] // 64 - decoded64 = F.max_pool3d(decoded64.float(), kernel_size=ratio, stride=ratio) > 0.5 - coords64 = torch.argwhere(decoded64)[:, [0, 2, 3, 4]].int() - decoded32 = F.max_pool3d(decoded64.float(), kernel_size=2, stride=2) > 0.5 - coords32 = torch.argwhere(decoded32)[:, [0, 2, 3, 4]].int() - if len(coords32) == 0 or len(coords64) == 0: - raise RuntimeError("Stage1 decoded an empty sparse structure") - return coords32, coords64 - - -@torch.no_grad() -def sample_sparse_structure( - model: torch.nn.Module, - noise: torch.Tensor, - vggt_images: torch.Tensor, - dino_features: torch.Tensor, - *, - steps: int, - guidance_strength: float, - guidance_interval: tuple[float, float], - guidance_rescale: float, - rescale_t: float, - sigma_min: float, -) -> torch.Tensor: - """Sample Stage1 with explicit conditional and unconditional predictions.""" - def predict(sample: torch.Tensor, time: float, conditioned: bool) -> torch.Tensor: - timestep = torch.full( - (sample.shape[0],), - time, - device=sample.device, - dtype=torch.float32, - ) - if conditioned: - return model(sample, timestep, vggt_images, dino_features) - return model.forward_unconditional(sample, timestep) - - sampler = FlowEulerSampler(sigma_min=float(sigma_min)) - return sampler.sample( - noise, - predict, - steps=int(steps), - guidance_strength=float(guidance_strength), - guidance_interval=tuple(float(value) for value in guidance_interval), - guidance_rescale=float(guidance_rescale), - guidance_as_difference=True, - rescale_t=float(rescale_t), - tqdm_desc="Sparse structure sampling", - ).samples - - -@torch.no_grad() -def decode_sparse_structure( - decoder: SparseStructureDecoder, - normalized_latent: torch.Tensor, - normalization: dict[str, Any] | None, - *, - batch_size: int = 1, -) -> torch.Tensor: - """Denormalize and decode logits; the pipeline places the decoder.""" - value = normalized_latent - if normalization is not None: - mean = torch.tensor(normalization["mean"], dtype=torch.float32, device="cpu") - std = torch.tensor(normalization["std"], dtype=torch.float32, device="cpu") - mean = mean.to(value.device).view(1, -1, 1, 1, 1) - std = std.to(value.device).view(1, -1, 1, 1, 1) - value = value * std + mean - decoded = [ - decoder(value[start : start + batch_size]) - for start in range(0, len(value), batch_size) - ] - return torch.cat(decoded, dim=0) diff --git a/uniforge3d/pipelines/texture.py b/uniforge3d/pipelines/texture.py deleted file mode 100644 index 0493eb09c1b22f6ee3aeecd138a3d8a916bba659..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/texture.py +++ /dev/null @@ -1,142 +0,0 @@ -"""PBR sampling, decoding and baking; model placement belongs to the pipeline.""" - -from __future__ import annotations - -from typing import Any - -import torch -import trimesh - -from ..modules.sparse import SparseTensor -from ..utils.preprocessing import InputBatch -from ..utils.texture_baking import to_glb -from .samplers import FlowEulerSampler, model_predictor -from .types import NormalizedShapeLatent - - -def denormalize_shape_latent( - config: dict[str, Any], - normalized_latent: NormalizedShapeLatent, - device: torch.device, -) -> SparseTensor: - """Convert normalized Shape1024 flow output to the shape VAE's latent space.""" - coords, feats = normalized_latent.coords, normalized_latent.feats - if coords.ndim != 2 or coords.shape[1] != 4: - raise ValueError(f"Expected Shape1024 coords [N,4], got {tuple(coords.shape)}") - if feats.ndim != 2 or feats.shape[0] != coords.shape[0]: - raise ValueError( - f"Shape1024 feature/coordinate mismatch: feats={tuple(feats.shape)}, " - f"coords={tuple(coords.shape)}" - ) - spatial = coords[:, 1:] - if spatial.numel() == 0 or int(spatial.min()) < 0 or int(spatial.max()) >= 64: - raise ValueError("Shape1024 coordinates are outside [0, 64)") - if not torch.isfinite(feats).all(): - raise ValueError("Shape1024 features contain NaN or Inf") - normalization = config["shape_slat_normalization"] - mean = torch.tensor(normalization["mean"], dtype=torch.float32)[None] - std = torch.tensor(normalization["std"], dtype=torch.float32)[None] - # Shape sampling returns normalized flow output; decoding consumes VAE latents. - feats = feats.float() * std + mean - return SparseTensor(feats=feats, coords=coords.int()).to(device) - - -@torch.no_grad() -def sample_texture( - model: torch.nn.Module, - config: dict[str, Any], - conditioner, - shape_vae_latent: SparseTensor, - batch: InputBatch, - dino_features: torch.Tensor, - view_assignment: dict[str, torch.Tensor], - device: torch.device, -) -> SparseTensor: - shape_norm = config["shape_slat_normalization"] - mean = torch.tensor(shape_norm["mean"], device=device)[None] - std = torch.tensor(shape_norm["std"], device=device)[None] - # Preserve the original VAE -> normalized flow conversion and its rounding. - shape_condition = shape_vae_latent.replace((shape_vae_latent.feats - mean) / std) - coords = shape_condition.coords[:, 1:].to(dtype=torch.int32) - if coords.numel() == 0 or int(coords.min()) < 0 or int(coords.max()) >= 64: - raise RuntimeError("Shape1024 latent does not contain valid coords64") - - condition = conditioner.encode( - model.adapter, - dino_features=dino_features.to(device), - vggt_images=batch.vggt_images.to(device), - structure_conditioned_coords=shape_condition.coords, - input_masks=batch.input_masks.to(device), - view_assignment=view_assignment, - ) - noise_channels = model.in_channels - shape_vae_latent.feats.shape[1] - noise = shape_condition.replace( - torch.randn(len(coords), noise_channels, device="cpu").to(coords.device) - ) - condition["cond"] = model.prepare_condition(noise, condition["cond"]) - condition["neg_cond"] = model.prepare_condition(noise, condition["neg_cond"]) - sampling = config["sampler"] - sampler = FlowEulerSampler(**sampling["args"]) - predict = model_predictor( - model, - condition["cond"], - condition["neg_cond"], - concat_cond=shape_condition, - ) - with torch.autocast(device_type=device.type, dtype=torch.bfloat16): - texture_slat = sampler.sample( - noise, - predict, - **sampling["params"], - verbose=True, - tqdm_desc="PBR texture sampling", - ).samples - texture_norm = config["texture_slat_normalization"] - mean = torch.tensor(texture_norm["mean"], device=device)[None] - std = torch.tensor(texture_norm["std"], device=device)[None] - return texture_slat.replace(texture_slat.feats * std + mean) - - -@torch.no_grad() -def decode_shape_and_texture( - shape_decoder: torch.nn.Module, - texture_decoder: torch.nn.Module, - shape_vae_latent: SparseTensor, - texture_vae_latent: SparseTensor, -): - """Decode with shared subdivisions and fill holes in the reference mesh.""" - meshes, subdivisions = shape_decoder(shape_vae_latent, return_subs=True) - voxels = texture_decoder(texture_vae_latent, guide_subs=subdivisions) * 0.5 + 0.5 - meshes[0].fill_holes() - return meshes[0], voxels[0] - - -@torch.no_grad() -def remesh_and_bake_texture( - texture_config: dict[str, Any], - mesh_config: dict[str, Any], - mesh, - pbr_voxel: SparseTensor, -) -> trimesh.Trimesh: - """Use the raw decoded surface and the official example's export settings.""" - mesh.simplify(int(mesh_config["pre_simplify_target"])) - return to_glb( - mesh.vertices, - mesh.faces, - attr_volume=pbr_voxel.feats, - coords=pbr_voxel.coords[:, 1:], - attr_layout={ - "base_color": slice(0, 3), - "metallic": slice(3, 4), - "roughness": slice(4, 5), - "alpha": slice(5, 6), - }, - aabb=[[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], - grid_size=int(mesh_config["grid_size"]), - texture_size=int(texture_config["texture_size"]), - decimation_target=int(texture_config.get("decimation_target", mesh_config["decimation_target"])), - remesh=True, - remesh_band=float(mesh_config["remesh_band"]), - remesh_project=float(mesh_config["remesh_project"]), - verbose=True, - ) diff --git a/uniforge3d/pipelines/types.py b/uniforge3d/pipelines/types.py deleted file mode 100644 index 4415b415f7b992ec18d49931c572e2618bd05abb..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/types.py +++ /dev/null @@ -1,19 +0,0 @@ -"""In-memory stage boundaries; none of these values are serialized.""" - -from dataclasses import dataclass - -import torch - - -@dataclass(frozen=True) -class SparseStructure: - coords32: torch.Tensor - coords64: torch.Tensor - - -@dataclass(frozen=True) -class NormalizedShapeLatent: - """Normalized flow output, before VAE denormalization.""" - - coords: torch.Tensor - feats: torch.Tensor diff --git a/uniforge3d/pipelines/uniforge3d_image_to_3d.py b/uniforge3d/pipelines/uniforge3d_image_to_3d.py deleted file mode 100644 index 35c7edcdb12c0c857b465d8ec88dfa8cd4861842..0000000000000000000000000000000000000000 --- a/uniforge3d/pipelines/uniforge3d_image_to_3d.py +++ /dev/null @@ -1,382 +0,0 @@ - - -from __future__ import annotations - -import json -from contextlib import ExitStack, contextmanager -from pathlib import Path -from typing import Sequence - -import torch -import trimesh -from huggingface_hub import snapshot_download - -from ..models.loaders import load_models, resolve_checkpoint -from ..utils.device import release_cuda -from ..utils.mesh import ( - display_to_model, - export_glb, - normalize_to_cube, - official_shape_only_postprocess, - surface_voxelize, -) -from ..utils.preprocessing import BackgroundRemover, InputBatch, build_input_batch -from .shape import decode_shape_latent, sample_shape_latent -from .sparse_structure import decode_sparse_structure, decoded_coordinates, sample_sparse_structure -from .texture import ( - decode_shape_and_texture, - denormalize_shape_latent, - remesh_and_bake_texture, - sample_texture, -) -from .types import NormalizedShapeLatent, SparseStructure - - -class UniForge3DImageTo3DPipeline: - - - def __init__( - self, - config: dict, - *, - device: int = 0, - low_vram: bool = True, - cache_dir: str | Path | None = None, - local_files_only: bool = False, - ) -> None: - self.config = config - self.device = torch.device("cuda", int(device)) - self.low_vram = low_vram - - with torch.device("cpu"): - models = load_models( - self.config, cache_dir=cache_dir, local_files_only=local_files_only, - ) - self.dino = models["dino"] - self.conditioner = models["conditioner"] - self.structure_model = models["structure_model"] - self.structure_decoder = models["structure_decoder"] - self.shape512_model = models["shape512_model"] - self.shape512_decoder = models["shape512_decoder"] - self.shape1024_model = models["shape1024_model"] - self.shape1024_decoder = models["shape1024_decoder"] - self.texture_model = models["texture_model"] - self.texture_decoder = models["texture_decoder"] - self.remove_background = BackgroundRemover( - self.config["image_preprocess"]["rembg_model"], self.device, - cache_dir=cache_dir, local_files_only=local_files_only, - ) - - @classmethod - def from_pretrained( - cls, path: str | Path, *, device: int = 0, low_vram: bool = True, - revision: str | None = None, cache_dir: str | Path | None = None, - local_files_only: bool = False, - ) -> "UniForge3DImageTo3DPipeline": - """Load a local model directory or a Hugging Face repository.""" - root = Path(path).expanduser() - if not root.is_dir(): - root = Path(snapshot_download( - str(path), revision=revision, cache_dir=cache_dir, - local_files_only=local_files_only, - allow_patterns=["pipeline.json", "uniforge3d/**/*.pt"], - )) - return cls.from_config( - root / "pipeline.json", weights_root=root, device=device, - low_vram=low_vram, cache_dir=cache_dir, - local_files_only=local_files_only, - ) - - @classmethod - def from_config( - cls, config_path: str | Path, *, device: int = 0, low_vram: bool = True, - weights_root: str | Path | None = None, - cache_dir: str | Path | None = None, local_files_only: bool = False, - ) -> "UniForge3DImageTo3DPipeline": - """Load a JSON config; local weights default to the repository's weights/.""" - config = json.loads(Path(config_path).read_text(encoding="utf-8")) - root = (Path(weights_root).expanduser() if weights_root is not None - else Path(__file__).resolve().parents[2] / "weights") - options = {"cache_dir": cache_dir, "local_files_only": local_files_only} - for stage in ("sparse_structure", "structured_latent_512", "structured_latent_1024", "texture"): - weights = config[stage]["weights"] - for key in ("checkpoint", "adapter_checkpoint", "dit_base", "vggt_base", "base_checkpoint"): - if key in weights: - weights[key] = resolve_checkpoint(weights[key], root, **options) - if "decoder" in config[stage]: - decoder = config[stage]["decoder"] - decoder["checkpoint"] = resolve_checkpoint( - decoder["checkpoint"], root, decoder=True, **options, - ) - for key in ("shape_decoder_checkpoint", "texture_decoder_checkpoint"): - config["texture"][key] = resolve_checkpoint( - config["texture"][key], root, decoder=True, **options, - ) - vggt = config["conditioner"]["vggt_feature_extractor"] - vggt["checkpoint_path"] = resolve_checkpoint(vggt["checkpoint_path"], root, **options) - return cls(config, device=device, low_vram=low_vram, **options) - - @contextmanager - def _use_models(self, *models): - - try: - for model in models: - model.to(self.device) - yield - finally: - if self.low_vram: - for model in models: - model.to("cpu") - release_cuda() - - def _preprocess_images(self, images: Sequence[str | Path]) -> InputBatch: - - with ExitStack() as stack: - background_loaded = False - - def remove_background(image): - nonlocal background_loaded - if not background_loaded: - stack.enter_context(self._use_models(self.remove_background.model)) - background_loaded = True - return self.remove_background(image) - - return build_input_batch( - images, - self.config["image_preprocess"], - remove_background, - ) - - @torch.no_grad() - def _encode_dino(self, batch: InputBatch) -> dict[str, torch.Tensor]: - """Encode once per resolution and share 512px features across stages.""" - with self._use_models(self.dino): - images512 = batch.dino_images512.to(self.device, dtype=torch.float32) - with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16): - structure_features = self.dino(images512).cpu() - shape1024_features = self.dino( - batch.dino_images1024.to(self.device, dtype=torch.float32) - ).cpu() - return { - "sparse_structure": structure_features, - "shape512": structure_features, - "shape1024": shape1024_features, - } - - def _generate_structure( - self, - batch: InputBatch, - dino_features: torch.Tensor, - ) -> SparseStructure: - sampling = self.config["sparse_structure"]["sampler"] - dit = self.structure_model.dit - resolution = dit.resolution - noise = torch.randn( - (1, dit.in_channels, resolution, resolution, resolution), - device="cpu", - ).to(self.device) - with self._use_models(self.structure_model): - vggt_images = batch.vggt_images.to(self.device) - with torch.autocast(device_type=self.device.type, dtype=torch.bfloat16): - latent = sample_sparse_structure( - self.structure_model, - noise, - vggt_images, - dino_features.to(self.device), - **sampling["args"], - **sampling["params"], - ) - with self._use_models(self.structure_decoder): - occupancy_logits = decode_sparse_structure( - self.structure_decoder, - latent, - self.config["sparse_structure"]["decoder"].get("normalization"), - ) - coords32, coords64 = decoded_coordinates(occupancy_logits) - return SparseStructure(coords32.cpu(), coords64.cpu()) - - def _sample_shape( - self, - model: torch.nn.Module, - config: dict, - batch: InputBatch, - *, - latent_coords: torch.Tensor, - structure_conditioned_coords: torch.Tensor, - dino_features: torch.Tensor, - return_view_assignment: bool, - ): - latent_coords = latent_coords.int().contiguous() - structure_conditioned_coords = structure_conditioned_coords.int().contiguous() - with self._use_models(model, self.conditioner): - conditioning = config["conditioning"] - latent_coords = latent_coords.to(device=self.device, dtype=torch.int32) - condition = self.conditioner.encode( - model.adapter, - dino_features=dino_features.to(device=self.device, dtype=torch.float32), - vggt_images=batch.vggt_images.to(device=self.device, dtype=torch.float32), - structure_conditioned_coords=structure_conditioned_coords, - input_masks=batch.input_masks.to(device=self.device, dtype=torch.bool), - latent_coords=latent_coords, - router_grid=int(conditioning["grid_resolution"]), - ) - latent = sample_shape_latent( - model, - latent_coords, - condition, - config["sampler"], - description=f"Shape-{config['decoder']['resolution']} sampling", - ) - view_assignment = ( - {"selected_view": condition["cond"]["selected_view"].cpu()} - if return_view_assignment else None - ) - if not torch.isfinite(latent.feats).all(): - raise RuntimeError("Shape sampling produced non-finite latent features") - return latent, view_assignment - - def _generate_shape512( - self, - batch: InputBatch, - structure: SparseStructure, - dino_features: torch.Tensor, - ) -> trimesh.Trimesh: - latent, _ = self._sample_shape( - self.shape512_model, - self.config["structured_latent_512"], - batch, - latent_coords=structure.coords32, - structure_conditioned_coords=structure.coords64, - dino_features=dino_features, - return_view_assignment=False, - ) - with self._use_models(self.shape512_decoder): - mesh = decode_shape_latent( - self.shape512_decoder, - latent, - self.config["structured_latent_512"]["decoder"].get("normalization"), - )[0] - return official_shape_only_postprocess( - mesh.vertices, - mesh.faces, - **self.config["mesh_postprocess"], - ) - - def _generate_shape1024( - self, - batch: InputBatch, - coords64: torch.Tensor, - dino_features: torch.Tensor, - ) -> tuple[NormalizedShapeLatent, dict[str, torch.Tensor]]: - latent, view_assignment = self._sample_shape( - self.shape1024_model, - self.config["structured_latent_1024"], - batch, - latent_coords=coords64, - structure_conditioned_coords=coords64, - dino_features=dino_features, - return_view_assignment=True, - ) - if view_assignment is None: - raise RuntimeError("Shape1024 must provide its texture routing result") - shape = NormalizedShapeLatent(coords=latent.coords.cpu(), feats=latent.feats.cpu()) - return shape, view_assignment - - def _shape512_to_coords64(self, mesh: trimesh.Trimesh) -> torch.Tensor: - """Convert the already-remeshed Shape-512 surface to coords64.""" - config = self.config["structured_latent_handoff"] - model_vertices = display_to_model(mesh.vertices) - normalized_vertices, _ = normalize_to_cube(model_vertices, config["target_max_side"]) - xyz = torch.from_numpy( - surface_voxelize(normalized_vertices, mesh.faces, config["surface_voxel_resolution"]) - ) - return torch.cat((torch.zeros((len(xyz), 1), dtype=torch.int32), xyz.int()), dim=1) - - def _generate_texture( - self, - batch: InputBatch, - normalized_shape_latent: NormalizedShapeLatent, - view_assignment: dict[str, torch.Tensor], - dino_features: torch.Tensor, - ) -> trimesh.Trimesh: - config = self.config["texture"] - with self._use_models( - self.texture_model, - self.shape1024_decoder, - self.texture_decoder, - self.conditioner, - ): - shape_vae_latent = denormalize_shape_latent( - config, - normalized_shape_latent, - self.device, - ) - texture_vae_latent = sample_texture( - self.texture_model, - config, - self.conditioner, - shape_vae_latent, - batch, - dino_features, - view_assignment, - self.device, - ) - reference_mesh, pbr_voxel = decode_shape_and_texture( - self.shape1024_decoder, self.texture_decoder, shape_vae_latent, texture_vae_latent - ) - del shape_vae_latent, texture_vae_latent - return remesh_and_bake_texture( - config, - self.config["mesh_postprocess"], - reference_mesh, - pbr_voxel, - ) - - @torch.no_grad() - def run( - self, - images: Sequence[str | Path], - output: str | Path, - *, - seed: int | None = None, - overwrite: bool = False, - ) -> Path: - - output_path = Path(output).expanduser().resolve() - if output_path.exists() and (not overwrite or not output_path.is_file()): - raise FileExistsError( - f"Output already exists: {output_path}; use --overwrite to recompute" - ) - seed = self.config["default_seed"] if seed is None else seed - - batch = self._preprocess_images(images) - - torch.cuda.set_device(self.device) - torch.manual_seed(seed) - try: - # Share one DINO model while preserving each stage's original precision. - dino_features = self._encode_dino(batch) - - sparse_structure = self._generate_structure(batch, dino_features["sparse_structure"]) - shape512_mesh = self._generate_shape512( - batch, sparse_structure, dino_features["shape512"] - ) - - - structure_conditioned_coords = self._shape512_to_coords64(shape512_mesh) - shape1024_latent, view_assignment = self._generate_shape1024( - batch, - structure_conditioned_coords, - dino_features["shape1024"], - ) - - # Texture reuses the Shape1024 latent and its per-token view routing. - textured_mesh = self._generate_texture( - batch, - shape1024_latent, - view_assignment, - dino_features["shape1024"], - ) - return export_glb(textured_mesh, output_path, overwrite=overwrite) - finally: - release_cuda() diff --git a/uniforge3d/representations/__init__.py b/uniforge3d/representations/__init__.py deleted file mode 100644 index 9a3c57f16caa7e1ed2f396374f231a0d9d1e40c7..0000000000000000000000000000000000000000 --- a/uniforge3d/representations/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -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/uniforge3d/representations/mesh/__init__.py b/uniforge3d/representations/mesh/__init__.py deleted file mode 100644 index a850298a593bf5e8e86855dab53e3084c776d018..0000000000000000000000000000000000000000 --- a/uniforge3d/representations/mesh/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .base import Mesh, MeshWithVoxel, MeshWithPbrMaterial, TextureFilterMode, TextureWrapMode, AlphaMode, PbrMaterial, Texture - diff --git a/uniforge3d/representations/mesh/base.py b/uniforge3d/representations/mesh/base.py deleted file mode 100644 index f742396da71841316b759a8ac6150cc29d6a906f..0000000000000000000000000000000000000000 --- a/uniforge3d/representations/mesh/base.py +++ /dev/null @@ -1,235 +0,0 @@ -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/uniforge3d/representations/voxel/__init__.py b/uniforge3d/representations/voxel/__init__.py deleted file mode 100644 index a5d68494db7998f21a2805ee23b4743e167d9ae6..0000000000000000000000000000000000000000 --- a/uniforge3d/representations/voxel/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .voxel_model import Voxel diff --git a/uniforge3d/representations/voxel/voxel_model.py b/uniforge3d/representations/voxel/voxel_model.py deleted file mode 100644 index 8399fc169c2dce04aadcb6f52f74739358606e04..0000000000000000000000000000000000000000 --- a/uniforge3d/representations/voxel/voxel_model.py +++ /dev/null @@ -1,55 +0,0 @@ -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/uniforge3d/utils/__init__.py b/uniforge3d/utils/__init__.py deleted file mode 100644 index 9f40a9b8f702beeddc6979b573338cda2b120c18..0000000000000000000000000000000000000000 --- a/uniforge3d/utils/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Configuration, input preprocessing, device and geometry helpers.""" diff --git a/uniforge3d/utils/device.py b/uniforge3d/utils/device.py deleted file mode 100644 index afd7921a5d6aeec5f79dbedf5108ed8e22b0ec74..0000000000000000000000000000000000000000 --- a/uniforge3d/utils/device.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Device-memory cleanup shared by the sequential inference stages.""" - -import gc - -import torch - - -def release_cuda() -> None: - gc.collect() - if torch.cuda.is_available(): - torch.cuda.empty_cache() diff --git a/uniforge3d/utils/mesh.py b/uniforge3d/utils/mesh.py deleted file mode 100644 index 9e0e68c98163f651c64306095043305363534931..0000000000000000000000000000000000000000 --- a/uniforge3d/utils/mesh.py +++ /dev/null @@ -1,218 +0,0 @@ -"""Shape-only remeshing and the established 512-to-1024 surface-voxel handoff.""" - -from __future__ import annotations - -import os -import tempfile -import warnings -from pathlib import Path -from typing import Any - -import cumesh -import numpy as np -import torch -import trimesh - - -def export_glb(mesh: trimesh.Trimesh, path: Path, *, overwrite: bool) -> Path: - """Atomically publish one complete GLB without truncating an older result.""" - path.parent.mkdir(parents=True, exist_ok=True) - fd, temporary_name = tempfile.mkstemp(prefix=f".{path.stem}.", suffix=".glb", dir=path.parent) - os.close(fd) - temporary = Path(temporary_name) - try: - mesh.export(temporary, file_type="glb", extension_webp=True) - if overwrite: - os.replace(temporary, path) - else: - os.link(temporary, path) - finally: - temporary.unlink(missing_ok=True) - return path - - -def official_shape_only_postprocess( - vertices: torch.Tensor, - faces: torch.Tensor, - *, - grid_size: int, - pre_simplify_target: int, - decimation_target: int, - remesh_band: float, - remesh_project: float, -) -> trimesh.Trimesh: - """TRELLIS.2 example.py/to_glb geometry path without UV or texture work.""" - mesh = cumesh.CuMesh() - mesh.init(vertices, faces) - mesh.simplify(pre_simplify_target, verbose=False) - try: - mesh.fill_holes(max_hole_perimeter=3e-2) - except RuntimeError as error: - if "[CuMesh]" not in str(error) or "invalid configuration argument" not in str(error): - raise - warnings.warn( - "CuMesh fill_holes rejected this mesh; continuing from the simplified mesh.", - RuntimeWarning, - ) - del mesh - torch.cuda.empty_cache() - mesh = cumesh.CuMesh() - mesh.init(vertices, faces) - mesh.simplify(pre_simplify_target, verbose=False) - filled_vertices, filled_faces = mesh.read() - bvh = cumesh.cuBVH(filled_vertices, filled_faces) - scale = (grid_size + 3 * remesh_band) / grid_size - mesh.init( - *cumesh.remeshing.remesh_narrow_band_dc( - filled_vertices, - filled_faces, - center=torch.zeros(3, device=vertices.device, dtype=vertices.dtype), - scale=scale, - resolution=grid_size, - band=remesh_band, - project_back=remesh_project, - verbose=False, - bvh=bvh, - ) - ) - mesh.simplify(decimation_target, verbose=False) - mesh.compute_vertex_normals() - output_vertices, output_faces = mesh.read() - output_normals = mesh.read_vertex_normals() - - vertices_np = output_vertices.cpu().numpy() - faces_np = output_faces.cpu().numpy() - normals_np = output_normals.cpu().numpy() - # Model coordinates -> GLB display coordinates: (x,y,z) -> (x,z,-y). - vertices_np[:, 1], vertices_np[:, 2] = vertices_np[:, 2], -vertices_np[:, 1] - normals_np[:, 1], normals_np[:, 2] = normals_np[:, 2], -normals_np[:, 1] - return trimesh.Trimesh( - vertices=vertices_np, - faces=faces_np, - vertex_normals=normals_np, - process=False, - ) - - -def display_to_model(vertices: np.ndarray) -> np.ndarray: - """Undo GLB export axes: (x,y,z) -> (x,-z,y).""" - return np.asarray(vertices, dtype=np.float64)[:, [0, 2, 1]] * [1.0, -1.0, 1.0] - - -def normalize_to_cube(vertices: np.ndarray, target_max_side: float) -> tuple[np.ndarray, dict[str, Any]]: - vertices = np.asarray(vertices, dtype=np.float64) - if vertices.ndim != 2 or vertices.shape[1] != 3 or len(vertices) == 0: - raise ValueError("Expected nonempty [N,3] vertices") - if not np.isfinite(vertices).all() or not 0 < target_max_side < 1: - raise ValueError("Nonfinite mesh or invalid target side") - lower, upper = vertices.min(axis=0), vertices.max(axis=0) - center = (lower + upper) * 0.5 - longest_side = float((upper - lower).max()) - if longest_side <= 1e-12: - raise ValueError("Degenerate mesh bounds") - scale = target_max_side / longest_side - normalized = (vertices - center) * scale - bounds = np.stack((normalized.min(axis=0), normalized.max(axis=0))) - if not np.allclose(bounds.mean(axis=0), 0.0, atol=1e-10): - raise RuntimeError("Normalized mesh is not AABB centered") - if not np.isclose(np.ptp(normalized, axis=0).max(), target_max_side, atol=1e-10): - raise RuntimeError("Normalized mesh does not have the requested longest side") - if np.abs(normalized).max() >= 0.5: - raise RuntimeError("Normalized mesh is outside the open unit cube") - transform = np.eye(4) - transform[:3, :3] *= scale - transform[:3, 3] = -center * scale - return normalized, { - "center_model": center.tolist(), - "uniform_scale": scale, - "target_max_side": target_max_side, - "source_bounds_model": [lower.tolist(), upper.tolist()], - "normalized_bounds_model": bounds.tolist(), - "model_to_normalized_4x4": transform.tolist(), - } - - -def surface_voxelize( - vertices: np.ndarray, - faces: np.ndarray, - resolution: int, - *, - max_faces_per_chunk: int = 100_000, -) -> np.ndarray: - """Voxelize triangle surfaces with an exact triangle-box SAT test.""" - vertices = np.asarray(vertices, dtype=np.float64) - faces = np.asarray(faces, dtype=np.int64) - if max_faces_per_chunk <= 0: - raise ValueError("max_faces_per_chunk must be positive") - - half_size = 0.5 / resolution - coord_chunks = [] - for start in range(0, len(faces), max_faces_per_chunk): - triangles = vertices[faces[start : start + max_faces_per_chunk]] - grid_triangles = (triangles + 0.5) * resolution - lower = np.floor(grid_triangles.min(axis=1)).astype(np.int32) - upper = np.floor(grid_triangles.max(axis=1)).astype(np.int32) - lower = np.clip(lower, 0, resolution - 1) - upper = np.clip(upper, 0, resolution - 1) - dimensions = upper - lower + 1 - - for dimensions_key in np.unique(dimensions, axis=0): - triangle_ids = np.flatnonzero(np.all(dimensions == dimensions_key, axis=1)) - ranges = [np.arange(int(size), dtype=np.int32) for size in dimensions_key] - offsets = np.stack(np.meshgrid(*ranges, indexing="ij"), axis=-1).reshape(-1, 3) - candidate_coords = lower[triangle_ids, None, :] + offsets[None, :, :] - candidate_coords = candidate_coords.reshape(-1, 3) - candidate_triangles = np.broadcast_to( - triangles[triangle_ids, None, :, :], - (len(triangle_ids), len(offsets), 3, 3), - ).reshape(-1, 3, 3) - centers = -0.5 + (candidate_coords.astype(np.float64) + 0.5) / resolution - intersects = _triangles_intersect_axis_aligned_boxes( - candidate_triangles, - centers, - half_size, - ) - coord_chunks.append(candidate_coords[intersects].astype(np.int32, copy=False)) - - coords = np.concatenate(coord_chunks, axis=0) if coord_chunks else np.empty((0, 3), dtype=np.int32) - if coords.size == 0: - raise RuntimeError("Surface voxelization returned no voxels") - coords = np.unique(coords, axis=0) - if int(coords.min()) < 0 or int(coords.max()) >= resolution: - raise RuntimeError("Surface voxels are outside the canonical grid") - return coords - - -def _triangles_intersect_axis_aligned_boxes( - triangles: np.ndarray, - centers: np.ndarray, - half_size: float, -) -> np.ndarray: - """Vectorized Akenine-Moller triangle/AABB overlap test.""" - local = triangles - centers[:, None, :] - edge0 = local[:, 1] - local[:, 0] - edge1 = local[:, 2] - local[:, 1] - edge2 = local[:, 0] - local[:, 2] - keep = np.ones(len(local), dtype=bool) - epsilon = np.finfo(np.float64).eps * 32 - - keep &= np.all(local.min(axis=1) <= half_size + epsilon, axis=1) - keep &= np.all(local.max(axis=1) >= -half_size - epsilon, axis=1) - - for edge in (edge0, edge1, edge2): - axes = ( - np.stack((np.zeros(len(edge)), edge[:, 2], -edge[:, 1]), axis=1), - np.stack((-edge[:, 2], np.zeros(len(edge)), edge[:, 0]), axis=1), - np.stack((edge[:, 1], -edge[:, 0], np.zeros(len(edge))), axis=1), - ) - for axis in axes: - projection = np.einsum("nvc,nc->nv", local, axis) - radius = half_size * np.abs(axis).sum(axis=1) + epsilon - keep &= projection.min(axis=1) <= radius - keep &= projection.max(axis=1) >= -radius - - normal = np.cross(edge0, local[:, 2] - local[:, 0]) - plane_distance = np.einsum("nc,nc->n", normal, local[:, 0]) - plane_radius = half_size * np.abs(normal).sum(axis=1) + epsilon - keep &= np.abs(plane_distance) <= plane_radius - return keep diff --git a/uniforge3d/utils/preprocessing.py b/uniforge3d/utils/preprocessing.py deleted file mode 100644 index 68244dfbcd8b3ee7883986a5a957d9ffc2558c30..0000000000000000000000000000000000000000 --- a/uniforge3d/utils/preprocessing.py +++ /dev/null @@ -1,156 +0,0 @@ -"""One alpha crop shared by every stage, with no disk intermediates.""" - -from __future__ import annotations - -import math -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Callable, Sequence - -import numpy as np -import torch -from PIL import Image -from torchvision import transforms -from transformers import AutoModelForImageSegmentation - - -class BackgroundRemover: - - - def __init__(self, checkpoint: str | Path, device: torch.device, **download_kwargs) -> None: - self.device = device - self.model = AutoModelForImageSegmentation.from_pretrained( - checkpoint, trust_remote_code=True, **download_kwargs - ).eval() - self.transform = transforms.Compose( - [ - transforms.Resize((1024, 1024)), - transforms.ToTensor(), - transforms.Normalize( - [0.485, 0.456, 0.406], - [0.229, 0.224, 0.225], - ), - ] - ) - - @torch.no_grad() - def __call__(self, image: Image.Image) -> Image.Image: - inputs = self.transform(image).unsqueeze(0).to(self.device) - prediction = self.model(inputs)[-1].sigmoid().cpu() - mask = transforms.ToPILImage()(prediction[0].squeeze()).resize(image.size) - image.putalpha(mask) - return image - - -@dataclass(frozen=True) -class ViewTensors: - dino_images512: torch.Tensor - dino_images1024: torch.Tensor - vggt_images: torch.Tensor - input_masks: torch.Tensor - - -@dataclass(frozen=True) -class InputBatch: - - dino_images512: torch.Tensor - dino_images1024: torch.Tensor - vggt_images: torch.Tensor - input_masks: torch.Tensor - - -def alpha_bbox_crop_params( - alpha: np.ndarray, - padding_factor: float = 1.0, - alpha_threshold: float = 0.0, - filepath: str = "", -) -> tuple[int, int, int]: - mask = np.asarray(alpha) > float(alpha_threshold) - if not np.any(mask): - raise ValueError(f"{filepath}: empty alpha mask") - ys, xs = np.nonzero(mask) - x0, x1 = int(xs.min()), int(xs.max()) - y0, y1 = int(ys.min()), int(ys.max()) - side = max(x1 - x0 + 1, y1 - y0 + 1) - if float(padding_factor) != 1.0: - side = max(1, int(math.ceil(float(side) * float(padding_factor)))) - center_x = (x0 + x1 + 1) * 0.5 - center_y = (y0 + y1 + 1) * 0.5 - return int(math.floor(center_x - side * 0.5)), int(math.floor(center_y - side * 0.5)), int(side) - - -def crop_with_padding_np( - array: np.ndarray, - left: int, - top: int, - side: int, - fill_value: float | int = 0, -) -> np.ndarray: - shape = (side, side) if array.ndim == 2 else (side, side, array.shape[2]) - output = np.full(shape, fill_value, dtype=array.dtype) - height, width = array.shape[:2] - src_left, src_top = max(left, 0), max(top, 0) - src_right, src_bottom = min(left + side, width), min(top + side, height) - if src_right <= src_left or src_bottom <= src_top: - return output - dst_left, dst_top = src_left - left, src_top - top - output[ - dst_top : dst_top + src_bottom - src_top, - dst_left : dst_left + src_right - src_left, - ] = array[src_top:src_bottom, src_left:src_right] - return output - - -def crop_resize_rgb_np(rgb: np.ndarray, crop: tuple[int, int, int], image_size: int) -> torch.Tensor: - cropped = crop_with_padding_np(rgb, *crop, fill_value=0) - resized = Image.fromarray(cropped).resize((image_size, image_size), Image.Resampling.LANCZOS) - array = np.asarray(resized, dtype=np.float32) / 255.0 - return torch.from_numpy(array).permute(2, 0, 1).contiguous().float() - - -def preprocess_view( - path: Path, - config: dict[str, Any], - remove_background: Callable[[Image.Image], Image.Image], -) -> ViewTensors: - alpha_threshold = float(config["alpha_threshold"]) - with Image.open(path) as image: - # Match TRELLIS.2: only non-opaque RGBA inputs already have an alpha mask. - if image.mode != "RGBA" or np.all(np.asarray(image.getchannel("A")) == 255): - image = remove_background(image.convert("RGB")) - rgba = np.asarray(image.convert("RGBA"), dtype=np.float32) / 255.0 - alpha = rgba[..., 3] - mask = alpha > alpha_threshold - if not np.any(mask): - raise ValueError(f"{path}: empty alpha mask") - # Preserve the trained black-background alpha composite and rounding. - rgb = (rgba[..., :3] * rgba[..., 3:4] * 255.0).clip(0, 255).astype(np.uint8) - crop = alpha_bbox_crop_params(alpha, config["padding_factor"], alpha_threshold, str(path)) - dino_images512 = crop_resize_rgb_np(rgb, crop, 512) - dino_images1024 = crop_resize_rgb_np(rgb, crop, 1024) - vggt448 = crop_resize_rgb_np(rgb, crop, 448) - alpha_crop = crop_with_padding_np(alpha, *crop, fill_value=0.0) - resized_alpha = np.asarray( - Image.fromarray(np.clip(alpha_crop * 255.0, 0, 255).astype(np.uint8)).resize( - (448, 448), Image.Resampling.NEAREST - ), - dtype=np.uint8, - ) - # Routing uses confident foreground, independently of the crop threshold. - masks448 = torch.from_numpy((resized_alpha > 127).copy()).bool() - return ViewTensors(dino_images512, dino_images1024, vggt448, masks448) - - -def build_input_batch( - images: Sequence[str | Path], - config: dict[str, Any], - remove_background: Callable[[Image.Image], Image.Image], -) -> InputBatch: - paths = [Path(image).expanduser().resolve() for image in images] - views = [preprocess_view(path, config, remove_background) for path in paths] - return InputBatch( - dino_images512=torch.stack([view.dino_images512 for view in views]).unsqueeze(0), - dino_images1024=torch.stack([view.dino_images1024 for view in views]).unsqueeze(0), - vggt_images=torch.stack([view.vggt_images for view in views]).unsqueeze(0), - input_masks=torch.stack([view.input_masks for view in views]).unsqueeze(0), - ) diff --git a/uniforge3d/utils/texture_baking.py b/uniforge3d/utils/texture_baking.py deleted file mode 100644 index 1ce82271bab56dc757b3cd45ceea4f88d1bea551..0000000000000000000000000000000000000000 --- a/uniforge3d/utils/texture_baking.py +++ /dev/null @@ -1,331 +0,0 @@ -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