Delete uniforge3d
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- uniforge3d/__init__.pyDeleted-5
- uniforge3d/configs/pipeline.jsonDeleted-714
- uniforge3d/models/__init__.pyDeleted-24
- uniforge3d/models/conditioning.pyDeleted-109
- uniforge3d/models/dino.pyDeleted-63
- uniforge3d/models/joint_dit_vggt_stage1.pyDeleted-383
- uniforge3d/models/loaders.pyDeleted-200
- uniforge3d/models/lora.pyDeleted-73
- uniforge3d/models/sparse_structure_flow.pyDeleted-246
- uniforge3d/models/structured_latent_flow.pyDeleted-369
- uniforge3d/models/vaes/__init__.pyDeleted-1
- uniforge3d/models/vaes/flexi_dual_grid.pyDeleted-67
- uniforge3d/models/vaes/sparse_structure.pyDeleted-175
- uniforge3d/models/vaes/sparse_unet.pyDeleted-384
- uniforge3d/models/vggt/__init__.pyDeleted-3
- uniforge3d/models/vggt/heads/camera_head.pyDeleted-150
- uniforge3d/models/vggt/heads/dpt_head.pyDeleted-485
- uniforge3d/models/vggt/heads/head_act.pyDeleted-126
- uniforge3d/models/vggt/heads/utils.pyDeleted-110
- uniforge3d/models/vggt/layers/__init__.pyDeleted-12
- uniforge3d/models/vggt/layers/attention.pyDeleted-94
- uniforge3d/models/vggt/layers/block.pyDeleted-135
- uniforge3d/models/vggt/layers/layer_scale.pyDeleted-23
- uniforge3d/models/vggt/layers/mlp.pyDeleted-41
- uniforge3d/models/vggt/layers/patch_embed.pyDeleted-86
- uniforge3d/models/vggt/layers/rope.pyDeleted-189
- uniforge3d/models/vggt/layers/swiglu_ffn.pyDeleted-68
- uniforge3d/models/vggt/layers/vision_transformer.pyDeleted-368
- uniforge3d/models/vggt/models/aggregator.pyDeleted-330
- uniforge3d/models/vggt/models/vggt.pyDeleted-64
- uniforge3d/models/vggt/utils/pose_enc.pyDeleted-125
- uniforge3d/models/vggt/utils/rotation.pyDeleted-133
- uniforge3d/models/vggt_adapter.pyDeleted-508
- uniforge3d/models/vggt_routed_features.pyDeleted-96
- uniforge3d/models/view_router.pyDeleted-293
- uniforge3d/modules/attention/__init__.pyDeleted-4
- uniforge3d/modules/attention/config.pyDeleted-30
- uniforge3d/modules/attention/full_attn.pyDeleted-146
- uniforge3d/modules/attention/modules.pyDeleted-103
- uniforge3d/modules/attention/rope.pyDeleted-48
- uniforge3d/modules/norm.pyDeleted-32
- uniforge3d/modules/sparse/__init__.pyDeleted-66
- uniforge3d/modules/sparse/attention/__init__.pyDeleted-4
- uniforge3d/modules/sparse/attention/full_attn.pyDeleted-221
- uniforge3d/modules/sparse/attention/modules.pyDeleted-142
- uniforge3d/modules/sparse/attention/rope.pyDeleted-58
- uniforge3d/modules/sparse/attention/routed_full_only_flash.pyDeleted-196
- uniforge3d/modules/sparse/attention/windowed_attn.pyDeleted-191
- uniforge3d/modules/sparse/basic.pyDeleted-837
- uniforge3d/modules/sparse/config.pyDeleted-46
12345"""UniForge3D multi-view image-to-3D inference."""
from .pipelines import UniForge3DImageTo3DPipeline
__all__ = ["UniForge3DImageTo3DPipeline"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714{ "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 } } }}123456789101112131415161718192021222324"""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 value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""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 FrozenRoutedVGGTFeatureExtractorfrom .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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Shared frozen DINOv3 encoder for Stage1 and structured-latent conditioning."""
from __future__ import annotations
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom 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 hidden123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383"""Inference-only Stage1 DiT/VGGT model topology."""
from __future__ import annotations
import mathfrom typing import Any, Sequence
import torchimport torch.nn as nnimport torch.nn.functional as F
from uniforge3d.models.vggt.models.aggregator import slice_expand_and_flattenfrom uniforge3d.models.vggt.models.vggt import VGGT
from ..modules.utils import manual_castfrom .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 h123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Initialize models and load original training weights over their pretrained bases."""
import jsonimport refrom pathlib import Pathfrom typing import Any
import torchfrom easydict import EasyDict as edictfrom huggingface_hub import hf_hub_download, snapshot_downloadfrom safetensors.torch import load_file, load_model
from . import __getattr__ as get_model_classfrom .conditioning import StructuredLatentConditionerfrom .dino import DinoV3Encoderfrom .lora import attach_stage1_lorafrom .structured_latent_flow import VGGTConditionedSLatFlowModelfrom .vaes.flexi_dual_grid import FlexiDualGridVaeDecoderfrom .vaes.sparse_structure import SparseStructureDecoderfrom .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, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Unmerged Stage1 LoRA, with the same operations and FP32 parameters as training."""
from fnmatch import fnmatchcase
import torchfrom torch import nnfrom 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246from functools import partialfrom typing import Literal, Optional, Tuple
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from ..modules.attention import RotaryPositionEmbedderfrom ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlockfrom ..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 h123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369from functools import partialfrom typing import Dict, List, Literal, Optional, Tuple, Union
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from ..modules import sparse as spfrom ..modules.sparse.attention.routed_full_only_flash import ( PackedRoutedFullOnlyLayoutBuilder, RoutedFullOnlyFlashCrossAttention,)from ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlockfrom ..modules.transformer import AbsolutePositionEmbedderfrom ..modules.utils import convert_module_to, manual_cast, str_to_dtypefrom .sparse_structure_flow import TimestepEmbedderfrom .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)1"""VAE network definitions for sparse structure, geometry and PBR decoding."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Ffrom ...modules import sparse as spfrom .sparse_unet import ( SparseResBlock3d, SparseConvNeXtBlock3d,
SparseResBlockDownsample3d, SparseResBlockUpsample3d, SparseResBlockS2C3d, SparseResBlockC2S3d,)from .sparse_unet import ( SparseUnetVaeDecoder,)from ...representations import Meshfrom 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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Ffrom ...modules.norm import GroupNorm32, ChannelLayerNorm32from ...modules.spatial import pixel_shuffle_3dfrom ...modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32
def norm_layer(norm_type: str, *args, **kwargs) -> nn.Module: """ Return a normalization layer. """ if norm_type == "group": return GroupNorm32(32, *args, **kwargs) elif norm_type == "layer": return ChannelLayerNorm32(*args, **kwargs) else: raise ValueError(f"Invalid norm type {norm_type}")
class ResBlock3d(nn.Module): def __init__( self, channels: int, out_channels: Optional[int] = None, norm_type: Literal["group", "layer"] = "layer", ): super().__init__() self.channels = channels self.out_channels = out_channels or channels
self.norm1 = norm_layer(norm_type, channels) self.norm2 = norm_layer(norm_type, self.out_channels) self.conv1 = nn.Conv3d(channels, self.out_channels, 3, padding=1) self.conv2 = zero_module(nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1)) self.skip_connection = nn.Conv3d(channels, self.out_channels, 1) if channels != self.out_channels else nn.Identity() def forward(self, x: torch.Tensor) -> torch.Tensor: h = self.norm1(x) h = F.silu(h) h = self.conv1(h) h = self.norm2(h) h = F.silu(h) h = self.conv2(h) h = h + self.skip_connection(x) return h
class 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Ffrom ...modules.utils import convert_module_to_f16, convert_module_to_f32, zero_modulefrom ...modules import sparse as spfrom ...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)
123"""Local VGGT package for the TRELLIS.2 stage2 joint experiment."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150# 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 mathimport numpy as np
import torchimport torch.nn as nnimport torch.nn.functional as F
from uniforge3d.models.vggt.layers import Mlpfrom uniforge3d.models.vggt.layers.block import Blockfrom 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485# 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 osfrom typing import List, Dict, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom .head_act import activate_headfrom .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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# 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 torchimport 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)))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# 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 torchimport 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
123456789101112# 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 Mlpfrom .patch_embed import PatchEmbedfrom .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFusedfrom .block import NestedTensorBlockfrom .attention import MemEffAttention
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# 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 loggingimport osimport warnings
from torch import Tensorfrom torch import nnimport 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135# 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 torchfrom torch import nn, Tensor
from .attention import Attentionfrom .layer_scale import LayerScalefrom .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
1234567891011121314151617181920212223# 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 torchfrom torch import Tensorfrom 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
1234567891011121314151617181920212223242526272829303132333435363738394041# 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# 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 Tensorimport 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# 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 npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom 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)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# 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 osfrom typing import Callable, Optionalimport warnings
from torch import Tensor, nnimport 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 = SwiGLUFFNXFORMERS_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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368# 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 partialimport mathfrom typing import Sequence, Tuple, Union, Callable
import torchimport torch.nn as nnfrom 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 model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330# 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 loggingimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom typing import Optional, Tuple, Union, List, Dict, Any
from uniforge3d.models.vggt.layers import PatchEmbedfrom uniforge3d.models.vggt.layers.block import Blockfrom uniforge3d.models.vggt.layers.rope import RotaryPositionEmbedding2D, PositionGetterfrom 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 torchimport torch.nn as nnfrom huggingface_hub import PyTorchModelHubMixin
from uniforge3d.models.vggt.heads.camera_head import CameraHeadfrom uniforge3d.models.vggt.heads.dpt_head import DPTHeadfrom 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 predictions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# 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 torchfrom .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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# 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 torchimport numpy as npimport 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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508"""Frozen VGGT feature extraction and four-layer DINO residual adapter."""
from __future__ import annotations
import mathfrom collections import OrderedDictfrom pathlib import Pathfrom typing import Dict, List, Mapping, Sequence, Tuple
import torchimport torch.nn as nnimport 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() )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Frozen coords64 VGGT backbone and its full-precision point/DPT head."""
from __future__ import annotations
import torchimport torch.nn as nn
from .vggt.heads.dpt_head import DPTHead, custom_interpolatefrom .vggt.heads.head_act import activate_headfrom .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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293"""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()}1234from .full_attn import *from .modules import *from .rope import *
123456789101112131415161718192021222324252627282930from 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 = debug123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146from typing import *import torchimport mathfrom . 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
@overloaddef 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. """ ...
@overloaddef 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. """ ...
@overloaddef 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Ffrom .full_attn import scaled_dot_product_attentionfrom .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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748from typing import *import torchimport 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 phases1234567891011121314151617181920212223242526272829303132import torchimport torch.nn as nnfrom .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 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566from . import configimport 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 Pylanceif __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
1234from .full_attn import *from .windowed_attn import *from .modules import *
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221from typing import *import torchfrom .. import VarLenTensorfrom .. import config
__all__ = [ 'sparse_scaled_dot_product_attention',]
@overloaddef 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. """ ...
@overloaddef 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. """ ...
@overloaddef 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. """ ...
@overloaddef 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. """ ...
@overloaddef 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. """ ...
@overloaddef 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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142from typing import *import torchimport torch.nn as nnimport torch.nn.functional as Ffrom .. import VarLenTensor, SparseTensorfrom .full_attn import sparse_scaled_dot_product_attentionfrom .windowed_attn import sparse_windowed_scaled_dot_product_self_attentionfrom .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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from typing import *import torchimport torch.nn as nnfrom ..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_embed123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196"""Packed Full-only routed cross-attention backed by FlashAttention varlen."""from __future__ import annotations
from typing import Dict
import torchimport torch.nn as nn
from ..basic import SparseTensorfrom .modules import SparseMultiHeadRMSNorm
try: from flash_attn import flash_attn_varlen_funcexcept Exception as exc: # pragma: no cover - validated at startup on production nodes flash_attn_varlen_func = None _FLASH_IMPORT_ERROR = excelse: _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)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191from typing import *import torchimport mathfrom .. import SparseTensorfrom .. 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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837from typing import *from fractions import Fractionimport torchfrom . 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]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546from typing import Literal
CONV = 'flex_gemm' DEBUG = FalseATTN = '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 = backenduniforge3d/__init__.pyDeleted-5
uniforge3d/configs/pipeline.jsonDeleted-714
uniforge3d/models/__init__.pyDeleted-24
uniforge3d/models/conditioning.pyDeleted-109
uniforge3d/models/dino.pyDeleted-63
uniforge3d/models/joint_dit_vggt_stage1.pyDeleted-383
uniforge3d/models/loaders.pyDeleted-200
uniforge3d/models/lora.pyDeleted-73
uniforge3d/models/sparse_structure_flow.pyDeleted-246
uniforge3d/models/structured_latent_flow.pyDeleted-369
uniforge3d/models/vaes/__init__.pyDeleted-1
uniforge3d/models/vaes/flexi_dual_grid.pyDeleted-67
uniforge3d/models/vaes/sparse_structure.pyDeleted-175
uniforge3d/models/vaes/sparse_unet.pyDeleted-384
uniforge3d/models/vggt/__init__.pyDeleted-3
uniforge3d/models/vggt/heads/camera_head.pyDeleted-150
uniforge3d/models/vggt/heads/dpt_head.pyDeleted-485
uniforge3d/models/vggt/heads/head_act.pyDeleted-126
uniforge3d/models/vggt/heads/utils.pyDeleted-110
uniforge3d/models/vggt/layers/__init__.pyDeleted-12
uniforge3d/models/vggt/layers/attention.pyDeleted-94
uniforge3d/models/vggt/layers/block.pyDeleted-135
uniforge3d/models/vggt/layers/layer_scale.pyDeleted-23
uniforge3d/models/vggt/layers/mlp.pyDeleted-41
uniforge3d/models/vggt/layers/patch_embed.pyDeleted-86
uniforge3d/models/vggt/layers/rope.pyDeleted-189
uniforge3d/models/vggt/layers/swiglu_ffn.pyDeleted-68
uniforge3d/models/vggt/layers/vision_transformer.pyDeleted-368
uniforge3d/models/vggt/models/aggregator.pyDeleted-330
uniforge3d/models/vggt/models/vggt.pyDeleted-64
uniforge3d/models/vggt/utils/pose_enc.pyDeleted-125
uniforge3d/models/vggt/utils/rotation.pyDeleted-133
uniforge3d/models/vggt_adapter.pyDeleted-508
uniforge3d/models/vggt_routed_features.pyDeleted-96
uniforge3d/models/view_router.pyDeleted-293
uniforge3d/modules/attention/__init__.pyDeleted-4
uniforge3d/modules/attention/config.pyDeleted-30
uniforge3d/modules/attention/full_attn.pyDeleted-146
uniforge3d/modules/attention/modules.pyDeleted-103
uniforge3d/modules/attention/rope.pyDeleted-48
uniforge3d/modules/norm.pyDeleted-32
uniforge3d/modules/sparse/__init__.pyDeleted-66
uniforge3d/modules/sparse/attention/__init__.pyDeleted-4
uniforge3d/modules/sparse/attention/full_attn.pyDeleted-221
uniforge3d/modules/sparse/attention/modules.pyDeleted-142
uniforge3d/modules/sparse/attention/rope.pyDeleted-58
uniforge3d/modules/sparse/attention/routed_full_only_flash.pyDeleted-196
uniforge3d/modules/sparse/attention/windowed_attn.pyDeleted-191
uniforge3d/modules/sparse/basic.pyDeleted-837
uniforge3d/modules/sparse/config.pyDeleted-46