diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..017234ec81433293e74758512332d630fc2207b9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.ckpt diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..a7266f8ed11e474fc23aec6549f7086783080897 --- /dev/null +++ b/app.py @@ -0,0 +1,63 @@ +import gradio as gr +import spaces +import torch +import hydra +import lightning as L +from einops import rearrange +from PIL import Image +from pathlib import Path + +# I tuoi import +from loomnet.utils import load_config +from inference import prepare_inputs + +DEVICE = "cuda" if torch.cuda.is_available() else "cpu" +OUTPUT_DIR = Path("outputs") +OUTPUT_DIR.mkdir(exist_ok=True) + +# Il modello viene caricato nella RAM dello spazio cloud all'avvio +cfg = load_config("configs/baseline.yaml", cli_args=[]) +model = hydra.utils.instantiate(cfg.system) +model.load_weights(cfg.resume) +model = model.to(DEVICE).eval() + +@spaces.GPU +def run_demo(image_path, elevation, seed): + if image_path is None: + return None, None + + L.seed_everything(int(seed), workers=True) + data = prepare_inputs(image_path, elevation, "ele30") + for k, v in data.items(): + data[k] = v.unsqueeze(0).to(DEVICE) + if k not in ["k_near_indices"]: data[k] = data[k].float() + + with torch.no_grad(): + images_pred = model._generate_images(data) + + gif_path = str(OUTPUT_DIR / "out.gif") + jpg_path = str(OUTPUT_DIR / "out.jpg") + + image_list = [Image.fromarray(img) for img in images_pred[0]] + image_list[0].save(gif_path, save_all=True, append_images=image_list[1:], duration=100, loop=0) + + full_image = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + Image.fromarray(full_image).save(jpg_path) + + return jpg_path, gif_path + +with gr.Blocks() as demo: + with gr.Row(): + with gr.Column(): + img_in = gr.Image(type="filepath", label="Immagine Input") + elevation_in = gr.Slider(-90, 90, value=12.0, label="Elevation") + seed_in = gr.Number(value=0, label="Seed") + btn = gr.Button("Genera") + with gr.Column(): + out_jpg = gr.Image(label="Viste Generate") + out_gif = gr.Image(label="GIF") + + btn.click(fn=run_demo, inputs=[img_in, elevation_in, seed_in], outputs=[out_jpg, out_gif]) + +if __name__ == "__main__": + demo.launch() \ No newline at end of file diff --git a/configs/baseline.yaml b/configs/baseline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12c63267e5d72eb464fffdbe7cde691c8f666e42 --- /dev/null +++ b/configs/baseline.yaml @@ -0,0 +1,125 @@ +name: loomnet_global +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "outputs" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: epoch=47-step=37544.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 1 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_v8.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_v8.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 64 #number of samples M per ray + num_weaving_layers_per_decoder_block: [3, 4, 6, 6] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 64 #the resolution of each splatted plane + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + do_global_rendering: False + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 370001 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 8 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_1_to_infinity.yaml b/configs/baseline_1_to_infinity.yaml new file mode 100644 index 0000000000000000000000000000000000000000..faf95aa0673546ec4cad769522724be38b30320b --- /dev/null +++ b/configs/baseline_1_to_infinity.yaml @@ -0,0 +1,125 @@ +name: loomnet_1_to_infinity_baseline_1 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet_1_to_infinity_baseline_1/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=49-step=67001.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 2 # 1 reference view + 32 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 2 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 2 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_1_to_infinity.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_1_to_infinity.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_1_to_infinity.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 16 #number of samples M per ray + num_weaving_layers_per_decoder_block: [3, 4, 6, 8] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 64 #the resolution of each splatted plane + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + use_positional_encoding: True + num_views_latent_space: 16 #num views for building the shared latent space + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 300000 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 4 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_for_ablation.yaml b/configs/baseline_for_ablation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..df8537b2dfc0c9aafc8d4f068768ca8809447cf7 --- /dev/null +++ b/configs/baseline_for_ablation.yaml @@ -0,0 +1,122 @@ +name: loomnet_v8_baseline_6 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet_v8_baseline_6/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=10-step=21186.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 2 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 2 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] #[60,67,74,81,88,95,4,9,14,19,24,31,38,45,52,59] #${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_v8.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_v8.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 16 #number of samples M per ray + num_weaving_layers_per_decoder_block: [3, 4, 6, 8] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 64 #the resolution of each splatted plane + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + use_positional_encoding: False + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 37001 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 4 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_for_test.yaml b/configs/baseline_for_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ba2669f6f4bda642324bf38341edfd381380ae1 --- /dev/null +++ b/configs/baseline_for_test.yaml @@ -0,0 +1,126 @@ +name: loomnet_v8_da-eliminare_per_paper +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet_v9/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=47-step=37544.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: [4, 9, 14, 19, 24, 31, 38, 45, 52, 59, 60, 67, 74, 81, 88, 95] #[4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + img_wh: [256, 256] + bg_color: white + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 2 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 2 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + use_geometric_loss: False + mv_model: + _target_: loomnet.models.mv_model_v8.MVModel + _partial_: true + cp_block_model: + # _target_: loomnet.models.extras.feature_aggregator.FeatureAggregator + # _partial_: true + # depth: 2 + # use_resnet: true + # use_fhw_attn: false + # pos_encs: ["abs"] # ["abs", "ref"] + _target_: loomnet.models.extras.feature_aggregator_v8.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + # n_heads_transformers: [16, 16, 16] #quante teste + # d_heads_transformers: [64, 64, 64] #la dimensione di ogni testa + n_heads_transformers: [16, 16, 16] #quante teste + d_heads_transformers: [32, 32, 32] #la dimensione di ogni testa + depths_transformers: [2, None, 2] + ambassadors_feature_grid_resolution: {4: 2, 8: 4, 16: 8, 32: 16} + number_nearby_hubs_per_projected_point: {4: 4, 8: 4, 16: 4, 32: 4} + num_latent_points: {4: 32, 8: 64, 16: 128, 32: 256} + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] + use_residual: false + render_options: + n_samples: 8 + lr: 1e-5 + cfg: 0.1 + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 360001 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 4 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_geometric_loss.yaml b/configs/baseline_geometric_loss.yaml new file mode 100644 index 0000000000000000000000000000000000000000..383390bd20d6c4f39c6cbd275f6055beac8e3196 --- /dev/null +++ b/configs/baseline_geometric_loss.yaml @@ -0,0 +1,148 @@ +name: loomnet_with_geometric_loss_point_matching_baseline_1 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet_with_geometric_loss_point_matching_baseline_1/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=1-step=7702.ckpt + + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 4 # our baseline uses 16 nearest views + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + img_wh: [256, 256] + bg_color: white + load_only_weights: #/raid/homes/giulio.federico/LoomNet/output_dir/loomnet_v9/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=47-step=37544.ckpt + + token_based_geometric_loss: + max_geometric_loss_weight: 0.1 + min_geometric_loss_weight: 0.005 + geometric_loss_scheduler: "cosine" + target_vggt_layers: [4,11,17,23] + + register_token_based_geometric_loss: + max_geometric_loss_weight: 0.1 + min_geometric_loss_weight: 0.005 + geometric_loss_scheduler: "cosine" + target_vggt_layers: [4,11,17,23] + + point_matching_geometric_loss: + k_near_views: ${extras.k_near_views} #for each view to check we will use extras.k_near_views-1 near views + num_points: 32 + num_views_to_check: 3 #how many random views to use to check consistency + + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: "random" + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #USA SEMPRE BATCH SIZE 1 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: "random" + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 2 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_for_geometric_loss.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_v8.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_v8.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 16 #number of samples M per ray + num_weaving_layers_per_decoder_block: [3, 4, 6, 8] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 64 #the resolution of each splatted plane + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + + #for geometric (vggt) loss + type_of_geometric_loss: 'point_matching_geometric_loss' #['token_based_geometric_loss', 'register_token_based_geometric_loss'] + use_vggt_gradient_checkpoint: True #If there are too many views or nearby views, it is better to use it to avoid going out of memory (even if it will be slower) + extras: ${extras} + + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 15000 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 3 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_global.yaml b/configs/baseline_global.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2b6bf7ac796e1c600dd1da53884d7beae20c3016 --- /dev/null +++ b/configs/baseline_global.yaml @@ -0,0 +1,125 @@ +name: loomnet_global +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: #/raid/homes/giulio.federico/LoomNet/output_dir/loomnet_v9/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=47-step=37544.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 1 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_global.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_v8.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_global.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 64 #number of samples M per ray + num_weaving_layers_per_decoder_block: [3, 4, 6, 12] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 128 #the resolution of each splatted plane + triplane_upsample_channel_dim: 32 + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + use_positional_encoding: True + + insert_stages: ["up"] + insert_up_layers: [3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 37001 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 4 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_triplane.yaml b/configs/baseline_triplane.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ea6f7ff89554c6c90cb4d8e321b414a010bb34ee --- /dev/null +++ b/configs/baseline_triplane.yaml @@ -0,0 +1,126 @@ +name: loomnet_triplane_4 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 2 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 6 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 1 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_triplane.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_triplane.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 48 #number of samples M per ray + num_weaving_layers_per_decoder_block: [4, 4, 5, 6] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [8, 8, 8, 16] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + #plane_channel_dim_after_upsample: 240 + splat_plane_resolutions: [64, 64, 64, 64] #the resolution of each splatted plane + latent_rendering_stages: [True, True, True, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + do_global_rendering: True + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] #[0, 1, 2, 3] + use_residual: true + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-3 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 946209 + check_val_every_n_epoch: 1 + log_every_n_steps: 50 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 16 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_triplane2.yaml b/configs/baseline_triplane2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..14e266f350a994ad6cbbf198d12fa3968795fb81 --- /dev/null +++ b/configs/baseline_triplane2.yaml @@ -0,0 +1,126 @@ +name: loomnet_triplane_4 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: #/4/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=7-step=7704.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 1 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_triplane.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_triplane.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 32 #number of samples M per ray + num_weaving_layers_per_decoder_block: [4, 4, 4, 4] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + #plane_channel_dim_after_upsample: 240 + splat_plane_resolutions: [64, 64, 64, 64] #the resolution of each splatted plane + latent_rendering_stages: [True, True, True, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + do_global_rendering: True + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] #[0, 1, 2, 3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 946209 + check_val_every_n_epoch: 1 + log_every_n_steps: 50 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 16 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_triplane3.yaml b/configs/baseline_triplane3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca8e4b7c0db345f1a3dd5b9242110ae0e9a3409e --- /dev/null +++ b/configs/baseline_triplane3.yaml @@ -0,0 +1,126 @@ +name: loomnet_triplane_4 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet_triplane_4/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=69-step=67410.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 1 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_triplane.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_triplane.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 32 #number of samples M per ray + num_weaving_layers_per_decoder_block: [4, 4, 4, 4] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + #plane_channel_dim_after_upsample: 240 + splat_plane_resolutions: [64, 64, 64, 64] #the resolution of each splatted plane + latent_rendering_stages: [True, True, True, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + do_global_rendering: True + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] #[0, 1, 2, 3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 946209 + check_val_every_n_epoch: 1 + log_every_n_steps: 50 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 16 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_triplane_with_3d_conv.yaml b/configs/baseline_triplane_with_3d_conv.yaml new file mode 100644 index 0000000000000000000000000000000000000000..26fa1e08e591a38adbe810d8ab2d89747a1a6d4d --- /dev/null +++ b/configs/baseline_triplane_with_3d_conv.yaml @@ -0,0 +1,126 @@ +name: loomnet_triplane_4 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 1 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_v8.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_triplane_with_3d_conv.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_triplane_with_3d_conv.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 48 #number of samples M per ray + num_weaving_layers_per_decoder_block: [4, 4, 5, 6] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [8, 8, 8, 16] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + #plane_channel_dim_after_upsample: 240 + splat_plane_resolutions: [64, 64, 64, 64] #the resolution of each splatted plane + latent_rendering_stages: [True, True, True, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + do_global_rendering: True + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] #[0, 1, 2, 3] + use_residual: true + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-3 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 946209 + check_val_every_n_epoch: 1 + log_every_n_steps: 50 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 16 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_with_distillation.yaml b/configs/baseline_with_distillation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dedc5c29250bde0f8e565e423a6b513dadd5fe0 --- /dev/null +++ b/configs/baseline_with_distillation.yaml @@ -0,0 +1,124 @@ +name: loomnet_with_distillation_3 +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet_v9/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=47-step=37544.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 17 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 2 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 2 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_with_distillation.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_with_distillation.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_with_distillation.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 16 #number of samples M per ray + num_weaving_layers_per_decoder_block: [3, 4, 6, 8] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 64 #the resolution of each splatted plane + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + use_positional_encoding: True + + insert_stages: ["mid", "up"] + insert_up_layers: [0, 1, 2, 3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 52545 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 4 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/baseline_with_projection.yaml b/configs/baseline_with_projection.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a4e1b43dfc98352cfc0afb11ba743f6742dffb8 --- /dev/null +++ b/configs/baseline_with_projection.yaml @@ -0,0 +1,126 @@ +name: loomnet +tags: ["lvis", "stable-zero123", "n16f16", "pabs"] +version: loomnet_v2-stable-zero123-n16f16-pabs +description: "Baseline config for loomnet. Trained on LVIS dataset with 16 fixed rendered views in a fixed elevation of 30. Epipolar constrained among 16 nearest views. Use absolute elevation for stable zero123." +output_dir: "/raid/homes/giulio.federico/LoomNet/output_dir/${name}" + +#NB: if you want to resume all the training states, use 'resume'. If you want to load only weights, use 'extras.load_only_weights' +resume: /raid/homes/giulio.federico/LoomNet/output_dir/loomnet/loomnet_v2-stable-zero123-n16f16-pabs/checkpoints/epoch=60-step=39162.ckpt + +extras: + # for dataset + # num_views: 17 # 1 reference view + 16 sampling views + # k_near_views: 16 # our baseline uses 16 nearest views + # sample_views_mode: [4, 10, 16, 22, 28, 34, 40, 46, 52, 58, 64, 70, 76, 82, 88, 94] # view indexs for sampling + num_views: 2 # 1 reference view + 16 sampling views + k_near_views: 1 # our baseline uses 16 nearest views + sample_views_mode: "random" + img_wh: [256, 256] + bg_color: white + load_only_weights: + +data: + _target_: loomnet.data.multiview.MultiViewDataModule + train_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "training" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_train.txt + use_abs_elevation: true # for stable zero123 + train_batch_size: 1 #15 + val_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "validation" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: "random" #64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_val.txt + use_abs_elevation: true # for stable zero123 + max_samples_per_category: 1 + val_batch_size: 2 # [NB]: during validation we will use double val_batch_size due to cfg + test_dataset: + _target_: loomnet.data.multiview.MultiViewDataset + type_of_dataset: "testing" + root_dir: /raid/homes/giulio.federico/LoomNet/dataset/google_scanned_objects_multiview_evaluation + img_wh: ${extras.img_wh} + bg_color: ${extras.bg_color} + num_views: ${extras.num_views} + k_near_views: ${extras.k_near_views} + ref_view_mode: 64 + sample_views_mode: ${extras.sample_views_mode} + caption_path: /raid/homes/giulio.federico/LoomNet/dataset/objaverse_lvis_multiview/caption_test.txt + use_abs_elevation: true + test_batch_size: 1 + num_workers: 16 #64 + pin_memory: true + +system: + _target_: loomnet.systems.i2mv_system_with_projection.I2MVSystem + base_model_id: "ashawkey/stable-zero123-diffusers" + mv_model: + _target_: loomnet.models.mv_model_v8.MVModel + _partial_: true + cp_block_model: + _target_: loomnet.models.extras.feature_aggregator_with_projection.FeatureAggregator + _partial_: true + num_views: ${extras.num_views} + n_samples_per_ray: 64 #number of samples M per ray + num_weaving_layers_per_decoder_block: [4, 4, 6, 8] #how many times the weaving stages is repeated for each decoder layer + num_weaving_heads_per_decoder_block: [4, 8, 8, 8] + plane_channel_dim: ${system.mv_model.plane_channel_dim} + plane_resolution: ${system.mv_model.plane_resolution} + splat_plane_resolution: 128 #the resolution of each splatted plane + triplane_upsample_channel_dim: 32 + latent_rendering_stages: [False, False, False, True] #in what stage to use latent rendering + do_local_bilinear_splatting: True + do_global_rendering: True + use_positional_encoding: True + + insert_stages: ["up"] + insert_up_layers: [3] + use_residual: false + plane_resolution: 32 #the resolution of each latent plane (of latent triplane) + plane_channel_dim: 512 #the number of channels of each latent plane + lr: 1e-5 + cfg: 0.1 + tv_weight: 5e-4 #loss weight for triplane + report_to: none #TODO --> wandn + +trainer: + _target_: lightning.pytorch.trainer.Trainer + default_root_dir: ${output_dir} + max_steps: 370001 + check_val_every_n_epoch: 1 + log_every_n_steps: 5 + num_sanity_val_steps: 0 + enable_progress_bar: true + strategy: ddp_find_unused_parameters_true + accelerator: gpu + precision: 16-mixed # mixed precision for extra speed-up + accumulate_grad_batches: 4 + gradient_clip_val: 1.0 + +callbacks: + model_checkpoint: + _target_: lightning.pytorch.callbacks.ModelCheckpoint + save_top_k: 1 + #every_n_train_steps: 10000 + #every_n_epochs: 12 + dirpath: "${output_dir}/${version}/checkpoints" + +# logger: +# wandb: +# _target_: lightning.pytorch.loggers.wandb.WandbLogger +# project: "${name}" +# save_dir: ${output_dir} +# name: "${version}" diff --git a/configs/loomnet_global2.log b/configs/loomnet_global2.log new file mode 100644 index 0000000000000000000000000000000000000000..bebec930e4b9d8d01c5c7ecd43c216407d2331ef --- /dev/null +++ b/configs/loomnet_global2.log @@ -0,0 +1,2 @@ +nohup: ignoring input +nohup: failed to run command 'torchrun': No such file or directory diff --git a/configs/loomnet_triplane.yaml.save b/configs/loomnet_triplane.yaml.save new file mode 100644 index 0000000000000000000000000000000000000000..456b807ca50bbe111ae37ba31fa758d731b92090 --- /dev/null +++ b/configs/loomnet_triplane.yaml.save @@ -0,0 +1 @@ +^x diff --git a/configs/nerf.yaml b/configs/nerf.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1db0ab641a0cfd69177725ca6a36122815aa762c --- /dev/null +++ b/configs/nerf.yaml @@ -0,0 +1,26 @@ +model: + base_lr: 1.0e-2 + target: renderer.renderer.RendererTrainer + params: + total_steps: 2000 + warm_up_steps: 100 + train_batch_num: 40960 + test_batch_num: 40960 + renderer: ngp + cube_bound: 0.6 + use_mask: true + lambda_rgb_loss: 0.5 + lambda_mask_loss: 10.0 + meta_camera_path: "/raid/homes/giulio.federico/LoomNet/src/meta/fixed_30_meta.pkl" + +data: + target: renderer.dummy_dataset.DummyDataset + params: {} + +callbacks: + save_interval: 5000 + +trainer: + val_check_interval: 500 + max_steps: 2000 + diff --git a/configs/neus.yaml b/configs/neus.yaml new file mode 100644 index 0000000000000000000000000000000000000000..143437aa922b742ffae19a5303db107252b5ad69 --- /dev/null +++ b/configs/neus.yaml @@ -0,0 +1,27 @@ +model: + base_lr: 5.0e-4 + target: renderer.renderer.RendererTrainer + params: + total_steps: 2000 + warm_up_steps: 100 + train_batch_num: 3584 + train_batch_fg_num: 512 + test_batch_num: 4096 + use_mask: true + lambda_rgb_loss: 0.5 + lambda_mask_loss: 1.0 + lambda_eikonal_loss: 0.1 + use_warm_up: true + meta_camera_path: /raid/homes/giulio.federico/LoomNet/competitors/SyncDreamer/meta_info/camera-16.pkl + +data: + target: renderer.dummy_dataset.DummyDataset + params: {} + +callbacks: + save_interval: 500 + +trainer: + val_check_interval: 500 + max_steps: 2000 + diff --git a/inference.py b/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..04e2f4907fdacc8318ce2e79a758244f8c1b8533 --- /dev/null +++ b/inference.py @@ -0,0 +1,141 @@ +import argparse +import json +import math +import os +from pathlib import Path +from typing import List + +import hydra +import lightning as L +import numpy as np +import torch +from einops import rearrange +from lightning import LightningModule +from PIL import Image + +from loomnet.utils import load_config +from loomnet.utils.media import get_bg_color, load_image +from loomnet.utils.pose import get_k_near_views + +WIDTH, HEIGHT = 256, 256 +K_NEAR_VIEWS = 16 + + +def prepare_inputs(input_img: str, input_elevation: float, sample_views_mode: str): + bg_color = get_bg_color("white") + input_img = load_image( + input_img, (WIDTH, HEIGHT), bg_color, return_type="pt" + ).permute(2, 0, 1) + + meta_fp = f"meta_info/transforms_{sample_views_mode}.json" + with open(meta_fp, "r") as f: + meta = json.load(f) + + # Camera intrinsics + fov = meta["camera_angle_x"] + focal_length = 1 / (2 * np.tan(0.5 * fov)) + intrinsics_4x4 = torch.tensor( + [ + [focal_length, 0, 0.5, 0], + [0, focal_length, 0.5, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ] + ) + + # Camera extrinsics + num_views = len(meta["frames"]) + elevations, azimuths, c2w_matrixs = [], [], [] + for frame in meta["frames"]: + elevations.append(frame["elevation"]) + azimuths.append(frame["azimuth"]) + c2w_matrixs.append(frame["transform_matrix"]) + elevations = torch.tensor(elevations) # (N,) + azimuths = torch.tensor(azimuths) # (N,) + c2w_matrixs = torch.tensor(c2w_matrixs) # (N, 4, 4) + c2w_matrixs[:, :, 1:3] *= -1 # blender to opencv + + # concat intrinsics and extrinsics + intrinsics_4x4 = ( + intrinsics_4x4.unsqueeze(0).repeat(num_views, 1, 1).reshape(num_views, 16) + ) + _c2w_matrixs = c2w_matrixs.reshape(num_views, 16) + camera_params = torch.cat([intrinsics_4x4, _c2w_matrixs], dim=1) + + # find nearest views + k_near_indices = get_k_near_views(elevations, azimuths, K_NEAR_VIEWS, num_views) + + # normalize elevations and azimuths + input_elevation = torch.tensor([input_elevation / 180 * math.pi]) + d_elevations = (elevations - input_elevation).reshape(-1, 1) + d_azimuths = azimuths.reshape(-1, 1) % (2 * math.pi) + + #distances = torch.zeros_like(d_elevations) + distances = torch.tensor(input_elevation).repeat(num_views).reshape(-1, 1) + + return { + "image_0": input_img, + "elevations": d_elevations, + "azimuths": d_azimuths, + "distances": distances, + "c2w_matrixs": c2w_matrixs, + "cameras": camera_params, + "k_near_indices": k_near_indices, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=str, default="configs/baseline.yaml") + parser.add_argument("--input_img", type=str, default="/raid/homes/giulio.federico/LoomNet/da_eliminare/render_0065.png") + parser.add_argument("--output_dir", type=str, default="/raid/homes/giulio.federico/LoomNet/output_dir") + parser.add_argument("--elevation", type=float, default=0.0) + parser.add_argument( + "--sample_views_mode", type=str, choices=["ele30", "ele40"], default="ele30" + ) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--device", type=str, default="cuda") + args, extras = parser.parse_known_args() + + output_dir = Path(args.output_dir) + output_dir.mkdir(exist_ok=True, parents=True) + + L.seed_everything(args.seed, workers=True) + cfg = load_config(args.config, cli_args=extras) + + # prepare model + model: LightningModule = hydra.utils.instantiate(cfg.system) + model.load_weights(cfg.resume) + model = model.to(args.device).eval() + print(f"Loaded model from {cfg.resume}") + + # prepare data + data = prepare_inputs(args.input_img, args.elevation, args.sample_views_mode) + for k, v in data.items(): + data[k] = v.unsqueeze(0).to(args.device) + if k not in ["k_near_indices"]: + data[k] = data[k].float() + + # generate + with torch.no_grad(): + images_pred = model._generate_images(data) + + # save + image_base_name = os.path.basename(args.input_img).split(".")[0] + image_list = [] + for image in images_pred[0]: + image_list.append(Image.fromarray(image)) + image_list[0].save( + output_dir / f"{image_base_name}.gif", + save_all=True, + append_images=image_list[1:], + duration=100, + loop=0, + ) + + full_image = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + Image.fromarray(full_image).save(output_dir / f"{image_base_name}.jpg") + + +if __name__ == "__main__": + main() diff --git a/loomnet/data/__init__.py b/loomnet/data/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loomnet/data/__pycache__/__init__.cpython-311.pyc b/loomnet/data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dadf5093659060e4460d7dc1821229a32d782b95 Binary files /dev/null and b/loomnet/data/__pycache__/__init__.cpython-311.pyc differ diff --git a/loomnet/data/__pycache__/multiview.cpython-311.pyc b/loomnet/data/__pycache__/multiview.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1252c0744a6b578f3f82b99c0daa64ca29381e6 Binary files /dev/null and b/loomnet/data/__pycache__/multiview.cpython-311.pyc differ diff --git a/loomnet/data/__pycache__/multiview_infinity.cpython-311.pyc b/loomnet/data/__pycache__/multiview_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ced41c221ac9b5e83bea93752f50005720be49e Binary files /dev/null and b/loomnet/data/__pycache__/multiview_infinity.cpython-311.pyc differ diff --git a/loomnet/data/multiview.py b/loomnet/data/multiview.py new file mode 100644 index 0000000000000000000000000000000000000000..9c65c52d4434f90507843c361760c0bbc829c19e --- /dev/null +++ b/loomnet/data/multiview.py @@ -0,0 +1,375 @@ +import json +import math +import os +from os.path import join as osp +from typing import Any, Dict, List, Optional, Tuple, Union +import random +import numpy as np +import torch +from lightning import LightningDataModule +from omegaconf import DictConfig, ListConfig +from PIL import Image +from torch.utils.data import DataLoader, Dataset + + +class MultiViewDataset(Dataset): + def __init__( + self, + type_of_dataset: str, + root_dir: str, + num_views: int, + bg_color: str, + img_wh: Tuple[int, int], + caption_path: str, + ref_view_mode: Union[str, List] = "random", + sample_views_mode: Union[str, List] = "random", + k_near_views: Optional[int] = None, + max_samples_per_category: Optional[int] = None, + use_abs_elevation: bool = False, + seed = 0 + ): + #data = [] + + # # Loop per ogni cartella di categoria + # for category in os.listdir(root_dir): + # category_path = os.path.join(root_dir, category) + + # if os.path.isdir(category_path): + + # uids = os.listdir(category_path) + # #se validazione, prendiamo per semplicità solo due campioni + # if max_samples_per_category is not None: + # random.seed(seed) + # uids = random.sample(uids, min(max_samples_per_category, len(uids))) + # for uid in uids: + + # uid_path = os.path.join(root_dir, category, uid) + # obj_data = {"obj_dir": uid_path, "caption": ""} + + # data.append(obj_data) + + data = [] + # Loop per ogni cartella di categoria + for category in os.listdir(root_dir): + category_path = os.path.join(root_dir, category) + + if os.path.isdir(category_path): + + uids = [f for f in os.listdir(category_path) if not os.path.isfile(os.path.join(category_path, f))] #os.listdir(category_path) + + if len(uids)!=0: + for uid in uids: + + uid_path = os.path.join(root_dir, category, uid) + obj_data = {"obj_dir": uid_path, "caption": ""} + + data.append(obj_data) + else: + uid_path = os.path.join(root_dir, category) + obj_data = {"obj_dir": uid_path, "caption": ""} + + data.append(obj_data) + + + #da eliminare (per velocità prendo solo i primi 8) + if type_of_dataset=="validation": + random.seed(3) # esempio: random.seed(42) + indices = random.sample(range(len(data)), 16) # prendo 96 indici casuali unici da 0 a 999 + data = [data[i] for i in indices] + + #data = data[:50] #TODO ELIMINA + + self.data = data + self.num_views = num_views + self.bg_color = bg_color + self.img_wh = img_wh + self.ref_view_mode = ref_view_mode + self.sample_views_mode = sample_views_mode + self.k_near_views = k_near_views if k_near_views else num_views + self.use_abs_elevation = use_abs_elevation + + def get_bg_color(self, bg_color): + if bg_color == "white": + bg_color = np.array([1.0, 1.0, 1.0], dtype=np.float32) + elif bg_color == "black": + bg_color = np.array([0.0, 0.0, 0.0], dtype=np.float32) + elif bg_color == "gray": + bg_color = np.array([0.5, 0.5, 0.5], dtype=np.float32) + elif bg_color == "random": + bg_color = np.random.rand(3) + elif bg_color == "random_gray": + bg_color = np.random.rand(1) * 0.5 + 0.3 + bg_color = np.array([bg_color] * 3, dtype=np.float32) + elif isinstance(bg_color, float): + bg_color = np.array([bg_color] * 3, dtype=np.float32) + else: + raise NotImplementedError + return bg_color + + def load_image(self, img_path, bg_color, rescale=True, return_type="np"): + # not using cv2 as may load in uint16 format + # img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) # [0, 255] + # img = cv2.resize(img, self.img_wh, interpolation=cv2.INTER_CUBIC) + # pil always returns uint8 + img = np.array(Image.open(img_path).resize(self.img_wh)) + img = img.astype(np.float32) / 255.0 # [0, 1] + + if img.shape[-1] == 4: + alpha = img[..., 3:4] + img = img[..., :3] * alpha + bg_color * (1 - alpha) + + if rescale: + img = img * 2.0 - 1.0 # to -1 ~ 1 + + if return_type == "np": + pass + elif return_type == "pt": + img = torch.from_numpy(img) + else: + raise NotImplementedError + + return img + + def get_k_near_views(self, elevations, azimuths, k_near_views, num_views): + views = torch.cat((elevations.unsqueeze(1), azimuths.unsqueeze(1)), dim=1) + distances = torch.cdist(views, views) + torch.fill_(distances.diagonal(), 0.0) + k_nearest_indices = torch.topk(distances, k_near_views, largest=False).indices + + return k_nearest_indices + + def __len__(self): + return len(self.data) + + def check_view_validaty(self, path_img): + img = np.array(Image.open(os.path.join(path_img))) + + #check if transparent + alpha = img[..., 3] + is_fully_transparent = np.all(alpha == 0) + + return not(is_fully_transparent) + + def __getitem__(self, index): + #{'obj_dir': path to folder uid, 'caption': ""} + sample = self.data[index] + obj_dir = sample["obj_dir"] + with open(osp(obj_dir, "meta.json"), "r") as f: + meta = json.load(f) + + # no use + caption = sample["caption"] + + # camera intrinsics + fov = meta["camera_angle_x"] + focal_length = 0.5 * 1 / np.tan(0.5 * fov) # FIXME: hard-code + intrinsics = np.array( + [ + [focal_length, 0, 0.5], + [0, focal_length, 0.5], + [0, 0, 1], + ], + dtype=np.float32, + ) + intrinsics = torch.from_numpy(intrinsics) + intrinsics_4x4 = torch.zeros(4, 4) + intrinsics_4x4[:3, :3] = intrinsics + intrinsics_4x4[3, 3] = 1.0 + + # sample or select ref view ids + num_views_all = len(meta["locations"]) + if self.ref_view_mode == "random": + check = False + c = 0 + while not(check): + ref_view_id = np.random.randint(num_views_all) + #chech if ref view is not transparent + check = self.check_view_validaty(os.path.join(obj_dir, meta["locations"][ref_view_id]["frames"][0]["name"])) + c=c+1 + if c == self.num_views: #DA ELIMINARE + print(f"The file at {obj_dir} directory do not contain any valid image....") + + elif isinstance(self.ref_view_mode, int): + ref_view_id = self.ref_view_mode + else: + raise NotImplementedError + + # sample or select view ids in a mode + num_views_all = len(meta["locations"]) + if self.sample_views_mode == "random": + view_ids = np.random.choice( + num_views_all, self.num_views - 1, replace=False + ) + elif isinstance(self.sample_views_mode, list) or isinstance( + self.sample_views_mode, ListConfig + ): + assert len(self.sample_views_mode) == self.num_views - 1, "Invalid view_ids" + view_ids = self.sample_views_mode + else: + raise NotImplementedError + view_ids = np.insert(view_ids, 0, ref_view_id) + locations = [meta["locations"][i] for i in view_ids] + + # load images, elevations, azimuths, c2w_matrixs + bg_color = self.get_bg_color(self.bg_color) + img_paths, img_tensors, elevations, azimuths, c2w_matrixs = [], [], [], [], [] + for loc in locations: + img_path = osp(obj_dir, loc["frames"][0]["name"]) + img = self.load_image(img_path, bg_color, return_type="pt").permute(2, 0, 1) + img_tensors.append(img) + img_paths.append(img_path) + elevations.append(loc["elevation"]) + azimuths.append(loc["azimuth"]) + c2w_matrixs.append(loc["transform_matrix"]) + + # concat and stack + img_tensors = torch.stack(img_tensors, dim=0).float() # (Nv, 3, H, W) + elevations = torch.tensor(elevations).float() # (Nv,) + azimuths = torch.tensor(azimuths).float() # (Nv,) + c2w_matrixs = torch.tensor(c2w_matrixs).float() # (Nv, 4, 4) + + # blender to opencv + c2w_matrixs[:, :, 1:3] *= -1 + + intrinsics_matrixs = intrinsics.unsqueeze(0).repeat( + self.num_views, 1, 1 + ) # (Nv, 3, 3) + intrinsics_matrixs_4x4 = intrinsics_4x4.unsqueeze(0).repeat( + self.num_views, 1, 1 + ) # (Nv, 4, 4) + + # flatten intrinsics_matrixs_4x4 and c2w_matrixs to (Nv, 16), and concat them + intrinsics_matrixs_4x4 = intrinsics_matrixs_4x4.reshape(self.num_views, 16) + c2w_matrixs = c2w_matrixs.reshape(self.num_views, 16) + camera_params = torch.cat((intrinsics_matrixs_4x4, c2w_matrixs), dim=1) + c2w_matrixs = c2w_matrixs.reshape(self.num_views, 4, 4) + + # find nearest views + if self.k_near_views > self.num_views: + raise ValueError("k_near_views should be no larger than num_views") + else: + k_near_indices = self.get_k_near_views( + elevations[1:], azimuths[1:], self.k_near_views, self.num_views - 1 + ) # NOTE: we use the 1st view as the reference view + d_elevations = (elevations - elevations[0:1]).reshape(-1, 1) + d_azimuths = (azimuths - azimuths[0:1]).reshape(-1, 1) % (2 * math.pi) + + if self.use_abs_elevation: # stable zero123 use abs_elevation as distance input + distances = elevations[0:1].repeat(self.num_views).reshape(-1, 1) + else: + distances = torch.zeros_like(d_elevations) + + return { + "view_ids": torch.tensor(view_ids), + "images": img_tensors[1:], + "image_0": img_tensors[0], + "elevations": d_elevations[1:], + "azimuths": d_azimuths[1:], + "distances": distances[1:], + "c2w_matrixs": c2w_matrixs[1:], + "intrinsics_matrixs": intrinsics_matrixs[1:], + "cameras": camera_params[1:], + "caption": caption, + "k_near_indices": k_near_indices, + "obj_dir": obj_dir.split('/')[-1] + } + + +class MultiViewDataModule(LightningDataModule): + def __init__( + self, + train_dataset: Dataset[Any], + val_dataset: Dataset[Any], + test_dataset: Dataset[Any], + train_batch_size: int = 1, + val_batch_size: int = 1, + test_batch_size: int = 1, + num_workers: Optional[int] = None, + pin_memory: bool = True, + ): + super().__init__() + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False) + + self.data_train = train_dataset + self.data_val = val_dataset + self.data_test = test_dataset + + self.num_workers = num_workers if num_workers else train_batch_size * 2 + + def prepare_data(self) -> None: + # TODO: check if data is available + pass + + def _dataloader( + self, dataset: Dataset, batch_size: int, shuffle: bool + ) -> DataLoader[Any]: + return DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=self.num_workers, + pin_memory=self.hparams.pin_memory, + ) + + def train_dataloader(self) -> DataLoader[Any]: + return DataLoader( + self.data_train, + batch_size=self.hparams.train_batch_size, + shuffle=True, + num_workers=self.num_workers, + pin_memory=self.hparams.pin_memory, + ) + + def val_dataloader(self) -> DataLoader[Any]: + # support multiple validation datasets + if isinstance(self.data_val, ListConfig): + return [ + self._dataloader(dataset, self.hparams.val_batch_size, False) + for dataset in self.data_val + ] + elif isinstance(self.data_val, DictConfig): + return [ + self._dataloader(dataset, self.hparams.val_batch_size, False) + for _, dataset in self.data_val.items() + ] + else: + return self._dataloader(self.data_val, self.hparams.val_batch_size, False) + + def test_dataloader(self) -> DataLoader[Any]: + # support multiple test datasets + if isinstance(self.data_test, ListConfig): + return [ + self._dataloader(dataset, self.hparams.test_batch_size, False) + for dataset in self.data_test + ] + elif isinstance(self.data_test, DictConfig): + return [ + self._dataloader(dataset, self.hparams.test_batch_size, False) + for _, dataset in self.data_test.items() + ] + else: + return self._dataloader(self.data_test, self.hparams.test_batch_size, False) + + +if __name__ == "__main__": + from torchvision.utils import save_image + + dataset = MultiViewDataset( + root_dir="/mnt/pfs/data/render_lvis_hzh", + num_views=17, + k_near_views=4, + bg_color="white", + img_wh=(256, 256), + ref_view_mode=2, + sample_views_mode="random", + caption_path="data/render_lvis_hzh/caption_train.txt", + use_abs_elevation=True, + ) + + sample = dataset[0] + print(sample["view_ids"]) + save_image((sample["image_0"] + 1.0) / 2, "temp_0.jpg", nrow=1, value_range=(0, 1)) + save_image((sample["images"] + 1.0) / 2, "temp.jpg", nrow=8, value_range=(0, 1)) diff --git a/loomnet/data/multiview_infinity.py b/loomnet/data/multiview_infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..0065fe7641eb68c0b43147d932d52a76fdf3ffee --- /dev/null +++ b/loomnet/data/multiview_infinity.py @@ -0,0 +1,410 @@ +import json +import math +import os +from os.path import join as osp +from typing import Any, Dict, List, Optional, Tuple, Union +import random +import numpy as np +import torch +from lightning import LightningDataModule +from omegaconf import DictConfig, ListConfig +from PIL import Image +from torch.utils.data import DataLoader, Dataset + + +class MultiViewDataset(Dataset): + def __init__( + self, + type_of_dataset: str, + root_dir: str, + num_views: int, + num_derived_views: int, + bg_color: str, + img_wh: Tuple[int, int], + caption_path: str, + ref_view_mode: Union[str, List] = "random", + sample_views_mode: Union[str, List] = "random", + sample_derived_views_mode: Union[str, List] = "random", + k_near_views: Optional[int] = None, + max_samples_per_category: Optional[int] = None, + use_abs_elevation: bool = False, + seed = 0 + ): + #data = [] + + # # Loop per ogni cartella di categoria + # for category in os.listdir(root_dir): + # category_path = os.path.join(root_dir, category) + + # if os.path.isdir(category_path): + + # uids = os.listdir(category_path) + # #se validazione, prendiamo per semplicità solo due campioni + # if max_samples_per_category is not None: + # random.seed(seed) + # uids = random.sample(uids, min(max_samples_per_category, len(uids))) + # for uid in uids: + + # uid_path = os.path.join(root_dir, category, uid) + # obj_data = {"obj_dir": uid_path, "caption": ""} + + # data.append(obj_data) + + data = [] + # Loop per ogni cartella di categoria + for category in os.listdir(root_dir): + category_path = os.path.join(root_dir, category) + + if os.path.isdir(category_path): + + uids = [f for f in os.listdir(category_path) if not os.path.isfile(os.path.join(category_path, f))] #os.listdir(category_path) + + if len(uids)!=0: + for uid in uids: + + uid_path = os.path.join(root_dir, category, uid) + obj_data = {"obj_dir": uid_path, "caption": ""} + + data.append(obj_data) + else: + uid_path = os.path.join(root_dir, category) + obj_data = {"obj_dir": uid_path, "caption": ""} + + data.append(obj_data) + + + #da eliminare (per velocità prendo solo i primi 8) + if type_of_dataset=="validation": + data = data[:144] + + + self.data = data + self.num_views = num_views + self.num_derived_views = num_derived_views + self.bg_color = bg_color + self.img_wh = img_wh + self.ref_view_mode = ref_view_mode + self.sample_views_mode = sample_views_mode + self.sample_derived_views_mode = sample_derived_views_mode + self.k_near_views = k_near_views if k_near_views else num_views + self.use_abs_elevation = use_abs_elevation + + def get_bg_color(self, bg_color): + if bg_color == "white": + bg_color = np.array([1.0, 1.0, 1.0], dtype=np.float32) + elif bg_color == "black": + bg_color = np.array([0.0, 0.0, 0.0], dtype=np.float32) + elif bg_color == "gray": + bg_color = np.array([0.5, 0.5, 0.5], dtype=np.float32) + elif bg_color == "random": + bg_color = np.random.rand(3) + elif bg_color == "random_gray": + bg_color = np.random.rand(1) * 0.5 + 0.3 + bg_color = np.array([bg_color] * 3, dtype=np.float32) + elif isinstance(bg_color, float): + bg_color = np.array([bg_color] * 3, dtype=np.float32) + else: + raise NotImplementedError + return bg_color + + def load_image(self, img_path, bg_color, rescale=True, return_type="np"): + # not using cv2 as may load in uint16 format + # img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) # [0, 255] + # img = cv2.resize(img, self.img_wh, interpolation=cv2.INTER_CUBIC) + # pil always returns uint8 + img = np.array(Image.open(img_path).resize(self.img_wh)) + img = img.astype(np.float32) / 255.0 # [0, 1] + + if img.shape[-1] == 4: + alpha = img[..., 3:4] + img = img[..., :3] * alpha + bg_color * (1 - alpha) + + if rescale: + img = img * 2.0 - 1.0 # to -1 ~ 1 + + if return_type == "np": + pass + elif return_type == "pt": + img = torch.from_numpy(img) + else: + raise NotImplementedError + + return img + + def get_k_near_anchors(self, elevations, azimuths, k_near_views, num_views, exclude_ids=None): + views = torch.cat((elevations.unsqueeze(1), azimuths.unsqueeze(1)), dim=1) + distances = torch.cdist(views, views) + + # Imposta la diagonale a inf per non contare sé stessi + distances.fill_diagonal_(float('inf')) + + if exclude_ids is not None: + # Esclude gli ID impostando la distanza a inf + distances[:, exclude_ids] = float('inf') + + #escludi le ancore + distances = distances[num_views:] + + k_nearest_indices = torch.topk(distances, k_near_views, largest=False).indices + + return k_nearest_indices + + + def __len__(self): + return len(self.data) + + def check_view_validaty(self, path_img): + img = np.array(Image.open(os.path.join(path_img))) + + #check if transparent + alpha = img[..., 3] + is_fully_transparent = np.all(alpha == 0) + + return not(is_fully_transparent) + + def __getitem__(self, index): + #{'obj_dir': path to folder uid, 'caption': ""} + sample = self.data[index] + obj_dir = sample["obj_dir"] + with open(osp(obj_dir, "meta.json"), "r") as f: + meta = json.load(f) + + # no use + caption = sample["caption"] + + # camera intrinsics + fov = meta["camera_angle_x"] + focal_length = 0.5 * 1 / np.tan(0.5 * fov) # FIXME: hard-code + intrinsics = np.array( + [ + [focal_length, 0, 0.5], + [0, focal_length, 0.5], + [0, 0, 1], + ], + dtype=np.float32, + ) + intrinsics = torch.from_numpy(intrinsics) + intrinsics_4x4 = torch.zeros(4, 4) + intrinsics_4x4[:3, :3] = intrinsics + intrinsics_4x4[3, 3] = 1.0 + + # sample or select ref view ids + num_views_all = len(meta["locations"]) + if self.ref_view_mode == "random": + check = False + c = 0 + while not(check): + ref_view_id = np.random.randint(num_views_all) + #chech if ref view is not transparent + check = self.check_view_validaty(os.path.join(obj_dir, meta["locations"][ref_view_id]["frames"][0]["name"])) + c=c+1 + if c == self.num_views: #DA ELIMINARE + print(f"The file at {obj_dir} directory do not contain any valid image....") + + elif isinstance(self.ref_view_mode, int): + ref_view_id = self.ref_view_mode + else: + raise NotImplementedError + + # sample or select anchor view ids + num_views_all = len(meta["locations"]) + if self.sample_views_mode == "random": + view_ids = np.random.choice( + num_views_all, self.num_views - 1, replace=False + ) + elif isinstance(self.sample_views_mode, list) or isinstance( + self.sample_views_mode, ListConfig + ): + assert len(self.sample_views_mode) == self.num_views - 1, "Invalid view_ids" + view_ids = self.sample_views_mode + else: + raise NotImplementedError + + + # sample or select derived view ids + if self.sample_derived_views_mode == "random": + derived_view_ids = np.random.choice( + num_views_all, self.num_derived_views, replace=False + ) + elif isinstance(self.sample_derived_views_mode, list) or isinstance( + self.sample_derived_views_mode, ListConfig + ): + derived_view_ids = self.sample_derived_views_mode + else: + raise NotImplementedError + + + + #insert reference view in the first position + view_ids = np.insert(view_ids, 0, ref_view_id) + #insert derived views in the last positions + view_ids = np.insert(view_ids, self.num_views, derived_view_ids) + locations = [meta["locations"][i] for i in view_ids] + + # load images, elevations, azimuths, c2w_matrixs + bg_color = self.get_bg_color(self.bg_color) + img_paths, img_tensors, elevations, azimuths, c2w_matrixs = [], [], [], [], [] + for loc in locations: + img_path = osp(obj_dir, loc["frames"][0]["name"]) + img = self.load_image(img_path, bg_color, return_type="pt").permute(2, 0, 1) + img_tensors.append(img) + img_paths.append(img_path) + elevations.append(loc["elevation"]) + azimuths.append(loc["azimuth"]) + c2w_matrixs.append(loc["transform_matrix"]) + + # concat and stack + img_tensors = torch.stack(img_tensors, dim=0).float() # (Nv, 3, H, W) + elevations = torch.tensor(elevations).float() # (Nv,) + azimuths = torch.tensor(azimuths).float() # (Nv,) + c2w_matrixs = torch.tensor(c2w_matrixs).float() # (Nv, 4, 4) + + # blender to opencv + c2w_matrixs[:, :, 1:3] *= -1 + + intrinsics_matrixs = intrinsics.unsqueeze(0).repeat( + self.num_views + self.num_derived_views, 1, 1 + ) # (Nv, 3, 3) + intrinsics_matrixs_4x4 = intrinsics_4x4.unsqueeze(0).repeat( + self.num_views + self.num_derived_views, 1, 1 + ) # (Nv, 4, 4) + + # flatten intrinsics_matrixs_4x4 and c2w_matrixs to (Nv, 16), and concat them + intrinsics_matrixs_4x4 = intrinsics_matrixs_4x4.reshape(self.num_views + self.num_derived_views, 16) + c2w_matrixs = c2w_matrixs.reshape(self.num_views + self.num_derived_views, 16) + camera_params = torch.cat((intrinsics_matrixs_4x4, c2w_matrixs), dim=1) + c2w_matrixs = c2w_matrixs.reshape(self.num_views + self.num_derived_views, 4, 4) + + # find nearest views + if self.k_near_views > self.num_views: + raise ValueError("k_near_views should be no larger than num_views") + else: + k_near_indices = self.get_k_near_anchors( + elevations[1:], azimuths[1:], self.k_near_views, self.num_views - 1, exclude_ids=np.arange(self.num_views-1, self.num_views-1 + self.num_derived_views) + ) # NOTE: we use the 1st view as the reference view + #k_near_indices = -1 + + d_elevations = (elevations - elevations[0:1]).reshape(-1, 1) + d_azimuths = (azimuths - azimuths[0:1]).reshape(-1, 1) % (2 * math.pi) + + if self.use_abs_elevation: # stable zero123 use abs_elevation as distance input + distances = elevations[0:1].repeat(self.num_views + self.num_derived_views).reshape(-1, 1) + else: + distances = torch.zeros_like(d_elevations) + + return { + "view_ids": torch.tensor(view_ids), + "images": img_tensors[1:], + "image_0": img_tensors[0], + "elevations": d_elevations[1:], + "azimuths": d_azimuths[1:], + "distances": distances[1:], + "c2w_matrixs": c2w_matrixs[1:], + "intrinsics_matrixs": intrinsics_matrixs[1:], + "cameras": camera_params[1:], + "caption": caption, + "k_near_indices": k_near_indices, + "obj_dir": obj_dir.split('/')[-1], + "num_anchor_images": self.num_views-1, + "num_derived_images": self.num_derived_views + } + + +class MultiViewDataModule(LightningDataModule): + def __init__( + self, + train_dataset: Dataset[Any], + val_dataset: Dataset[Any], + test_dataset: Dataset[Any], + train_batch_size: int = 1, + val_batch_size: int = 1, + test_batch_size: int = 1, + num_workers: Optional[int] = None, + pin_memory: bool = True, + ): + super().__init__() + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False) + + self.data_train = train_dataset + self.data_val = val_dataset + self.data_test = test_dataset + + self.num_workers = num_workers if num_workers else train_batch_size * 2 + + def prepare_data(self) -> None: + # TODO: check if data is available + pass + + def _dataloader( + self, dataset: Dataset, batch_size: int, shuffle: bool + ) -> DataLoader[Any]: + return DataLoader( + dataset, + batch_size=batch_size, + shuffle=shuffle, + num_workers=self.num_workers, + pin_memory=self.hparams.pin_memory, + ) + + def train_dataloader(self) -> DataLoader[Any]: + return DataLoader( + self.data_train, + batch_size=self.hparams.train_batch_size, + shuffle=True, + num_workers=self.num_workers, + pin_memory=self.hparams.pin_memory, + ) + + def val_dataloader(self) -> DataLoader[Any]: + # support multiple validation datasets + if isinstance(self.data_val, ListConfig): + return [ + self._dataloader(dataset, self.hparams.val_batch_size, False) + for dataset in self.data_val + ] + elif isinstance(self.data_val, DictConfig): + return [ + self._dataloader(dataset, self.hparams.val_batch_size, False) + for _, dataset in self.data_val.items() + ] + else: + return self._dataloader(self.data_val, self.hparams.val_batch_size, False) + + def test_dataloader(self) -> DataLoader[Any]: + # support multiple test datasets + if isinstance(self.data_test, ListConfig): + return [ + self._dataloader(dataset, self.hparams.test_batch_size, False) + for dataset in self.data_test + ] + elif isinstance(self.data_test, DictConfig): + return [ + self._dataloader(dataset, self.hparams.test_batch_size, False) + for _, dataset in self.data_test.items() + ] + else: + return self._dataloader(self.data_test, self.hparams.test_batch_size, False) + + +if __name__ == "__main__": + from torchvision.utils import save_image + + dataset = MultiViewDataset( + root_dir="/mnt/pfs/data/render_lvis_hzh", + num_views=17, + k_near_views=4, + bg_color="white", + img_wh=(256, 256), + ref_view_mode=2, + sample_views_mode="random", + caption_path="data/render_lvis_hzh/caption_train.txt", + use_abs_elevation=True, + ) + + sample = dataset[0] + print(sample["view_ids"]) + save_image((sample["image_0"] + 1.0) / 2, "temp_0.jpg", nrow=1, value_range=(0, 1)) + save_image((sample["images"] + 1.0) / 2, "temp.jpg", nrow=8, value_range=(0, 1)) diff --git a/loomnet/models/__init__.py b/loomnet/models/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loomnet/models/__pycache__/__init__.cpython-311.pyc b/loomnet/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84637ec18fda2ea4aaab9f092ce6a21e82675d2f Binary files /dev/null and b/loomnet/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model.cpython-311.pyc b/loomnet/models/__pycache__/mv_model.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea75bf5da467160649444e1350945cc9fd7be4bc Binary files /dev/null and b/loomnet/models/__pycache__/mv_model.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_1_to_infinity.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_1_to_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b64ddb22cc35f2701e0f3b771ee80a0afa42216b Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_1_to_infinity.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_infinity.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1cd5498d5dda30553a98663267d9d854c3786e4 Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_infinity.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_triplane.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_triplane.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de9d1441fb4901a52bc51b038b862461bd92ca13 Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_triplane.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_triplane_with_3d_conv.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_triplane_with_3d_conv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77546a1a491d6f854c4bc5bb335a5b043d9f13f7 Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_triplane_with_3d_conv.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_v7.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_v7.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f755b4a6238afe38a10a1b20a292809254579d31 Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_v7.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_v8.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_v8.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee6ca65e9246eec6e58bb7f4214bbb77318ad97c Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_v8.cpython-311.pyc differ diff --git a/loomnet/models/__pycache__/mv_model_with_distillation.cpython-311.pyc b/loomnet/models/__pycache__/mv_model_with_distillation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eff7fa27fe2d4680428b65ba7bf9c0e2ef3a64e Binary files /dev/null and b/loomnet/models/__pycache__/mv_model_with_distillation.cpython-311.pyc differ diff --git a/loomnet/models/blocks/__init__.py b/loomnet/models/blocks/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loomnet/models/blocks/__pycache__/__init__.cpython-311.pyc b/loomnet/models/blocks/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c44545083fa96d8c70dd51d80ecd2bb082ef9c41 Binary files /dev/null and b/loomnet/models/blocks/__pycache__/__init__.cpython-311.pyc differ diff --git a/loomnet/models/blocks/__pycache__/generic_blocks.cpython-311.pyc b/loomnet/models/blocks/__pycache__/generic_blocks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ef285b05670ab9896524d76fab10198f92f52ab Binary files /dev/null and b/loomnet/models/blocks/__pycache__/generic_blocks.cpython-311.pyc differ diff --git a/loomnet/models/blocks/__pycache__/pointwise_spatial_transformer.cpython-311.pyc b/loomnet/models/blocks/__pycache__/pointwise_spatial_transformer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58c0019816c41316cb91f198c198d25e604878b0 Binary files /dev/null and b/loomnet/models/blocks/__pycache__/pointwise_spatial_transformer.cpython-311.pyc differ diff --git a/loomnet/models/blocks/__pycache__/resnet.cpython-311.pyc b/loomnet/models/blocks/__pycache__/resnet.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce1915456391f698fee077418f7cddde5260daa8 Binary files /dev/null and b/loomnet/models/blocks/__pycache__/resnet.cpython-311.pyc differ diff --git a/loomnet/models/blocks/__pycache__/resnet_fpn.cpython-311.pyc b/loomnet/models/blocks/__pycache__/resnet_fpn.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d62e20c6ca2b98efd990e0596a695b6142fd1ff Binary files /dev/null and b/loomnet/models/blocks/__pycache__/resnet_fpn.cpython-311.pyc differ diff --git a/loomnet/models/blocks/__pycache__/transformer_t.cpython-311.pyc b/loomnet/models/blocks/__pycache__/transformer_t.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63464839317b51863408c437568e8b044dbbd2ba Binary files /dev/null and b/loomnet/models/blocks/__pycache__/transformer_t.cpython-311.pyc differ diff --git a/loomnet/models/blocks/attention.py b/loomnet/models/blocks/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d01f72efdc5ebb4b19d84ecb732033da692d5a --- /dev/null +++ b/loomnet/models/blocks/attention.py @@ -0,0 +1,739 @@ +# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py + +from dataclasses import dataclass +from typing import Callable, Optional + +import torch +import torch.nn.functional as F +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.models.attention import AdaLayerNorm, FeedForward +from diffusers.models.modeling_utils import ModelMixin +from diffusers.utils import BaseOutput +from diffusers.utils.import_utils import is_xformers_available +from einops import rearrange, repeat +from torch import nn + + +@dataclass +class Transformer3DModelOutput(BaseOutput): + sample: torch.FloatTensor + + +if is_xformers_available(): + import xformers + import xformers.ops +else: + xformers = None + + +class CrossAttention(nn.Module): + r""" + A cross attention layer. + + Parameters: + query_dim (`int`): The number of channels in the query. + cross_attention_dim (`int`, *optional*): + The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`. + heads (`int`, *optional*, defaults to 8): The number of heads to use for multi-head attention. + dim_head (`int`, *optional*, defaults to 64): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + bias (`bool`, *optional*, defaults to False): + Set to `True` for the query, key, and value linear layers to contain a bias parameter. + """ + + def __init__( + self, + query_dim: int, + cross_attention_dim: Optional[int] = None, + heads: int = 8, + dim_head: int = 64, + dropout: float = 0.0, + bias=False, + upcast_attention: bool = False, + upcast_softmax: bool = False, + added_kv_proj_dim: Optional[int] = None, + norm_num_groups: Optional[int] = None, + ): + super().__init__() + inner_dim = dim_head * heads + cross_attention_dim = ( + cross_attention_dim if cross_attention_dim is not None else query_dim + ) + self.upcast_attention = upcast_attention + self.upcast_softmax = upcast_softmax + + self.scale = dim_head**-0.5 + + self.heads = heads + # for slice_size > 0 the attention score computation + # is split across the batch axis to save memory + # You can set slice_size with `set_attention_slice` + self.sliceable_head_dim = heads + self._slice_size = None + self._use_memory_efficient_attention_xformers = False + self.added_kv_proj_dim = added_kv_proj_dim + + if norm_num_groups is not None: + self.group_norm = nn.GroupNorm( + num_channels=inner_dim, + num_groups=norm_num_groups, + eps=1e-5, + affine=True, + ) + else: + self.group_norm = None + + self.to_q = nn.Linear(query_dim, inner_dim, bias=bias) + self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=bias) + self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=bias) + if self.added_kv_proj_dim is not None: + self.add_k_proj = nn.Linear(added_kv_proj_dim, cross_attention_dim) + self.add_v_proj = nn.Linear(added_kv_proj_dim, cross_attention_dim) + + self.to_out = nn.ModuleList([]) + self.to_out.append(nn.Linear(inner_dim, query_dim)) + self.to_out.append(nn.Dropout(dropout)) + + def reshape_heads_to_batch_dim(self, tensor): + batch_size, seq_len, dim = tensor.shape + head_size = self.heads + tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size) + tensor = tensor.permute(0, 2, 1, 3).reshape( + batch_size * head_size, seq_len, dim // head_size + ) + return tensor + + def reshape_batch_dim_to_heads(self, tensor): + batch_size, seq_len, dim = tensor.shape + head_size = self.heads + tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim) + tensor = tensor.permute(0, 2, 1, 3).reshape( + batch_size // head_size, seq_len, dim * head_size + ) + return tensor + + def set_attention_slice(self, slice_size): + if slice_size is not None and slice_size > self.sliceable_head_dim: + raise ValueError( + f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}." + ) + + self._slice_size = slice_size + + def forward( + self, hidden_states, encoder_hidden_states=None, attention_mask=None, meta=None + ): + batch_size, sequence_length, _ = hidden_states.shape + encoder_hidden_states = encoder_hidden_states + + if self.group_norm is not None: + hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = self.to_q(hidden_states) + dim = query.shape[-1] + query = self.reshape_heads_to_batch_dim(query) + + if self.added_kv_proj_dim is not None: + key = self.to_k(hidden_states) + value = self.to_v(hidden_states) + encoder_hidden_states_key_proj = self.add_k_proj(encoder_hidden_states) + encoder_hidden_states_value_proj = self.add_v_proj(encoder_hidden_states) + + key = self.reshape_heads_to_batch_dim(key) + value = self.reshape_heads_to_batch_dim(value) + encoder_hidden_states_key_proj = self.reshape_heads_to_batch_dim( + encoder_hidden_states_key_proj + ) + encoder_hidden_states_value_proj = self.reshape_heads_to_batch_dim( + encoder_hidden_states_value_proj + ) + + key = torch.concat([encoder_hidden_states_key_proj, key], dim=1) + value = torch.concat([encoder_hidden_states_value_proj, value], dim=1) + else: + encoder_hidden_states = ( + encoder_hidden_states + if encoder_hidden_states is not None + else hidden_states + ) + key = self.to_k(encoder_hidden_states) + value = self.to_v(encoder_hidden_states) + + key = self.reshape_heads_to_batch_dim(key) + value = self.reshape_heads_to_batch_dim(value) + + if attention_mask is not None: + if attention_mask.shape[-1] != query.shape[1]: + target_length = query.shape[1] + attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) + attention_mask = attention_mask.repeat_interleave(self.heads, dim=0) + + # attention, what we cannot get enough of + if self._use_memory_efficient_attention_xformers: + hidden_states = self._memory_efficient_attention_xformers( + query, key, value, attention_mask + ) + # Some versions of xformers return output in fp32, cast it back to the dtype of the input + hidden_states = hidden_states.to(query.dtype) + else: + if self._slice_size is None or query.shape[0] // self._slice_size == 1: + hidden_states = self._attention(query, key, value, attention_mask) + else: + hidden_states = self._sliced_attention( + query, key, value, sequence_length, dim, attention_mask + ) + + # linear proj + hidden_states = self.to_out[0](hidden_states) + + # dropout + hidden_states = self.to_out[1](hidden_states) + return hidden_states + + def _attention(self, query, key, value, attention_mask=None): + if self.upcast_attention: + query = query.float() + key = key.float() + + attention_scores = torch.baddbmm( + torch.empty( + query.shape[0], + query.shape[1], + key.shape[1], + dtype=query.dtype, + device=query.device, + ), + query, + key.transpose(-1, -2), + beta=0, + alpha=self.scale, + ) + + if attention_mask is not None: + attention_scores = attention_scores + attention_mask + + if self.upcast_softmax: + attention_scores = attention_scores.float() + + attention_probs = attention_scores.softmax(dim=-1) + + # cast back to the original dtype + attention_probs = attention_probs.to(value.dtype) + + # compute attention output + hidden_states = torch.bmm(attention_probs, value) + + # reshape hidden_states + hidden_states = self.reshape_batch_dim_to_heads(hidden_states) + return hidden_states + + def _sliced_attention( + self, query, key, value, sequence_length, dim, attention_mask + ): + batch_size_attention = query.shape[0] + hidden_states = torch.zeros( + (batch_size_attention, sequence_length, dim // self.heads), + device=query.device, + dtype=query.dtype, + ) + slice_size = ( + self._slice_size if self._slice_size is not None else hidden_states.shape[0] + ) + for i in range(hidden_states.shape[0] // slice_size): + start_idx = i * slice_size + end_idx = (i + 1) * slice_size + + query_slice = query[start_idx:end_idx] + key_slice = key[start_idx:end_idx] + + if self.upcast_attention: + query_slice = query_slice.float() + key_slice = key_slice.float() + + attn_slice = torch.baddbmm( + torch.empty( + slice_size, + query.shape[1], + key.shape[1], + dtype=query_slice.dtype, + device=query.device, + ), + query_slice, + key_slice.transpose(-1, -2), + beta=0, + alpha=self.scale, + ) + + if attention_mask is not None: + attn_slice = attn_slice + attention_mask[start_idx:end_idx] + + if self.upcast_softmax: + attn_slice = attn_slice.float() + + attn_slice = attn_slice.softmax(dim=-1) + + # cast back to the original dtype + attn_slice = attn_slice.to(value.dtype) + attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx]) + + hidden_states[start_idx:end_idx] = attn_slice + + # reshape hidden_states + hidden_states = self.reshape_batch_dim_to_heads(hidden_states) + return hidden_states + + def _memory_efficient_attention_xformers(self, query, key, value, attention_mask): + # TODO attention_mask + query = query.contiguous() + key = key.contiguous() + value = value.contiguous() + hidden_states = xformers.ops.memory_efficient_attention( + query, key, value, attn_bias=attention_mask + ) + hidden_states = self.reshape_batch_dim_to_heads(hidden_states) + return hidden_states + + +class Transformer3DModel(ModelMixin, ConfigMixin): + @register_to_config + def __init__( + self, + num_attention_heads: int = 16, + attention_head_dim: int = 88, + in_channels: Optional[int] = None, + num_layers: int = 1, + dropout: float = 0.0, + norm_num_groups: int = 32, + cross_attention_dim: Optional[int] = None, + attention_bias: bool = False, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + use_linear_projection: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + ): + super().__init__() + self.use_linear_projection = use_linear_projection + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + inner_dim = num_attention_heads * attention_head_dim + + # Define input layers + self.in_channels = in_channels + + self.norm = torch.nn.GroupNorm( + num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True + ) + if use_linear_projection: + self.proj_in = nn.Linear(in_channels, inner_dim) + else: + self.proj_in = nn.Conv2d( + in_channels, inner_dim, kernel_size=1, stride=1, padding=0 + ) + + # Define transformers blocks + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + inner_dim, + num_attention_heads, + attention_head_dim, + dropout=dropout, + cross_attention_dim=cross_attention_dim, + activation_fn=activation_fn, + num_embeds_ada_norm=num_embeds_ada_norm, + attention_bias=attention_bias, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + ) + for d in range(num_layers) + ] + ) + + # Define output layers + if use_linear_projection: + self.proj_out = nn.Linear(in_channels, inner_dim) + else: + self.proj_out = nn.Conv2d( + inner_dim, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + timestep: Optional[torch.LongTensor] = None, + return_dict: bool = True, + meta=None, + ): + # Input + assert ( + hidden_states.dim() == 5 + ), f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}." + video_length = hidden_states.shape[2] + hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w") + batch, _, height, weight = hidden_states.shape + residual = hidden_states + + hidden_states = self.norm(hidden_states) + if not self.use_linear_projection: + hidden_states = self.proj_in(hidden_states) + inner_dim = hidden_states.shape[1] + hidden_states = hidden_states.permute(0, 2, 3, 1).reshape( + batch, height * weight, inner_dim + ) + else: + inner_dim = hidden_states.shape[1] + hidden_states = hidden_states.permute(0, 2, 3, 1).reshape( + batch, height * weight, inner_dim + ) + hidden_states = self.proj_in(hidden_states) + + # Blocks + for block in self.transformer_blocks: + hidden_states = block( + hidden_states, + encoder_hidden_states=encoder_hidden_states, + timestep=timestep, + meta=meta, + ) + + # Output + if not self.use_linear_projection: + hidden_states = ( + hidden_states.reshape(batch, height, weight, inner_dim) + .permute(0, 3, 1, 2) + .contiguous() + ) + hidden_states = self.proj_out(hidden_states) + else: + hidden_states = self.proj_out(hidden_states) + hidden_states = ( + hidden_states.reshape(batch, height, weight, inner_dim) + .permute(0, 3, 1, 2) + .contiguous() + ) + + output = hidden_states + residual + + output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length) + if not return_dict: + return (output,) + + return Transformer3DModelOutput(sample=output) + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + activation_fn: str = "geglu", + num_embeds_ada_norm: Optional[int] = None, + attention_bias: bool = False, + only_cross_attention: bool = False, + upcast_attention: bool = False, + ): + super().__init__() + self.only_cross_attention = only_cross_attention + self.use_ada_layer_norm = num_embeds_ada_norm is not None + # SC-Attn + self.attn1 = KNearsetAttention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + ) + # self.attn1= CrossAttention( + # query_dim=dim, + # heads=num_attention_heads, + # dim_head=attention_head_dim, + # dropout=dropout, + # bias=attention_bias, + # upcast_attention=upcast_attention, + # ) + self.norm1 = ( + AdaLayerNorm(dim, num_embeds_ada_norm) + if self.use_ada_layer_norm + else nn.LayerNorm(dim) + ) + + # Cross-Attn + if cross_attention_dim is not None: + self.attn2 = CrossAttention( + query_dim=dim, + cross_attention_dim=cross_attention_dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + upcast_attention=upcast_attention, + ) + else: + self.attn2 = None + + if cross_attention_dim is not None: + self.norm2 = ( + AdaLayerNorm(dim, num_embeds_ada_norm) + if self.use_ada_layer_norm + else nn.LayerNorm(dim) + ) + else: + self.norm2 = None + + # Feed-forward + self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn) + self.norm3 = nn.LayerNorm(dim) + + def set_use_memory_efficient_attention_xformers( + self, + use_memory_efficient_attention_xformers: bool, + attention_op: Optional[Callable] = None, + ): + if not is_xformers_available(): + print("Here is how to install it") + raise ModuleNotFoundError( + "Refer to https://github.com/facebookresearch/xformers for more information on how to install" + " xformers", + name="xformers", + ) + elif not torch.cuda.is_available(): + raise ValueError( + "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is only" + " available for GPU " + ) + else: + try: + # Make sure we can run the memory efficient attention + _ = xformers.ops.memory_efficient_attention( + torch.randn((1, 2, 40), device="cuda"), + torch.randn((1, 2, 40), device="cuda"), + torch.randn((1, 2, 40), device="cuda"), + ) + except Exception as e: + raise e + self.attn1._use_memory_efficient_attention_xformers = ( + use_memory_efficient_attention_xformers + ) + if self.attn2 is not None: + self.attn2._use_memory_efficient_attention_xformers = ( + use_memory_efficient_attention_xformers + ) + # self.attn_temp._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers + + def forward( + self, + hidden_states, + encoder_hidden_states=None, + timestep=None, + attention_mask=None, + meta=None, + ): + # SparseCausal-Attention + norm_hidden_states = ( + self.norm1(hidden_states, timestep) + if self.use_ada_layer_norm + else self.norm1(hidden_states) + ) + + if self.only_cross_attention: + hidden_states = ( + self.attn1( + norm_hidden_states, + encoder_hidden_states, + attention_mask=attention_mask, + ) + + hidden_states + ) + else: + hidden_states = ( + self.attn1( + norm_hidden_states, + attention_mask=attention_mask, + meta=meta, + ) + + hidden_states + ) + if self.attn2 is not None: + # Cross-Attention + norm_hidden_states = ( + self.norm2(hidden_states, timestep) + if self.use_ada_layer_norm + else self.norm2(hidden_states) + ) + hidden_states = ( + self.attn2( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + ) + + hidden_states + ) + + # Feed-forward + hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states + return hidden_states + + +class SparseCausalAttention(CrossAttention): + def forward( + self, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + video_length=None, + ): + batch_size, sequence_length, _ = hidden_states.shape + + encoder_hidden_states = encoder_hidden_states + + if self.group_norm is not None: + hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = self.to_q(hidden_states) + dim = query.shape[-1] + query = self.reshape_heads_to_batch_dim(query) + + if self.added_kv_proj_dim is not None: + raise NotImplementedError + + encoder_hidden_states = ( + encoder_hidden_states + if encoder_hidden_states is not None + else hidden_states + ) + key = self.to_k(encoder_hidden_states) + value = self.to_v(encoder_hidden_states) + + former_frame_index = torch.arange(video_length) - 1 + former_frame_index[0] = 0 + + key = rearrange(key, "(b f) d c -> b f d c", f=video_length) + key = torch.cat([key[:, [0] * video_length], key[:, former_frame_index]], dim=2) + key = rearrange(key, "b f d c -> (b f) d c") + + value = rearrange(value, "(b f) d c -> b f d c", f=video_length) + value = torch.cat( + [value[:, [0] * video_length], value[:, former_frame_index]], dim=2 + ) + value = rearrange(value, "b f d c -> (b f) d c") + + key = self.reshape_heads_to_batch_dim(key) + value = self.reshape_heads_to_batch_dim(value) + + if attention_mask is not None: + if attention_mask.shape[-1] != query.shape[1]: + target_length = query.shape[1] + attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) + attention_mask = attention_mask.repeat_interleave(self.heads, dim=0) + + # attention, what we cannot get enough of + if self._use_memory_efficient_attention_xformers: + hidden_states = self._memory_efficient_attention_xformers( + query, key, value, attention_mask + ) + # Some versions of xformers return output in fp32, cast it back to the dtype of the input + hidden_states = hidden_states.to(query.dtype) + else: + if self._slice_size is None or query.shape[0] // self._slice_size == 1: + hidden_states = self._attention(query, key, value, attention_mask) + else: + hidden_states = self._sliced_attention( + query, key, value, sequence_length, dim, attention_mask + ) + + # linear proj + hidden_states = self.to_out[0](hidden_states) + + # dropout + hidden_states = self.to_out[1](hidden_states) + return hidden_states + + +class KNearsetAttention(CrossAttention): + def forward( + self, hidden_states, encoder_hidden_states=None, attention_mask=None, meta=None + ): + video_length = meta["video_length"] + k_near_indices = meta["k_near_indices"] # B X F X K + batch_size, sequence_length, _ = hidden_states.shape + + encoder_hidden_states = encoder_hidden_states + + if self.group_norm is not None: + hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = self.to_q(hidden_states) + dim = query.shape[-1] + query = self.reshape_heads_to_batch_dim(query) + + if self.added_kv_proj_dim is not None: + raise NotImplementedError + + encoder_hidden_states = ( + encoder_hidden_states + if encoder_hidden_states is not None + else hidden_states + ) + key = self.to_k(encoder_hidden_states) + value = self.to_v(encoder_hidden_states) + + key = repeat(key, "(b f) d c -> b f k d c", f=video_length, k=video_length) + + b, f_views, k_views = k_near_indices.shape + b_ids = ( + torch.arange(b)[:, None, None].expand(-1, f_views, k_views).to(key.device) + ) + f_ids = ( + torch.arange(f_views)[None, :, None].expand(b, -1, k_views).to(key.device) + ) + + k_nearest_key = key[b_ids, f_ids, k_near_indices] # b x f x k x d x c + + key = rearrange(key, "b f k d c -> (b f) (k d) c") + + value = repeat(value, "(b f) d c -> b f k d c", f=video_length, k=video_length) + k_nearest_value = value[b_ids, f_ids, k_near_indices] # b x f x k x d x c + value = rearrange(value, "b f k d c -> (b f) (k d) c") + + key = self.reshape_heads_to_batch_dim(key) + value = self.reshape_heads_to_batch_dim(value) + + if attention_mask is not None: + if attention_mask.shape[-1] != query.shape[1]: + target_length = query.shape[1] + attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) + attention_mask = attention_mask.repeat_interleave(self.heads, dim=0) + + # attention, what we cannot get enough of + if self._use_memory_efficient_attention_xformers: + hidden_states = self._memory_efficient_attention_xformers( + query, key, value, attention_mask + ) + # Some versions of xformers return output in fp32, cast it back to the dtype of the input + hidden_states = hidden_states.to(query.dtype) + else: + if self._slice_size is None or query.shape[0] // self._slice_size == 1: + hidden_states = self._attention(query, key, value, attention_mask) + else: + hidden_states = self._sliced_attention( + query, key, value, sequence_length, dim, attention_mask + ) + + # linear proj + hidden_states = self.to_out[0](hidden_states) + + # dropout + hidden_states = self.to_out[1](hidden_states) + return hidden_states diff --git a/loomnet/models/blocks/attention_processor.py b/loomnet/models/blocks/attention_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..771b55a7c4be123ca72ff7e1f478175fa87a0df2 --- /dev/null +++ b/loomnet/models/blocks/attention_processor.py @@ -0,0 +1,871 @@ +# modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat + + +class AttnProcessor(nn.Module): + r""" + Default processor for performing attention-related computations. + """ + + def __init__( + self, + hidden_size=None, + cross_attention_dim=None, + ): + super().__init__() + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + elif attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + query = attn.head_to_batch_dim(query) + key = attn.head_to_batch_dim(key) + value = attn.head_to_batch_dim(value) + + attention_probs = attn.get_attention_scores(query, key, attention_mask) + hidden_states = torch.bmm(attention_probs, value) + hidden_states = attn.batch_to_head_dim(hidden_states) + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + return hidden_states + + +class IPAttnProcessor(nn.Module): + r""" + Attention processor for IP-Adapater. + Args: + hidden_size (`int`): + The hidden size of the attention layer. + cross_attention_dim (`int`): + The number of channels in the `encoder_hidden_states`. + scale (`float`, defaults to 1.0): + the weight scale of image prompt. + num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): + The context length of the image features. + """ + + def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4): + super().__init__() + + self.hidden_size = hidden_size + self.cross_attention_dim = cross_attention_dim + self.scale = scale + self.num_tokens = num_tokens + + self.to_k_ip = nn.Linear( + cross_attention_dim or hidden_size, hidden_size, bias=False + ) + self.to_v_ip = nn.Linear( + cross_attention_dim or hidden_size, hidden_size, bias=False + ) + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + else: + # get encoder_hidden_states, ip_hidden_states + end_pos = encoder_hidden_states.shape[1] - self.num_tokens + encoder_hidden_states, ip_hidden_states = ( + encoder_hidden_states[:, :end_pos, :], + encoder_hidden_states[:, end_pos:, :], + ) + if attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + query = attn.head_to_batch_dim(query) + key = attn.head_to_batch_dim(key) + value = attn.head_to_batch_dim(value) + + attention_probs = attn.get_attention_scores(query, key, attention_mask) + hidden_states = torch.bmm(attention_probs, value) + hidden_states = attn.batch_to_head_dim(hidden_states) + + # for ip-adapter + ip_key = self.to_k_ip(ip_hidden_states) + ip_value = self.to_v_ip(ip_hidden_states) + + ip_key = attn.head_to_batch_dim(ip_key) + ip_value = attn.head_to_batch_dim(ip_value) + + ip_attention_probs = attn.get_attention_scores(query, ip_key, None) + ip_hidden_states = torch.bmm(ip_attention_probs, ip_value) + ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states) + + hidden_states = hidden_states + self.scale * ip_hidden_states + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + return hidden_states + + +class AttnProcessor2_0(torch.nn.Module): + r""" + Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). + """ + + def __init__( + self, + hidden_size=None, + cross_attention_dim=None, + frames=8, + ): + super().__init__() + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError( + "AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0." + ) + self.frames = frames + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + hidden_states = rearrange( + hidden_states, "(b f) n c -> b (f n) c", f=self.frames + ) + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + + if attention_mask is not None: + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + # scaled_dot_product_attention expects attention_mask shape to be + # (batch, heads, source_length, target_length) + attention_mask = attention_mask.view( + batch_size, attn.heads, -1, attention_mask.shape[-1] + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + elif attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + inner_dim = key.shape[-1] + head_dim = inner_dim // attn.heads + + query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + # the output of sdp = (batch, num_heads, seq_len, head_dim) + # TODO: add support for attn.scale when we move to Torch 2.1 + hidden_states = F.scaled_dot_product_attention( + query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False + ) + + hidden_states = hidden_states.transpose(1, 2).reshape( + batch_size, -1, attn.heads * head_dim + ) + hidden_states = hidden_states.to(query.dtype) + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + hidden_states = rearrange( + hidden_states, "b (f n) c -> (b f) n c", f=self.frames + ) + return hidden_states + + +class IPAttnProcessor2_0(torch.nn.Module): + r""" + Attention processor for IP-Adapater for PyTorch 2.0. + Args: + hidden_size (`int`): + The hidden size of the attention layer. + cross_attention_dim (`int`): + The number of channels in the `encoder_hidden_states`. + scale (`float`, defaults to 1.0): + the weight scale of image prompt. + num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): + The context length of the image features. + """ + + def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4): + super().__init__() + + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError( + "AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0." + ) + + self.hidden_size = hidden_size + self.cross_attention_dim = cross_attention_dim + self.scale = scale + self.num_tokens = num_tokens + + self.to_k_ip = nn.Linear( + cross_attention_dim or hidden_size, hidden_size, bias=False + ) + self.to_v_ip = nn.Linear( + cross_attention_dim or hidden_size, hidden_size, bias=False + ) + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + + if attention_mask is not None: + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + # scaled_dot_product_attention expects attention_mask shape to be + # (batch, heads, source_length, target_length) + attention_mask = attention_mask.view( + batch_size, attn.heads, -1, attention_mask.shape[-1] + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + else: + # get encoder_hidden_states, ip_hidden_states + end_pos = encoder_hidden_states.shape[1] - self.num_tokens + encoder_hidden_states, ip_hidden_states = ( + encoder_hidden_states[:, :end_pos, :], + encoder_hidden_states[:, end_pos:, :], + ) + if attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + inner_dim = key.shape[-1] + head_dim = inner_dim // attn.heads + + query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + # the output of sdp = (batch, num_heads, seq_len, head_dim) + # TODO: add support for attn.scale when we move to Torch 2.1 + hidden_states = F.scaled_dot_product_attention( + query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False + ) + + hidden_states = hidden_states.transpose(1, 2).reshape( + batch_size, -1, attn.heads * head_dim + ) + hidden_states = hidden_states.to(query.dtype) + + # for ip-adapter + ip_key = self.to_k_ip(ip_hidden_states) + ip_value = self.to_v_ip(ip_hidden_states) + + ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + # the output of sdp = (batch, num_heads, seq_len, head_dim) + # TODO: add support for attn.scale when we move to Torch 2.1 + ip_hidden_states = F.scaled_dot_product_attention( + query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False + ) + + ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape( + batch_size, -1, attn.heads * head_dim + ) + ip_hidden_states = ip_hidden_states.to(query.dtype) + + hidden_states = hidden_states + self.scale * ip_hidden_states + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + return hidden_states + + +## for controlnet +class CNAttnProcessor: + r""" + Default processor for performing attention-related computations. + """ + + def __init__(self, num_tokens=4): + self.num_tokens = num_tokens + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + else: + end_pos = encoder_hidden_states.shape[1] - self.num_tokens + encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text + if attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + query = attn.head_to_batch_dim(query) + key = attn.head_to_batch_dim(key) + value = attn.head_to_batch_dim(value) + + attention_probs = attn.get_attention_scores(query, key, attention_mask) + hidden_states = torch.bmm(attention_probs, value) + hidden_states = attn.batch_to_head_dim(hidden_states) + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + return hidden_states + + +class CNAttnProcessor2_0: + r""" + Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). + """ + + def __init__(self, num_tokens=4): + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError( + "AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0." + ) + self.num_tokens = num_tokens + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + + if attention_mask is not None: + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + # scaled_dot_product_attention expects attention_mask shape to be + # (batch, heads, source_length, target_length) + attention_mask = attention_mask.view( + batch_size, attn.heads, -1, attention_mask.shape[-1] + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + else: + end_pos = encoder_hidden_states.shape[1] - self.num_tokens + encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text + if attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + inner_dim = key.shape[-1] + head_dim = inner_dim // attn.heads + + query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + # the output of sdp = (batch, num_heads, seq_len, head_dim) + # TODO: add support for attn.scale when we move to Torch 2.1 + hidden_states = F.scaled_dot_product_attention( + query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False + ) + + hidden_states = hidden_states.transpose(1, 2).reshape( + batch_size, -1, attn.heads * head_dim + ) + hidden_states = hidden_states.to(query.dtype) + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + return hidden_states + + +from typing import Callable, Optional, Union + +import xformers +import xformers.ops + + +class XFormersAttnProcessor: + r""" + Processor for implementing memory efficient attention using xFormers. + + Args: + attention_op (`Callable`, *optional*, defaults to `None`): + The base + [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to + use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best + operator. + """ + + def __init__(self, attention_op=None): + self.attention_op = attention_op + + def __call__( + self, + attn, + hidden_states: torch.FloatTensor, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + temb: Optional[torch.FloatTensor] = None, + scale: float = 1.0, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, key_tokens, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + + attention_mask = attn.prepare_attention_mask( + attention_mask, key_tokens, batch_size + ) + if attention_mask is not None: + _, query_tokens, _ = hidden_states.shape + attention_mask = attention_mask.expand(-1, query_tokens, -1) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states, scale=scale) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + elif attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states, scale=scale) + value = attn.to_v(encoder_hidden_states, scale=scale) + + query = attn.head_to_batch_dim(query).contiguous() + key = attn.head_to_batch_dim(key).contiguous() + value = attn.head_to_batch_dim(value).contiguous() + + hidden_states = xformers.ops.memory_efficient_attention( + query, + key, + value, + attn_bias=attention_mask, + op=self.attention_op, + scale=attn.scale, + ) + hidden_states = hidden_states.to(query.dtype) + hidden_states = attn.batch_to_head_dim(hidden_states) + + # linear proj + hidden_states = attn.to_out[0](hidden_states, scale=scale) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + + return hidden_states + + +class AttnProcessor3D(nn.Module): + r""" + Default processor for performing attention-related computations. + """ + + def __init__(self, attention_op=None, video_length=16): + super().__init__() + self.video_length = video_length + self.attention_op = attention_op + + def __call__( + self, + attn, + hidden_states, + encoder_hidden_states=None, + attention_mask=None, + temb=None, + ): + residual = hidden_states + + if attn.spatial_norm is not None: + hidden_states = attn.spatial_norm(hidden_states, temb) + + input_ndim = hidden_states.ndim + + if input_ndim == 4: + batch_size, channel, height, width = hidden_states.shape + hidden_states = hidden_states.view( + batch_size, channel, height * width + ).transpose(1, 2) + + batch_size, sequence_length, _ = ( + hidden_states.shape + if encoder_hidden_states is None + else encoder_hidden_states.shape + ) + attention_mask = attn.prepare_attention_mask( + attention_mask, sequence_length, batch_size + ) + + if attn.group_norm is not None: + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose( + 1, 2 + ) + + query = attn.to_q(hidden_states) + + if encoder_hidden_states is None: + encoder_hidden_states = hidden_states + elif attn.norm_cross: + encoder_hidden_states = attn.norm_encoder_hidden_states( + encoder_hidden_states + ) + + key = attn.to_k(encoder_hidden_states) + value = attn.to_v(encoder_hidden_states) + + video_length = self.video_length + query = rearrange(query, "(b f) d c -> b (f d) c", f=video_length) + key = rearrange(key, "(b f) d c -> b (f d) c", f=video_length) + value = rearrange(value, "(b f) d c -> b (f d) c", f=video_length) + + query = attn.head_to_batch_dim(query).contiguous() + key = attn.head_to_batch_dim(key).contiguous() + value = attn.head_to_batch_dim(value).contiguous() + + hidden_states = xformers.ops.memory_efficient_attention( + query, + key, + value, + attn_bias=attention_mask, + op=self.attention_op, + scale=attn.scale, + ) + hidden_states = hidden_states.to(query.dtype) + hidden_states = attn.batch_to_head_dim(hidden_states) + + # linear proj + hidden_states = attn.to_out[0](hidden_states) + # dropout + hidden_states = attn.to_out[1](hidden_states) + + if input_ndim == 4: + hidden_states = hidden_states.transpose(-1, -2).reshape( + batch_size, channel, height, width + ) + + if attn.residual_connection: + hidden_states = hidden_states + residual + + hidden_states = hidden_states / attn.rescale_output_factor + hidden_states = rearrange( + hidden_states, "b (f d) c -> (b f) d c", f=video_length + ) + return hidden_states diff --git a/loomnet/models/blocks/generic_blocks.py b/loomnet/models/blocks/generic_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cf3bc91bd6520c5bb68c6ad0675f3209e40a52 --- /dev/null +++ b/loomnet/models/blocks/generic_blocks.py @@ -0,0 +1,295 @@ +import torch.nn.functional as F +import torch +import torch.nn as nn +from typing import Union, Callable, Optional +import torch +from torch import Tensor + +class ResnetBlock2D(nn.Module): + def __init__(self, in_channels, middle_channels, group_channels, eps=1e-5, kernel_size=3, stride =1, padding=1, dropout=0): + super().__init__() + + self.norm1 = torch.nn.GroupNorm(num_groups=group_channels, num_channels=in_channels, eps=eps, affine=True) + self.nonlinearity = nn.SiLU() + self.conv1 = nn.Conv2d(in_channels, middle_channels, kernel_size=kernel_size, stride=stride, padding=padding) + self.dropout = torch.nn.Dropout(dropout) + self.conv2 = nn.Conv2d(middle_channels, in_channels, kernel_size=1, stride=stride, padding=padding) + + def forward(self, x): + + y = self.norm1(x) + y = self.nonlinearity(y) + y = self.conv1(y) + y_up = F.interpolate(y, size=(x.shape[-2], x.shape[-1]), mode="bilinear") + + y2 = x + y_up + y2 = self.dropout(y2) + + y3 = self.conv2(y2) + + y4 = y3 + y2 + + return y4 + + + + + + + +class UpSample2D(nn.Module): + def __init__(self, in_channels): + super().__init__() + + self.scale_factor = 2 + self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=(3,3), padding=(1,1)) + + def forward(self, x): + x = F.interpolate(x, scale_factor=self.scale_factor, mode="nearest") + x = self.conv(x) + return x + + + +class UpSampleDecoder(nn.Module): + def __init__(self, in_channels, middle_channels, up_factor = 1, group_channels = 32, eps=1e-5, kernel_size=3, dropout=0): + super().__init__() + + assert in_channels % group_channels == 0, "in_channels must be divisible by group_channels" + + self.blocks = nn.ModuleList() + + for _ in range(up_factor): + self.blocks.append(nn.Sequential( + ResnetBlock2D(in_channels, middle_channels, group_channels, eps, kernel_size, dropout), + UpSample2D(in_channels)) + ) + + + def forward(self, x): + + for block in self.blocks: + x = block(x) + + return x + + +class GammaModulator(nn.Module): + def __init__(self, dim, init_values, mlp_hidden_dim, dropout=0.0): + super().__init__() + + #self.norm1 = nn.LayerNorm(dim) + self.norm2 = nn.LayerNorm(dim) + #self.layer_scale1 = LayerScale(dim, init_values=init_values) + self.layer_scale2 = LayerScale(dim, init_values=init_values) + + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=nn.GELU, + drop=dropout, + bias=True, + ) + + ''' + - original_x and new_x both with shape [b, num_tokens, dim]) + ''' + def forward(self, original_x, new_x): + + #new_x = new_x + self.layer_scale1(self.norm1(new_x)) + + #modulate original feature map with the global info collected + original_x = original_x + self.layer_scale2(self.mlp(self.norm2(new_x))) + + return original_x + + #loomnet v3 + # def forward(self, original_x, new_x): + + # x = original_x + self.layer_scale1(self.norm1(new_x)) + + # x = x + self.layer_scale2(self.mlp(self.norm2(x))) + + # return x + + +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 + + + + +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 + + + + + + + + + +class ConvBlock(nn.Module): + + def __init__(self, dim, expansion=2, kernel_size=7): + super().__init__() + self.dwconv = nn.Conv2d(dim, dim, kernel_size, padding=kernel_size // 2, groups=dim) # depthwise conv + self.pwconv1 = nn.Conv2d(dim, dim * expansion, kernel_size=1) + self.act = nn.GELU() + self.pwconv2 = nn.Conv2d(dim * expansion, dim, kernel_size=1) + self.norm = nn.BatchNorm2d(dim) + + def forward(self, x): + shortcut = x + x = self.dwconv(x) + x = self.norm(x) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + return x + shortcut # Residual connection + +class FeatureEnhancer(nn.Module): + def __init__(self, grid_channels, feature_channels, mlp_hidden_dim, grid_encoder_hidden_dim, depth=2, gamma_init_values=1e-5): + super().__init__() + + self.initial_proj = nn.Conv2d(grid_channels, grid_encoder_hidden_dim, kernel_size=1) + + self.encoder = nn.Sequential(*[ConvBlock(grid_encoder_hidden_dim) for _ in range(depth)]) + + self.project_to_feat = nn.Conv2d(grid_encoder_hidden_dim, feature_channels, kernel_size=1) + + # Gating mechanism (learnable modulation) + self.gamma_modulator = GammaModulator(dim=feature_channels, mlp_hidden_dim=mlp_hidden_dim, init_values=gamma_init_values) + + def forward(self, original_feature_map, grid_features ): + + B1, C1, H1, W1 = original_feature_map.shape + + grid_features = F.interpolate(grid_features, size=(H1, W1), mode="nearest") + + grid_features = self.initial_proj(grid_features) # [b, hidden_dim, N, N] + grid_features = self.encoder(grid_features) # deeper encoding + grid_features = self.project_to_feat(grid_features) # [b, C, N, N] + + B2, C2, H2, W2 = grid_features.shape + + original_feature_map_tokens = to_tokens(original_feature_map, B1, C1, H1, W1) + grid_features_tokens = to_tokens(grid_features, B2, C2, H2, W2) + + new_feature_map = from_tokens(self.gamma_modulator(original_feature_map_tokens, grid_features_tokens), H1, W1) + + return new_feature_map + + + +def to_tokens(x, B, C, H, W): + # x: [B, C, D, D] + x = x.view(B, C, H * W).contiguous() # [B, C, D*D] + x = x.permute(0, 2, 1).contiguous() # [B, D*D, C] + return x + +def from_tokens(tokens, H, W): + # tokens: [B, D*D, C] + B, N, C = tokens.shape + x = tokens.permute(0, 2, 1).contiguous() # [B, C, D*D] + x = x.view(B, C, H, W).contiguous() # [B, C, D, D] + return x + + + + +class HarmonicEmbedding(torch.nn.Module): + def __init__( + self, + n_harmonic_functions: int = 6, + omega_0: float = 1.0, + logspace: bool = True, + append_input: bool = True, + ) -> None: + super().__init__() + + if logspace: + frequencies = 2.0 ** torch.arange( + n_harmonic_functions, + dtype=torch.float32, + ) + else: + frequencies = torch.linspace( + 1.0, + 2.0 ** (n_harmonic_functions - 1), + n_harmonic_functions, + dtype=torch.float32, + ) + + self.register_buffer("_frequencies", frequencies * omega_0, persistent=False) + self.append_input = append_input + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: tensor of shape [..., dim] + Returns: + embedding: a harmonic embedding of `x` + of shape [..., (n_harmonic_functions * 2 + int(append_input)) * dim] + """ + embed = (x[..., None] * self._frequencies).view(*x.shape[:-1], -1) + embed = torch.cat( + (embed.sin(), embed.cos(), x) + if self.append_input + else (embed.sin(), embed.cos()), + dim=-1, + ) + return embed + + @staticmethod + def get_output_dim_static( + input_dims: int, + n_harmonic_functions: int, + append_input: bool, + ) -> int: + """ + Utility to help predict the shape of the output of `forward`. + Args: + input_dims: length of the last dimension of the input tensor + n_harmonic_functions: number of embedding frequencies + append_input: whether or not to concat the original + input to the harmonic embedding + Returns: + int: the length of the last dimension of the output tensor + """ + return input_dims * (2 * n_harmonic_functions + int(append_input)) \ No newline at end of file diff --git a/loomnet/models/blocks/pointwise_spatial_transformer.py b/loomnet/models/blocks/pointwise_spatial_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..a95a754593e17c8068aa7df889a823a77a936e42 --- /dev/null +++ b/loomnet/models/blocks/pointwise_spatial_transformer.py @@ -0,0 +1,179 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +#__________________________________ positional encoding _______________________________ + + +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 + omega = torch.arange(embed_dim // 2, dtype=torch.double, device=pos.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() + + + + + +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 + """ + + num_views, num_points, _ = pos_grid.shape + + # Process x and y coordinates separately + emb_x = make_sincos_pos_embed(embed_dim // 2, pos_grid[..., 0], omega_0=omega_0) # [1, H*W, D/2] + emb_y = make_sincos_pos_embed(embed_dim // 2, pos_grid[..., 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(num_views, num_points, embed_dim) # [H, W, D] + +def apply_pos_embed(pos_grid, feature_map_dimension: int=4, ratio: float = 0.1) -> torch.Tensor: + """ + Apply positional embedding to tensor x. + """ + #(num_grid_positions,2) + pos_embed = position_grid_to_embed(pos_grid, feature_map_dimension) + pos_embed = pos_embed * ratio + return pos_embed + + + + + +#___________________________________ Point-wise Adaptive Spatial Transformer _____________________ + + +# class PointWiseSpatialTransformer(nn.Module): +# def __init__(self, feature_map_spatial_dim, feature_map_channel_dim): +# super(PointWiseSpatialTransformer, self).__init__() + +# # Spatial transformer localization-network +# self.localization = nn.Sequential( +# nn.Conv2d(feature_map_channel_dim, feature_map_channel_dim, kernel_size=1), +# nn.MaxPool2d(2, stride=2) if feature_map_spatial_dim in [8,16,32] else nn.Identity(), +# nn.ReLU(True), +# nn.Conv2d(feature_map_channel_dim, feature_map_channel_dim//2, kernel_size=1), +# nn.MaxPool2d(2, stride=2) if feature_map_spatial_dim in [16,32] else nn.Identity(), +# nn.ReLU(True), +# nn.Conv2d(feature_map_channel_dim//2, 16, kernel_size=1), +# nn.MaxPool2d(2, stride=2) if feature_map_spatial_dim in [32] else nn.Identity(), +# nn.ReLU(True) +# ) + +# #normalization layer before concatenatig pos embed in [-1, 1] +# self.loc_norm = torch.nn.LayerNorm(16 * 4 * 4) + +# # Regressor for the 3 * 2 affine matrix +# self.fc_loc = nn.Sequential( +# nn.Linear(16 * 4 * 4 + feature_map_spatial_dim, 32), +# nn.ReLU(True), +# nn.Linear(32, 3 * 2) +# ) + +# # Initialize the weights/bias with identity transformation +# self.fc_loc[2].weight.data.zero_() +# self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float)) + +# # Spatial transformer network forward function +# def stn(self, x, pos_emb): + +# b_and_num_views, num_points, _ = pos_emb.shape + +# xs = self.localization(x) +# xs = xs.view(-1, 16 * 4 * 4) +# xs = self.loc_norm(xs) +# #replico la localization map per ogni punto +# xs = xs.unsqueeze(1).repeat(1, pos_emb.shape[1], 1) +# #aggiungo le posizioni all'embedding della mappa +# xs = torch.cat([xs, pos_emb], dim=-1) + +# #predico affine transformation for each point +# theta = self.fc_loc(xs) +# theta = theta.view(b_and_num_views, num_points, 2, 3) + +# return theta + +# def forward(self, feature_map, pos_emb): +# # transform projected points +# theta = self.stn(feature_map, pos_emb) + +# return theta + +class PointWiseSpatialTransformer(nn.Module): + def __init__(self, feature_map_spatial_dim, feature_map_channel_dim): + super(PointWiseSpatialTransformer, self).__init__() + + # Spatial transformer localization-network + self.localization = nn.Sequential( + nn.Conv2d(feature_map_channel_dim, feature_map_channel_dim, kernel_size=1), + nn.MaxPool2d(2, stride=2) if feature_map_spatial_dim in [8,16,32] else nn.Identity(), + nn.ReLU(True), + nn.Conv2d(feature_map_channel_dim, feature_map_channel_dim//2, kernel_size=1), + nn.MaxPool2d(2, stride=2) if feature_map_spatial_dim in [16,32] else nn.Identity(), + nn.ReLU(True), + nn.Conv2d(feature_map_channel_dim//2, 16, kernel_size=1), + nn.MaxPool2d(2, stride=2) if feature_map_spatial_dim in [32] else nn.Identity(), + nn.ReLU(True) + ) + + # Regressor for the 3 * 2 affine matrix + self.fc_loc = nn.Sequential( + nn.Linear(16 * 4 * 4, 32), + nn.ReLU(True), + nn.Linear(32, 3 * 2) + ) + + # Initialize the weights/bias with identity transformation + self.fc_loc[2].weight.data.zero_() + self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float)) + + # Spatial transformer network forward function + def stn(self, x, size_grid): + + b_and_num_views, c, _, _ = x.size() + + xs = self.localization(x) + xs = xs.view(-1, 16 * 4 * 4) + theta = self.fc_loc(xs) + theta = theta.view(-1, 2, 3) + + grid = F.affine_grid(theta, [b_and_num_views, c, size_grid, size_grid]) + ambassadors_features = F.grid_sample(x, grid) + + return ambassadors_features, grid + + + def forward(self, feature_map, size_grid): + # transform projected points + ambassadors_features, grid = self.stn(feature_map, size_grid) + + return ambassadors_features, grid \ No newline at end of file diff --git a/loomnet/models/blocks/resnet.py b/loomnet/models/blocks/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..1d47122dadd55abce383ca0c36d96527403dc086 --- /dev/null +++ b/loomnet/models/blocks/resnet.py @@ -0,0 +1,357 @@ +# Borrowed from https://github.com/Tangshitao/MVDiffusion/blob/main/src/models/modules/resnet.py +from abc import abstractmethod + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class BasicResNetBlock(nn.Module): + def __init__(self, in_channels, out_channels, stride=1, zero_init=False): + super(BasicResNetBlock, self).__init__() + self.conv1 = nn.Conv2d( + in_channels, + out_channels, + kernel_size=3, + stride=stride, + padding=1, + bias=False, + ) + self.bn1 = nn.GroupNorm(32, out_channels) + self.relu = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d( + out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False + ) + self.bn2 = nn.GroupNorm(32, out_channels) + + self.shortcut = nn.Sequential() + if stride != 1 or in_channels != out_channels: + self.shortcut = nn.Sequential( + nn.Conv2d( + in_channels, out_channels, kernel_size=1, stride=stride, bias=False + ), + nn.GroupNorm(32, out_channels), + ) + if zero_init: + self.conv2.weight.data.zero_() + if self.conv2.bias is not None: + self.conv2.bias.data.zero_() + + def forward(self, x): + identity = x + + out = self.bn1(x) + out = self.relu(out) + out = self.conv1(out) + + out = self.bn2(out) + out = self.relu(out) + out = self.conv2(out) + identity = self.shortcut(identity) + + out += identity + + return out + + +class SiLU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(x) + + +class GroupNorm32(nn.GroupNorm): + def forward(self, x): + return super().forward(x.float()).type(x.dtype) + + +def conv_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D convolution module. + """ + if dims == 1: + return nn.Conv1d(*args, **kwargs) + elif dims == 2: + return nn.Conv2d(*args, **kwargs) + elif dims == 3: + return nn.Conv3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +def linear(*args, **kwargs): + """ + Create a linear module. + """ + return nn.Linear(*args, **kwargs) + + +class Upsample(nn.Module): + """ + An upsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + upsampling occurs in the inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + if use_conv: + self.conv = conv_nd( + dims, self.channels, self.out_channels, 3, padding=padding + ) + + def forward(self, x): + assert x.shape[1] == self.channels + if self.dims == 3: + x = F.interpolate( + x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" + ) + else: + x = F.interpolate(x, scale_factor=2, mode="nearest") + if self.use_conv: + x = self.conv(x) + return x + + +def normalization(channels): + """ + Make a standard normalization layer. + :param channels: number of input channels. + :return: an nn.Module for normalization. + """ + return GroupNorm32(32, channels) + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def avg_pool_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D average pooling module. + """ + if dims == 1: + return nn.AvgPool1d(*args, **kwargs) + elif dims == 2: + return nn.AvgPool2d(*args, **kwargs) + elif dims == 3: + return nn.AvgPool3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +class Downsample(nn.Module): + """ + A downsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + downsampling occurs in the inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + stride = 2 if dims != 3 else (1, 2, 2) + if use_conv: + self.op = conv_nd( + dims, + self.channels, + self.out_channels, + 3, + stride=stride, + padding=padding, + ) + else: + assert self.channels == self.out_channels + self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) + + def forward(self, x): + assert x.shape[1] == self.channels + return self.op(x) + + +class TimestepBlock(nn.Module): + """ + Any module where forward() takes timestep embeddings as a second argument. + """ + + @abstractmethod + def forward(self, x, emb): + """ + Apply the module to `x` given `emb` timestep embeddings. + """ + + +def checkpoint(func, inputs, params, flag): + """ + Evaluate a function without caching intermediate activations, allowing for + reduced memory at the expense of extra compute in the backward pass. + :param func: the function to evaluate. + :param inputs: the argument sequence to pass to `func`. + :param params: a sequence of parameters `func` depends on but does not + explicitly take as arguments. + :param flag: if False, disable gradient checkpointing. + """ + if flag: + args = tuple(inputs) + tuple(params) + return CheckpointFunction.apply(func, len(inputs), *args) + else: + return func(*inputs) + + +class CheckpointFunction(torch.autograd.Function): + @staticmethod + def forward(ctx, run_function, length, *args): + ctx.run_function = run_function + ctx.input_tensors = list(args[:length]) + ctx.input_params = list(args[length:]) + + with torch.no_grad(): + output_tensors = ctx.run_function(*ctx.input_tensors) + return output_tensors + + @staticmethod + def backward(ctx, *output_grads): + ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] + with torch.enable_grad(): + # Fixes a bug where the first op in run_function modifies the + # Tensor storage in place, which is not allowed for detach()'d + # Tensors. + shallow_copies = [x.view_as(x) for x in ctx.input_tensors] + output_tensors = ctx.run_function(*shallow_copies) + input_grads = torch.autograd.grad( + output_tensors, + ctx.input_tensors + ctx.input_params, + output_grads, + allow_unused=True, + ) + del ctx.input_tensors + del ctx.input_params + del output_tensors + return (None, None) + input_grads + + +class ResBlock(TimestepBlock): + """ + A residual block that can optionally change the number of channels. + :param channels: the number of input channels. + :param emb_channels: the number of timestep embedding channels. + :param dropout: the rate of dropout. + :param out_channels: if specified, the number of out channels. + :param use_conv: if True and out_channels is specified, use a spatial + convolution instead of a smaller 1x1 convolution to change the + channels in the skip connection. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param use_checkpoint: if True, use gradient checkpointing on this module. + :param up: if True, use this block for upsampling. + :param down: if True, use this block for downsampling. + """ + + def __init__( + self, + channels, + emb_channels, + dropout=0.0, + out_channels=None, + use_conv=False, + use_scale_shift_norm=False, + dims=2, + use_checkpoint=False, + up=False, + down=False, + ): + super().__init__() + self.channels = channels + self.emb_channels = emb_channels + self.dropout = dropout + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.use_checkpoint = use_checkpoint + self.use_scale_shift_norm = use_scale_shift_norm + + self.in_layers = nn.Sequential( + normalization(channels), + nn.SiLU(), + conv_nd(dims, channels, self.out_channels, 3, padding=1), + ) + + self.updown = up or down + + if up: + self.h_upd = Upsample(channels, False, dims) + self.x_upd = Upsample(channels, False, dims) + elif down: + self.h_upd = Downsample(channels, False, dims) + self.x_upd = Downsample(channels, False, dims) + else: + self.h_upd = self.x_upd = nn.Identity() + + self.emb_layers = nn.Sequential( + nn.SiLU(), + linear( + emb_channels, + 2 * self.out_channels if use_scale_shift_norm else self.out_channels, + ), + ) + self.out_layers = nn.Sequential( + normalization(self.out_channels), + nn.SiLU(), + nn.Dropout(p=dropout), + zero_module( + conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) + ), + ) + + if self.out_channels == channels: + self.skip_connection = nn.Identity() + elif use_conv: + self.skip_connection = conv_nd( + dims, channels, self.out_channels, 3, padding=1 + ) + else: + self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) + + def forward(self, x, emb): + """ + Apply the block to a Tensor, conditioned on a timestep embedding. + :param x: an [N x C x ...] Tensor of features. + :param emb: an [N x emb_channels] Tensor of timestep embeddings. + :return: an [N x C x ...] Tensor of outputs. + """ + return checkpoint( + self._forward, (x, emb), self.parameters(), self.use_checkpoint + ) + + def _forward(self, x, emb): + if self.updown: + in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] + h = in_rest(x) + h = self.h_upd(h) + x = self.x_upd(x) + h = in_conv(h) + else: + h = self.in_layers(x) + emb_out = self.emb_layers(emb).type(h.dtype) + while len(emb_out.shape) < len(h.shape): + emb_out = emb_out[..., None] + if self.use_scale_shift_norm: + out_norm, out_rest = self.out_layers[0], self.out_layers[1:] + scale, shift = torch.chunk(emb_out, 2, dim=1) + h = out_norm(h) * (1 + scale) + shift + h = out_rest(h) + else: + h = h + emb_out + h = self.out_layers(h) + return self.skip_connection(x) + h diff --git a/loomnet/models/blocks/resnet_fpn.py b/loomnet/models/blocks/resnet_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..67085f2a6bdcec2b2e1f166746bb3b934e517bef --- /dev/null +++ b/loomnet/models/blocks/resnet_fpn.py @@ -0,0 +1,372 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class BottleNeck(nn.Module): + # Scale factor of the number of output channels + expansion = 4 + + def __init__(self, in_channels, out_channels, + stride=1, is_first_block=False): + """ + Args: + in_channels: number of input channels + out_channels: number of output channels + stride: stride using in (a) 3x3 convolution and + (b) 1x1 convolution used for downsampling for skip connection + is_first_block: whether it is the first residual block of the layer + """ + super().__init__() + self.conv1 = nn.Conv2d(in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, stride=1, padding=0) + self.bn1 = nn.BatchNorm2d(out_channels) + + self.conv2 = nn.Conv2d(in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, stride=stride, padding=1) + self.bn2 = nn.BatchNorm2d(out_channels) + + self.conv3 = nn.Conv2d(in_channels=out_channels, + out_channels=out_channels*self.expansion, + kernel_size=1, stride=1, padding=0) + self.bn3 = nn.BatchNorm2d(out_channels*self.expansion) + + self.relu = nn.ReLU() + + # Skip connection goes through 1x1 convolution with stride=2 for + # the first blocks of conv3_x, conv4_x, and conv5_x layers for matching + # spatial dimension of feature maps and number of channels in order to + # perform the add operations. + self.downsample = None + if is_first_block: + self.downsample = nn.Sequential(nn.Conv2d(in_channels=in_channels, + out_channels=out_channels*self.expansion, + kernel_size=1, + stride=stride, + padding=0), + nn.BatchNorm2d(out_channels*self.expansion)) + + + def forward(self, x): + """ + Args: + x: input + Returns: + Residual block output + """ + identity = x.clone() + x = self.relu(self.bn1(self.conv1(x))) + x = self.relu(self.bn2(self.conv2(x))) + + x = self.conv3(x) + x = self.bn3(x) + + if self.downsample: + identity = self.downsample(identity) + + x += identity + x = self.relu(x) + + return x + + +class BasicBlock(nn.Module): + # Scale factor of the number of output channels + expansion = 1 + + def __init__(self, in_channels, out_channels, + stride=1, is_first_block=False): + """ + Args: + in_channels: number of input channels + out_channels: number of output channels + stride: stride using in (a) the first 3x3 convolution and + (b) 1x1 convolution used for downsampling for skip connection + is_first_block: whether it is the first residual block of the layer + """ + super().__init__() + self.conv1 = nn.Conv2d(in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + padding=1) + self.bn1 = nn.BatchNorm2d(out_channels) + self.conv2 = nn.Conv2d(in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + stride=1, + padding=1) + self.bn2 = nn.BatchNorm2d(out_channels) + + self.relu = nn.ReLU() + + # Skip connection goes through 1x1 convolution with stride=2 for + # the first blocks of conv3_x, conv4_x, and conv5_x layers for matching + # spatial dimension of feature maps and number of channels in order to + # perform the add operations. + self.downsample = None + if is_first_block and stride != 1: + self.downsample = nn.Sequential(nn.Conv2d(in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=stride, + padding=0), + nn.BatchNorm2d(out_channels)) + + + def forward(self, x): + """ + Args: + x: input + Returns: + Residual block ouput + """ + identity = x.clone() + x = self.relu(self.bn1(self.conv1(x))) + x = self.bn2(self.conv2(x)) + + if self.downsample: + identity = self.downsample(identity) + x += identity + x = self.relu(x) + + return x + + +class ResNet(nn.Module): + def __init__(self, ResBlock, n_blocks_list=[3, 4, 6, 3], + out_channels_list=[64, 128, 256, 512], num_channels=3, final_channel_dim=1280): + """ + Args: + ResBlock: residual block type, BasicBlock for ResNet-18, 34 or + BottleNeck for ResNet-50, 101, 152 + n_block_lists: number of residual blocks for each conv layer (conv2_x - conv5_x) + out_channels_list: list of the output channel numbers for conv2_x - conv5_x + num_channels: the number of channels of input image + """ + super().__init__() + + # Create four convoluiontal layers + in_channels = final_channel_dim // 5 + + # First layer + self.conv1 = nn.Sequential(nn.Conv2d(in_channels=num_channels, + out_channels=in_channels, kernel_size=7, + stride=2, padding=3), + nn.BatchNorm2d(in_channels), + nn.ReLU(), + nn.MaxPool2d(kernel_size=3, + stride=2, padding=1)) + + # For the first block of the second layer, do not downsample and use stride=1. + self.conv2_x = self.CreateLayer(ResBlock, n_blocks_list[0], + in_channels, out_channels_list[0], stride=1) + + # For the first blocks of conv3_x - conv5_x layers, perform downsampling using stride=2. + # By default, ResBlock.expansion = 4 for ResNet-50, 101, 152, + # ResBlock.expansion = 1 for ResNet-18, 34. + self.conv3_x = self.CreateLayer(ResBlock, n_blocks_list[1], + out_channels_list[0]*ResBlock.expansion, + out_channels_list[1], stride=2) + self.conv4_x = self.CreateLayer(ResBlock, n_blocks_list[2], + out_channels_list[1]*ResBlock.expansion, + out_channels_list[2], stride=2) + self.conv5_x = self.CreateLayer(ResBlock, n_blocks_list[3], + out_channels_list[2]*ResBlock.expansion, + out_channels_list[3], stride=2) + + + def forward(self, x): + """ + Args: + x: input image + Returns: + C2: feature maps after conv2_x + C3: feature maps after conv3_x + C4: feature maps after conv4_x + C5: feature maps after conv5_x + y: output class + """ + x = self.conv1(x) + + # Feature maps + C2 = self.conv2_x(x) + C3 = self.conv3_x(C2) + C4 = self.conv4_x(C3) + C5 = self.conv5_x(C4) + + return C2, C3, C4, C5 + + + def CreateLayer(self, ResBlock, n_blocks, in_channels, out_channels, stride=1): + """ + Create a layer with specified type and number of residual blocks. + Args: + ResBlock: residual block type, BasicBlock for ResNet-18, 34 or + BottleNeck for ResNet-50, 101, 152 + n_blocks: number of residual blocks + in_channels: number of input channels + out_channels: number of output channels + stride: stride used in the first 3x3 convolution of the first resdiual block + of the layer and 1x1 convolution for skip connection in that block + Returns: + Convolutional layer + """ + layer = [] + for i in range(n_blocks): + if i == 0: + # Downsample the feature map using input stride for the first block of the layer. + layer.append(ResBlock(in_channels, out_channels, + stride=stride, is_first_block=True)) + else: + # Keep the feature map size same for the rest three blocks of the layer. + # by setting stride=1 and is_first_block=False. + # By default, ResBlock.expansion = 4 for ResNet-50, 101, 152, + # ResBlock.expansion = 1 for ResNet-18, 34. + layer.append(ResBlock(out_channels*ResBlock.expansion, out_channels)) + + return nn.Sequential(*layer) + + +class FPNBlock(nn.Module): + def __init__(self, in_channels, out_channels=256, is_highest_block=False): + """ + Args: + in_channels: the number of input channels + out_channels: the number of output channels + is_highest_block: whether the block is at the highest level of pyramid + """ + super().__init__() + # 1x1 convolution to unify the number of feature map channels to + # a specified value for fusion (matching) + self.conv1 = nn.Conv2d(in_channels, out_channels, + kernel_size=1, stride=1, padding=0) + # apply 3x3 convolution for feature output + self.conv2 = nn.Conv2d(out_channels, out_channels, + kernel_size=3, stride=1, padding=1) + self.is_highest_block = is_highest_block + + + def forward(self, x, y): + """ + Args: + x: input tensor at the current level + y: input tesnor at the previous level (upper level) + Returns: + x: output tensor to the next level (lower level) + out: output tensor at the curret level (after 1x1 and 3x3 convolutions) + """ + x = self.conv1(x) + if not self.is_highest_block: + x += F.interpolate(y, scale_factor=2, mode="bilinear", + align_corners=True) + out = self.conv2(x) + return x, out + + +class FPN(nn.Module): + def __init__(self, expansion=2, in_channels_list=[64, 128, 256, 512], + out_channels=256): + """ + Args: + expansion: expansion rate of ResBlock (1 for BasicBlock or 4 for BottleNeck) + in_channels_list: list of the output channel numbers for conv2_x - conv5_x + out_channels: target number of channels (256 by default) + """ + super().__init__() + + # Create layers to generate P2-P6 + self.P2 = FPNBlock(in_channels_list[0]*expansion, out_channels=out_channels) + self.P3 = FPNBlock(in_channels_list[1]*expansion, out_channels=out_channels) + self.P4 = FPNBlock(in_channels_list[2]*expansion, out_channels=out_channels) + self.P5 = FPNBlock(in_channels_list[3]*expansion, out_channels=out_channels, + is_highest_block=True) + self.P6 = nn.MaxPool2d(kernel_size=1, stride=2, padding=0) + + + def forward(self, C2, C3, C4, C5): + """ + Args: + C2-C5: feature maps output by ResNet + Returns: + P2-P6: enchanced features by FPN + """ + x, P5 = self.P5(C5, None) + x, P4 = self.P4(C4, x) + x, P3 = self.P3(C3, x) + _, P2 = self.P2(C2, x) + P6 = self.P6(P5) + + return P2, P3, P4, P5, P6 + + +class ResnetFPN(nn.Module): + def __init__(self, resnet_arch='50', in_channels=3, final_channel_dim = 1280): + """ + Args: + resnet_arch: the type of ResNet architecture + in_channels: number of channels of the input feature map + """ + super().__init__() + + assert(resnet_arch in ['18', '34', '50', '101', '152']) + assert final_channel_dim % 5 ==0, "final channel dim must be divisible by 5" + + ResBlock = BasicBlock if resnet_arch == '18' or resnet_arch == '34' else BottleNeck + + # Number of residual blocks for each conv layer (conv2_x - conv5_x) + if resnet_arch == '18': + n_blocks_list = [2, 2, 2, 2] + elif resnet_arch == '34' or resnet_arch == '50': + n_blocks_list = [3, 4, 6, 3] + elif resnet_arch == '101': + n_blocks_list = [3, 4, 23, 3] + else: + n_blocks_list = [3, 8, 36, 3] + + # Create ResNet + self.resnet = ResNet(ResBlock, n_blocks_list=n_blocks_list, num_channels=in_channels, final_channel_dim=final_channel_dim) + + # Create FPN + self.FPN = FPN(expansion=ResBlock.expansion) + + + def forward(self, x): + """ + Args: + x: input tensor + Returns: + P2-P6: enhanced features + """ + C2, C3, C4, C5 = self.resnet(x) + P2, P3, P4, P5, P6 = self.FPN(C2, C3, C4, C5) + return P2, P3, P4, P5, P6 + + +if __name__ == "__main__": + ### Resnet arch types + #resnet_arch = '18' + #resnet_arch = '34' + resnet_arch = '50' + #resnet_arch = '101' + #resnet_arch = '152' + + ### Create ResNet+FPN + net = ResnetFPN(resnet_arch, in_channels=3) + + ### Input + x = torch.randn((1, 3, 512, 800), dtype=torch.float32) + + ### Inference + P2, P3, P4, P5, P6 = net(x) + + ### Output + print(f"P2 shape is {P2.shape}") + print(f"P3 shape is {P3.shape}") + print(f"P4 shape is {P4.shape}") + print(f"P5 shape is {P5.shape}") + print(f"P6 shape is {P6.shape}") + + print("Done!") \ No newline at end of file diff --git a/loomnet/models/blocks/transformer.py b/loomnet/models/blocks/transformer.py new file mode 100755 index 0000000000000000000000000000000000000000..c4d09fc376f4499051a3a370834be875f20bebfa --- /dev/null +++ b/loomnet/models/blocks/transformer.py @@ -0,0 +1,221 @@ +# Borrowed from https://github.com/Tangshitao/MVDiffusion/blob/main/src/models/modules/transformer.py +import torch +import torch.nn.functional as F +from einops import rearrange +from torch import einsum, nn + + +class GEGLU(nn.Module): + def __init__(self, dim_in, dim_out): + super().__init__() + self.proj = nn.Linear(dim_in, dim_out * 2) + + def forward(self, x): + x, gate = self.proj(x).chunk(2, dim=-1) + return x * F.gelu(gate) + + +class FeedForward(nn.Module): + def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): + super().__init__() + inner_dim = int(dim * mult) + dim_out = dim + project_in = ( + nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) + if not glu + else GEGLU(dim, inner_dim) + ) + + linear = nn.Linear(inner_dim, dim_out) + linear.weight.data.fill_(0) + linear.bias.data.fill_(0) + self.net = nn.Sequential(project_in, nn.Dropout(dropout), linear) + + def forward(self, x): + return self.net(x) + + +class CrossAttention(nn.Module): + def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): + super().__init__() + inner_dim = dim_head * heads + context_dim = context_dim + + self.scale = dim_head**-0.5 + self.heads = heads + + self.to_q = nn.Linear(query_dim, inner_dim, bias=False) + self.to_k = nn.Linear(context_dim, inner_dim, bias=False) + self.to_v = nn.Linear(context_dim, inner_dim, bias=False) + + self.to_out = nn.Linear(inner_dim, query_dim) + self.to_out.weight.data.fill_(0) + self.to_out.bias.data.fill_(0) + + def forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + + k = self.to_k(context) + v = self.to_v(context) + + q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v)) + + sim = einsum("b i d, b j d -> b i j", q, k) * self.scale + + del q, k + + sim = sim.softmax(dim=-1) + + out = einsum("b i j, b j d -> b i d", sim, v) + out = rearrange(out, "(b h) n d -> b n (h d)", h=h) + return self.to_out(out) + + +def checkpoint(func, inputs, params, flag): + """ + Evaluate a function without caching intermediate activations, allowing for + reduced memory at the expense of extra compute in the backward pass. + :param func: the function to evaluate. + :param inputs: the argument sequence to pass to `func`. + :param params: a sequence of parameters `func` depends on but does not + explicitly take as arguments. + :param flag: if False, disable gradient checkpointing. + """ + if flag: + args = tuple(inputs) + tuple(params) + return CheckpointFunction.apply(func, len(inputs), *args) + else: + return func(*inputs) + + +class CheckpointFunction(torch.autograd.Function): + @staticmethod + def forward(ctx, run_function, length, *args): + ctx.run_function = run_function + ctx.input_tensors = list(args[:length]) + ctx.input_params = list(args[length:]) + ctx.gpu_autocast_kwargs = { + "enabled": torch.is_autocast_enabled(), + "dtype": torch.get_autocast_gpu_dtype(), + "cache_enabled": torch.is_autocast_cache_enabled(), + } + with torch.no_grad(): + output_tensors = ctx.run_function(*ctx.input_tensors) + return output_tensors + + @staticmethod + def backward(ctx, *output_grads): + ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] + with torch.enable_grad(), torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs): + # Fixes a bug where the first op in run_function modifies the + # Tensor storage in place, which is not allowed for detach()'d + # Tensors. + shallow_copies = [x.view_as(x) for x in ctx.input_tensors] + output_tensors = ctx.run_function(*shallow_copies) + input_grads = torch.autograd.grad( + output_tensors, + ctx.input_tensors + ctx.input_params, + output_grads, + allow_unused=True, + ) + del ctx.input_tensors + del ctx.input_params + del output_tensors + return (None, None) + input_grads + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + disable_self_attn=False, + use_checkpoint=True, + ): + super().__init__() + + self.attn1 = CrossAttention( + query_dim=dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + context_dim=context_dim, + ) # is a self-attention if not self.disable_self_attn + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.norm1 = nn.LayerNorm(dim) + self.norm2 = nn.LayerNorm(dim) + + self.checkpoint = checkpoint + self.use_checkpoint = use_checkpoint + + def forward(self, x, context=None, query_pe=None): + if self.use_checkpoint: + return checkpoint( + self._forward, + (x, context, query_pe), + self.parameters(), + self.checkpoint, + ) + else: + return self._forward(x, context, query_pe) + + def _forward(self, x, context=None, query_pe=None): + if context is None: + context = x + query = x + if query_pe is not None: + query = query + query_pe + query = self.norm1(query) + context = self.norm1(context) + x = self.attn1(query, context=context) + x + x = self.ff(self.norm2(x)) + x + + return x + + +class PosEmbedding(nn.Module): + def __init__(self, in_channels, N_freqs, logscale=True): + """ + Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) + in_channels: number of input channels (3 for both xyz and direction) + """ + super(PosEmbedding, self).__init__() + self.N_freqs = N_freqs + self.in_channels = in_channels + # self.funcs = [torch.sin, torch.cos] + # self.out_channels = in_channels*(len(self.funcs)*N_freqs) + if N_freqs <= 80: + base = 2 + else: + base = 5000 ** (1 / (N_freqs / 2.5)) + if logscale: + freq_bands = base ** torch.linspace(0, N_freqs - 1, N_freqs)[None, None] + else: + freq_bands = torch.linspace(1, 2 ** (N_freqs - 1), N_freqs) + self.register_buffer("freq_bands", freq_bands) + + def forward(self, x): + """ + Embeds x to (x, sin(2^k x), cos(2^k x), ...) + Different from the paper, "x" is also in the output + See https://github.com/bmild/nerf/issues/12 + Inputs: + x: (B, self.in_channels) + Outputs: + out: (B, self.out_channels) + """ + shape = x.shape[:-1] + x = x.reshape(-1, 2, 1) + + encodings = x * self.freq_bands + sin_encodings = torch.sin(encodings) # (n, c, num_encoding_functions) + cos_encodings = torch.cos(encodings) + pe = torch.cat([sin_encodings, cos_encodings], dim=1) + pe = pe.reshape(*shape, -1) + return pe diff --git a/loomnet/models/blocks/transformer_t.py b/loomnet/models/blocks/transformer_t.py new file mode 100644 index 0000000000000000000000000000000000000000..89899ff38465e0f074e61877adbc6a737c3381c7 --- /dev/null +++ b/loomnet/models/blocks/transformer_t.py @@ -0,0 +1,268 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat + +from loomnet.utils.ops import default, exists, zero_module + + +class CrossAttention(nn.Module): + def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): + super().__init__() + inner_dim = dim_head * heads + + if context_dim is None: + context_dim = query_dim + + self.scale = dim_head**-0.5 + self.heads = heads + + self.to_q = nn.Linear(query_dim, inner_dim, bias=False) + self.to_k = nn.Linear(context_dim, inner_dim, bias=False) + self.to_v = nn.Linear(context_dim, inner_dim, bias=False) + + self.to_out = nn.Sequential( + nn.Linear(inner_dim, query_dim), nn.Dropout(dropout) + ) + + def forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + context = default(context, x) + k = self.to_k(context) + v = self.to_v(context) + q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v)) + + sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scale + + if exists(mask): + mask = rearrange(mask, "b ... -> b (...)") + max_neg_value = -torch.finfo(sim.dtype).max + mask = repeat(mask, "b j -> (b h) () j", h=h) + sim.masked_fill_(~mask, max_neg_value) + + # attention, what we cannot get enough of + attn = sim.softmax(dim=-1) + + out = torch.einsum("b i j, b j d -> b i d", attn, v) + out = rearrange(out, "(b h) n d -> b n (h d)", h=h) + return self.to_out(out) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values=1e-5, inplace=False): + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class GEGLU(nn.Module): + def __init__(self, dim_in, dim_out): + super().__init__() + self.proj = nn.Linear(dim_in, dim_out * 2) + + def forward(self, x): + x, gate = self.proj(x).chunk(2, dim=-1) + return x * F.gelu(gate) + + +class FeedForward(nn.Module): + def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): + super().__init__() + inner_dim = int(dim * mult) + if dim_out is None: + dim_out = dim + + project_in = ( + nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) + if not glu + else GEGLU(dim, inner_dim) + ) + + self.net = nn.Sequential( + project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out) + ) + + def forward(self, x): + return self.net(x) + + +class AdaLayerNorm(nn.Module): + def __init__(self, n_embd): + super().__init__() + + self.silu = nn.SiLU() + self.linear = nn.Linear(n_embd, n_embd * 2) + self.layernorm = nn.LayerNorm(n_embd, elementwise_affine=False) + + def forward(self, x, timestep): + emb = self.linear(timestep) + scale, shift = torch.chunk(emb, 2, dim=-1) + x = self.layernorm(x) * (1 + scale) + shift + return x + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + self.attn1 = CrossAttention( + query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) # is a self-attention + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.attn2 = CrossAttention( + query_dim=dim, + context_dim=context_dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + ) # is self-attn if context is none + self.norm1 = AdaLayerNorm(dim) + self.norm2 = AdaLayerNorm(dim) + self.norm3 = AdaLayerNorm(dim) + + def forward(self, x, t, context=None, mask=None): + x = self.attn1(self.norm1(x, t)) + x + x = self.attn2(self.norm2(x, t), context=context, mask=mask) + x + x = self.ff(self.norm3(x, t)) + x + return x + + +class Transformer(nn.Module): + """ + Transformer block for image-like data. + First, project the input (aka embedding) + and reshape to b, t, d. + Then apply standard transformer action. + Finally, reshape to image + """ + + def __init__( + self, + in_channels, + n_heads, + d_head, + out_channels=None, + depth=1, + dropout=0.0, + context_dim=None, + ): + super().__init__() + self.in_channels = in_channels + inner_dim = n_heads * d_head + + self.proj_in = nn.Linear(in_channels, inner_dim, bias=False) + + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + inner_dim, + n_heads=n_heads, + d_head=d_head, + context_dim=context_dim, + dropout=dropout, + ) + for _ in range(depth) + ] + ) + out_channels = default(out_channels, in_channels) + self.proj_out = zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + self.t_proj = nn.Linear(1280, inner_dim) + + def forward(self, x, t, context=None, attention_mask=None): + x = self.proj_in(x) + t = self.t_proj(t).unsqueeze(1) + for block in self.transformer_blocks: + x = block(x, t, context=context, mask=attention_mask) + + x = self.proj_out(x) + return x + + +class FuseTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + self.attn1 = CrossAttention( + query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) # is a self-attention + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.norm1 = AdaLayerNorm(dim) + self.norm3 = AdaLayerNorm(dim) + + def forward(self, x, t, context=None, mask=None): + # (b f n) k s c + x = self.attn1(self.norm1(x, t), mask=mask) + x + x = self.ff(self.norm3(x, t)) + x + return x + + +class FuseTransformer(nn.Module): + """ + Transformer block for image-like data. + First, project the input (aka embedding) + and reshape to b, t, d. + Then apply standard transformer action. + Finally, reshape to image + """ + + def __init__( + self, + in_channels, + n_heads, + d_head, + out_channels=None, + depth=1, + dropout=0.0, + context_dim=None, + ): + super().__init__() + self.in_channels = in_channels + inner_dim = n_heads * d_head + + self.proj_in = nn.Linear(in_channels, inner_dim, bias=False) + + self.transformer_blocks = nn.ModuleList( + [ + FuseTransformerBlock( + inner_dim, + n_heads=n_heads, + d_head=d_head, + context_dim=context_dim, + dropout=dropout, + ) + for _ in range(depth) + ] + ) + + out_channels = default(out_channels, in_channels) + self.proj_out = zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + self.t_proj = nn.Linear(1280, inner_dim) + + def forward(self, x, t, context=None, attention_mask=None): + x = self.proj_in(x) + t = self.t_proj(t) + for block in self.transformer_blocks: + x = block(x, t, context=context, mask=attention_mask) + x = self.proj_out(x) + return x \ No newline at end of file diff --git a/loomnet/models/blocks/transformer_t_old.py b/loomnet/models/blocks/transformer_t_old.py new file mode 100644 index 0000000000000000000000000000000000000000..967b4976cb37180ac33218f9a441fb192e826aab --- /dev/null +++ b/loomnet/models/blocks/transformer_t_old.py @@ -0,0 +1,739 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat +from torch_geometric.nn import GATv2Conv +from loomnet.utils.ops import default, exists, zero_module + + +class CrossAttention(nn.Module): + def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): + super().__init__() + inner_dim = dim_head * heads + + if context_dim is None: + context_dim = query_dim + + self.scale = dim_head**-0.5 + self.heads = heads + + self.to_q = nn.Linear(query_dim, inner_dim, bias=False) + self.to_k = nn.Linear(context_dim, inner_dim, bias=False) + self.to_v = nn.Linear(context_dim, inner_dim, bias=False) + + self.to_out = nn.Sequential( + nn.Linear(inner_dim, query_dim), nn.Dropout(dropout) + ) + + def forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + context = default(context, x) + k = self.to_k(context) + v = self.to_v(context) + q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v)) + + sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scale + + if exists(mask): + mask = rearrange(mask, "b ... -> b (...)") + max_neg_value = -torch.finfo(sim.dtype).max + mask = repeat(mask, "b j -> (b h) () j", h=h) + sim.masked_fill_(~mask, max_neg_value) + + # attention, what we cannot get enough of + attn = sim.softmax(dim=-1) + + out = torch.einsum("b i j, b j d -> b i d", attn, v) + out = rearrange(out, "(b h) n d -> b n (h d)", h=h) + return self.to_out(out) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values=1e-5, inplace=False): + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class GEGLU(nn.Module): + def __init__(self, dim_in, dim_out): + super().__init__() + self.proj = nn.Linear(dim_in, dim_out * 2) + + def forward(self, x): + x, gate = self.proj(x).chunk(2, dim=-1) + return x * F.gelu(gate) + + +class FeedForward(nn.Module): + def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): + super().__init__() + inner_dim = int(dim * mult) + if dim_out is None: + dim_out = dim + + project_in = ( + nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) + if not glu + else GEGLU(dim, inner_dim) + ) + + self.net = nn.Sequential( + project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out) + ) + + def forward(self, x): + return self.net(x) + + +class AdaLayerNorm(nn.Module): + def __init__(self, n_embd, use_activation=False): + super().__init__() + + self.use_activation = use_activation + if use_activation: + self.silu = nn.SiLU() + self.linear = nn.Linear(n_embd, n_embd * 2) + self.layernorm = nn.LayerNorm(n_embd, elementwise_affine=False) + + def forward(self, x, timestep): + + B, dim = timestep.shape + _, tot_points, _ = x.shape + + if self.use_activation: + timestep = self.silu(timestep) + emb = self.linear(timestep) + emb = emb.repeat_interleave(tot_points, dim=0).view(B, tot_points, emb.shape[-1]) + scale, shift = torch.chunk(emb, 2, dim=-1) + x = self.layernorm(x) * (1 + scale) + shift + return x + + +class AdaLayerNorm3(nn.Module): + def __init__(self, n_embd, use_activation=False): + super().__init__() + + self.use_activation = use_activation + if use_activation: + self.silu = nn.SiLU() + self.linear = nn.Linear(n_embd, n_embd * 2) + self.layernorm = nn.LayerNorm(n_embd, elementwise_affine=False) + + def forward(self, x, timestep): + + B, _, dim = timestep.shape + tot_points, _ = x.shape + + if self.use_activation: + timestep = self.silu(timestep) + emb = self.linear(timestep) + emb = emb.repeat_interleave(tot_points//B, dim=0).squeeze(1) + scale, shift = torch.chunk(emb, 2, dim=-1) + x = self.layernorm(x) * (1 + scale) + shift + return x + + + +class AdaLayerNorm2(nn.Module): + def __init__(self, n_embd, use_activation=False): + super().__init__() + + self.use_activation = use_activation + if use_activation: + self.silu = nn.SiLU() + self.linear = nn.Linear(n_embd, n_embd * 2) + self.layernorm = nn.LayerNorm(n_embd, elementwise_affine=False) + + def forward(self, x, timestep): + + B, dim = timestep.shape + B2, tot_points, _ = x.shape + + if self.use_activation: + timestep = self.silu(timestep) + emb = self.linear(timestep) + emb = emb.repeat_interleave(B2//B, dim=0).unsqueeze(1).expand(-1, tot_points, -1) + scale, shift = torch.chunk(emb, 2, dim=-1) + x = self.layernorm(x) * (1 + scale) + shift + return x + + + + + +class AdaLayerNormGraph(nn.Module): + def __init__(self, n_embd, use_activation=False): + super().__init__() + + self.use_activation = use_activation + if use_activation: + self.silu = nn.SiLU() + self.linear = nn.Linear(n_embd, n_embd * 2) + self.layernorm = nn.LayerNorm(n_embd, elementwise_affine=False) + + def forward(self, x, timestep): + + B, _ = timestep.shape + tot_points, _ = x.shape + + if self.use_activation: + timestep = self.silu(timestep) + emb = self.linear(timestep) + emb = emb.repeat_interleave(tot_points//B, dim=0) + scale, shift = torch.chunk(emb, 2, dim=-1) + x = self.layernorm(x) * (1 + scale) + shift + return x + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + self.attn1 = CrossAttention( + query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) # is a self-attention + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.attn2 = CrossAttention( + query_dim=dim, + context_dim=context_dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + ) # is self-attn if context is none + self.norm1 = AdaLayerNorm2(dim) + self.norm2 = AdaLayerNorm2(dim) + self.norm3 = AdaLayerNorm2(dim) + + def forward(self, x, t, context=None, mask=None, mod=None): + x = self.attn1(self.norm1(x, t)) + x + x = self.attn2(self.norm2(x, t), context=context, mask=mask) + x + x = self.ff(self.norm3(x, t)) + x + return x + + + +class BasicTransformerBlock3(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + self.attn1 = CrossAttention( + query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) # is a self-attention + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.norm1 = AdaLayerNorm(dim) + self.norm2 = AdaLayerNorm(dim) + + def forward(self, x, t, context=None, mask=None, mod=None): + x = self.attn1(self.norm1(x, t)) + x + x = self.ff(self.norm2(x, t)) + x + return x + + + + +class BasicTransformerModulationBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + self.attn1 = CrossAttention( + query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) # is a self-attention + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + + self.norm1 = AdaLayerNorm(dim) + self.norm3 = AdaLayerNorm(dim, use_activation=True) + + def forward(self, x, t, context=None, mask=None, mod = None): + x = self.attn1(self.norm1(x, t)) + x + x = self.ff(self.norm3(x, mod)) + x + return x + + + + + + +class BasicTransformerBlock2(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff, mult=3) + self.attn2 = CrossAttention( + query_dim=dim, + context_dim=context_dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + ) # is self-attn if context is none + + self.norm2 = AdaLayerNorm2(dim) + self.norm3 = AdaLayerNorm2(dim) + + def forward(self, x, t, context=None, mask=None, mod=None): + x = self.attn2(self.norm2(x, t), context=context, mask=mask) + x + x = self.ff(self.norm3(x, t)) + x + return x + + + + + + + + + + +class Transformer(nn.Module): + """ + Transformer block for image-like data. + First, project the input (aka embedding) + and reshape to b, t, d. + Then apply standard transformer action. + Finally, reshape to image + """ + + def __init__( + self, + in_channels, + n_heads, + d_head, + out_channels=None, + depth=1, + dropout=0.0, + context_dim=None, + mod_dim = None, + type_of_transformer_block = 'self-cross', #['self-cross', 'cross', 'self-mod'] + zero_out_proj = False + ): + super().__init__() + self.in_channels = in_channels + inner_dim = n_heads * d_head + + self.proj_in = nn.Linear(in_channels, inner_dim, bias=False) + + # Mapping tra tipo di blocco e classe corrispondente + transformer_block_type = { + 'self-cross': BasicTransformerBlock, + 'cross': BasicTransformerBlock2, + 'self': BasicTransformerBlock3, + 'self-mod': BasicTransformerModulationBlock, + } + + self.transformer_blocks = nn.ModuleList( + [ + transformer_block_type[type_of_transformer_block]( + inner_dim, + n_heads=n_heads, + d_head=d_head, + context_dim=context_dim, + dropout=dropout, + ) + + for _ in range(depth) + ] + ) + out_channels = default(out_channels, in_channels) + + if zero_out_proj: + self.proj_out = zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + else: + self.proj_out = nn.Linear(inner_dim, out_channels, bias=False) #zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + + self.t_proj = nn.Linear(1280, inner_dim) + + self.type_of_transformer_block = type_of_transformer_block + if type_of_transformer_block == 'self-mod': + self.mod_proj = nn.Linear(mod_dim, inner_dim, bias=False) + + def forward(self, x, t, context=None, attention_mask=None, mod=None): + x = self.proj_in(x) + t = self.t_proj(t) + if self.type_of_transformer_block == 'self-mod': + mod = self.mod_proj(mod) + + for block in self.transformer_blocks: + x = block(x, t, context=context, mask=attention_mask, mod=mod) + + x = self.proj_out(x) + return x + + +class FuseTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + ): + super().__init__() + self.attn1 = CrossAttention( + query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) # is a self-attention + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.norm1 = AdaLayerNorm(dim) + self.norm3 = AdaLayerNorm(dim) + + def forward(self, x, t, context=None, mask=None): + # (b f n) k s c + x = self.attn1(self.norm1(x, t), mask=mask) + x + x = self.ff(self.norm3(x, t)) + x + return x + + +class FuseTransformer(nn.Module): + """ + Transformer block for image-like data. + First, project the input (aka embedding) + and reshape to b, t, d. + Then apply standard transformer action. + Finally, reshape to image + """ + + def __init__( + self, + in_channels, + n_heads, + d_head, + out_channels=None, + depth=1, + dropout=0.0, + context_dim=None, + ): + super().__init__() + self.in_channels = in_channels + inner_dim = n_heads * d_head + + self.proj_in = nn.Linear(in_channels, inner_dim, bias=False) + + self.transformer_blocks = nn.ModuleList( + [ + FuseTransformerBlock( + inner_dim, + n_heads=n_heads, + d_head=d_head, + context_dim=context_dim, + dropout=dropout, + ) + for _ in range(depth) + ] + ) + + out_channels = default(out_channels, in_channels) + self.proj_out = zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + self.t_proj = nn.Linear(1280, inner_dim) + + def forward(self, x, t, context=None, attention_mask=None): + x = self.proj_in(x) + t = self.t_proj(t) + for block in self.transformer_blocks: + x = block(x, t, context=context, mask=attention_mask) + x = self.proj_out(x) + return x + + + + + + + + + + +class GraphAttentionWrapper(nn.Module): + """ + Wrapper per usare GATv2Conv all'interno di un blocco tipo Transformer. + Compatibile con il tuo schema CrossAttention. + """ + def __init__(self, in_dim, heads=4, dim_head=32, dropout=0.0): + super().__init__() + self.heads = heads + self.out_dim = heads * dim_head + + self.gat = GATv2Conv( + in_channels=in_dim, + out_channels=dim_head, + heads=heads, + dropout=dropout, + add_self_loops=False, #--> i want to update only hub nodes + ) + self.proj = nn.Linear(self.out_dim, in_dim) + + def forward(self, x, edge_index, hub_indices, **kwargs): + out = self.gat(x, edge_index) + out = self.proj(out[hub_indices]) #layer finale solo per gli hub + return out + + + +class LocalGraphAttentionWrapper(nn.Module): + """ + Wrapper per usare GATv2Conv all'interno di un blocco tipo Transformer. + Compatibile con il tuo schema CrossAttention. + """ + def __init__(self, in_dim, heads=4, dim_head=32, dropout=0.0): + super().__init__() + self.heads = heads + self.out_dim = heads * dim_head + + self.gat = GATv2Conv( + in_channels=in_dim, + out_channels=dim_head, + heads=heads, + dropout=dropout + ) + self.proj = nn.Linear(self.out_dim, in_dim) + + def forward(self, x, edge_index, **kwargs): + out = self.gat(x, edge_index) + out = self.proj(out) #layer finale solo per gli hub + return out + +class BasicLocalGraphTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + # context_dim=None, + gated_ff=True, + ): + super().__init__() + # Usa il wrapper GraphAttentionWrapper invece di CrossAttention + self.attn1 = LocalGraphAttentionWrapper( + in_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) + # self.attn2 = GraphAttentionWrapper( + # in_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + # ) + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + + self.norm1 = AdaLayerNorm3(dim) + # self.norm2 = AdaLayerNorm(dim) + self.norm3 = AdaLayerNorm3(dim) + + def forward(self, x, t, edge_index, context=None, mask=None): + # Passa l'edge_index per l'attenzione a grafo + x = self.attn1(self.norm1(x, t), edge_index) + x + # x = self.attn2(self.norm2(x, t), edge_index) + x + x = self.ff(self.norm3(x, t)) + x + return x + + + + +class BasicGraphTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + # context_dim=None, + gated_ff=True, + num_grid_points = 1, + num_views = 1, + reverse_connection = False + ): + super().__init__() + # Usa il wrapper GraphAttentionWrapper invece di CrossAttention + self.attn1 = GraphAttentionWrapper( + in_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + ) + # self.attn2 = GraphAttentionWrapper( + # in_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout + # ) + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff, mult=3) + + self.dim = dim + + self.norm1 = AdaLayerNormGraph(dim) + # self.norm2 = AdaLayerNorm(dim) + self.norm3 = AdaLayerNormGraph(dim) + + self.num_grid_points = num_grid_points + self.num_views = num_views + self.reverse_connection = reverse_connection + + def forward(self, ambassadors_features, latent_points, t, edge_index, context=None, mask=None): + + B, _, _ = ambassadors_features.shape + B2, num_points, _ = latent_points.shape + + if B2 == 1: + #replico punti latenti per ogni batch + latent_points = latent_points.repeat(B, 1, 1) + #li metto insieme ai punti proiettati --> (B, num_grid_points + num_latent_points, C) + combined_features = torch.cat([ambassadors_features, latent_points], dim=1) + #per la GNN riporto tutto in forma di (Num_Points, C) + combined_features = combined_features.view(B*(self.num_views*(self.num_grid_points)+num_points), self.dim) + + + #mi tengo traccia di dove si trovano gli hub (mi servirà per quando poi farò la GNN) + ambs_per_batch = self.num_views * self.num_grid_points + anchors_per_batch = num_points + total_per_batch = ambs_per_batch + anchors_per_batch + + # In ogni batch, gli anchor sono negli ultimi `anchors_per_batch` elementi + anchor_indices = torch.arange(B).repeat_interleave(anchors_per_batch) * total_per_batch + anchor_indices += torch.arange(anchors_per_batch).repeat(B) + anchor_indices += ambs_per_batch + + if B2 == 1: + #creo gli indici per indicare a quale batch appartengono i vari nodi + chunk_len = edge_index.shape[1] // B + + # --- RIGA 0 --- + for i in range(B): + start = i * chunk_len + end = start + chunk_len + offset = i * (num_points) + edge_index[0, start:end] += offset + + # --- RIGA 1 --- + for i in range(B): + start = i * chunk_len + end = start + chunk_len + offset = self.num_grid_points*self.num_views if i == 0 else ((i+1) * self.num_grid_points*self.num_views + i*num_points) + edge_index[1, start:end] += offset + + if self.reverse_connection: + device = combined_features.device + edge_index = edge_index[[1, 0]] + mask = torch.ones(combined_features.size(0), dtype=torch.bool, device=device) + mask[anchor_indices] = False + anchor_indices = mask#torch.arange(combined_features.size(0), device=device)[mask] + + # Passa l'edge_index per l'attenzione a grafo (ritorna solo gli anchor) + anchors = self.attn1(self.norm1(combined_features, t), edge_index, anchor_indices) + combined_features[anchor_indices] + # x = self.attn2(self.norm2(x, t), edge_index) + x + anchors = self.ff(self.norm3(anchors, t)) + anchors + return anchors + + +class LocalGraphTransformer(nn.Module): + def __init__( + self, + in_channels, + n_heads, + d_head, + out_channels=None, + depth=1, + dropout=0.0, + # context_dim=None, + ): + super().__init__() + self.in_channels = in_channels + inner_dim = n_heads * d_head + + self.proj_in = nn.Linear(in_channels, inner_dim, bias=False) + + self.transformer_blocks = nn.ModuleList([ + BasicLocalGraphTransformerBlock( + inner_dim, + n_heads=n_heads, + d_head=d_head, + # context_dim=context_dim, + dropout=dropout, + ) + for _ in range(depth) + ]) + + out_channels = out_channels if out_channels is not None else in_channels + self.proj_out = nn.Linear(inner_dim, out_channels, bias=False) #zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + self.t_proj = nn.Linear(1280, inner_dim) + + def forward(self, x, t, edge_index, context=None, attention_mask=None): + x = self.proj_in(x) + t = self.t_proj(t).unsqueeze(1) + for block in self.transformer_blocks: + x = block(x, t, edge_index=edge_index, context=context, mask=attention_mask) + x = self.proj_out(x) + return x + + + +class GraphTransformer(nn.Module): + def __init__( + self, + in_channels, + n_heads, + d_head, + out_channels=None, + dropout=0.0, + num_grid_points = 1, + num_views = 1, + reverse_connection = False + ): + super().__init__() + self.in_channels = in_channels + inner_dim = n_heads * d_head + + self.ambassadors_proj_in = nn.Linear(in_channels, inner_dim, bias=False) + self.latents_proj_in = nn.Linear(in_channels, inner_dim, bias=False) + + self.transformer_block = BasicGraphTransformerBlock( + inner_dim, + n_heads=n_heads, + d_head=d_head, + # context_dim=context_dim, + dropout=dropout, + num_grid_points = num_grid_points, + num_views = num_views, + reverse_connection=reverse_connection + ) + + out_channels = out_channels if out_channels is not None else in_channels + self.proj_out = nn.Linear(inner_dim, out_channels, bias=False) #zero_module(nn.Linear(inner_dim, out_channels, bias=False)) + self.t_proj = nn.Linear(1280, inner_dim) + + def forward(self, ambassadors_features, latent_points, t, edge_index, context=None, attention_mask=None): + ambassadors_features = self.ambassadors_proj_in(ambassadors_features) + latent_points = self.latents_proj_in(latent_points) + t = self.t_proj(t) + updated_anchors = self.transformer_block(ambassadors_features, latent_points, t, edge_index=edge_index, context=context, mask=attention_mask) + updated_anchors = self.proj_out(updated_anchors) + return updated_anchors \ No newline at end of file diff --git a/loomnet/models/blocks/unet.py b/loomnet/models/blocks/unet.py new file mode 100644 index 0000000000000000000000000000000000000000..daf14d1f87d2766e846751ab304514bd088ea4d7 --- /dev/null +++ b/loomnet/models/blocks/unet.py @@ -0,0 +1,490 @@ +# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py + +import json +import os +from dataclasses import dataclass +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.utils.checkpoint +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.models.embeddings import TimestepEmbedding, Timesteps +from diffusers.models.modeling_utils import ModelMixin +from diffusers.utils import BaseOutput, logging + +from .unet_blocks import ( + CrossAttnDownBlock3D, + CrossAttnUpBlock3D, + DownBlock3D, + UNetMidBlock3DCrossAttn, + UpBlock3D, + get_down_block, + get_up_block, +) +from .unet_res3d import InflatedConv3d + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +@dataclass +class UNet3DConditionOutput(BaseOutput): + sample: torch.FloatTensor + + +class UNet3DConditionModel(ModelMixin, ConfigMixin): + _supports_gradient_checkpointing = True + + @register_to_config + def __init__( + self, + sample_size: Optional[int] = None, + in_channels: int = 4, + out_channels: int = 4, + center_input_sample: bool = False, + flip_sin_to_cos: bool = True, + freq_shift: int = 0, + down_block_types: Tuple[str] = ( + "CrossAttnDownBlock3D", + "CrossAttnDownBlock3D", + "CrossAttnDownBlock3D", + "DownBlock3D", + ), + mid_block_type: str = "UNetMidBlock3DCrossAttn", + up_block_types: Tuple[str] = ( + "UpBlock3D", + "CrossAttnUpBlock3D", + "CrossAttnUpBlock3D", + "CrossAttnUpBlock3D", + ), + only_cross_attention: Union[bool, Tuple[bool]] = False, + block_out_channels: Tuple[int] = (320, 640, 1280, 1280), + layers_per_block: int = 2, + downsample_padding: int = 1, + mid_block_scale_factor: float = 1, + act_fn: str = "silu", + norm_num_groups: int = 32, + norm_eps: float = 1e-5, + cross_attention_dim: int = 1280, + attention_head_dim: Union[int, Tuple[int]] = 8, + dual_cross_attention: bool = False, + use_linear_projection: bool = False, + class_embed_type: Optional[str] = None, + num_class_embeds: Optional[int] = None, + upcast_attention: bool = False, + resnet_time_scale_shift: str = "default", + ): + super().__init__() + + self.sample_size = sample_size + time_embed_dim = block_out_channels[0] * 4 + + # input + self.conv_in = InflatedConv3d( + in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1) + ) + + # time + self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) + timestep_input_dim = block_out_channels[0] + + self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) + + # class embedding + if class_embed_type is None and num_class_embeds is not None: + self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) + elif class_embed_type == "timestep": + self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) + elif class_embed_type == "identity": + self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) + else: + self.class_embedding = None + + self.down_blocks = nn.ModuleList([]) + self.mid_block = None + self.up_blocks = nn.ModuleList([]) + + if isinstance(only_cross_attention, bool): + only_cross_attention = [only_cross_attention] * len(down_block_types) + + if isinstance(attention_head_dim, int): + attention_head_dim = (attention_head_dim,) * len(down_block_types) + + # down + output_channel = block_out_channels[0] + for i, down_block_type in enumerate(down_block_types): + input_channel = output_channel + output_channel = block_out_channels[i] + is_final_block = i == len(block_out_channels) - 1 + + down_block = get_down_block( + down_block_type, + num_layers=layers_per_block, + in_channels=input_channel, + out_channels=output_channel, + temb_channels=time_embed_dim, + add_downsample=not is_final_block, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + resnet_groups=norm_num_groups, + cross_attention_dim=cross_attention_dim, + attn_num_head_channels=attention_head_dim[i], + downsample_padding=downsample_padding, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention[i], + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + self.down_blocks.append(down_block) + + # mid + if mid_block_type == "UNetMidBlock3DCrossAttn": + self.mid_block = UNetMidBlock3DCrossAttn( + in_channels=block_out_channels[-1], + temb_channels=time_embed_dim, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + output_scale_factor=mid_block_scale_factor, + resnet_time_scale_shift=resnet_time_scale_shift, + cross_attention_dim=cross_attention_dim, + attn_num_head_channels=attention_head_dim[-1], + resnet_groups=norm_num_groups, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + upcast_attention=upcast_attention, + ) + else: + raise ValueError(f"unknown mid_block_type : {mid_block_type}") + + # count how many layers upsample the videos + self.num_upsamplers = 0 + + # up + reversed_block_out_channels = list(reversed(block_out_channels)) + reversed_attention_head_dim = list(reversed(attention_head_dim)) + only_cross_attention = list(reversed(only_cross_attention)) + output_channel = reversed_block_out_channels[0] + for i, up_block_type in enumerate(up_block_types): + is_final_block = i == len(block_out_channels) - 1 + + prev_output_channel = output_channel + output_channel = reversed_block_out_channels[i] + input_channel = reversed_block_out_channels[ + min(i + 1, len(block_out_channels) - 1) + ] + + # add upsample block for all BUT final layer + if not is_final_block: + add_upsample = True + self.num_upsamplers += 1 + else: + add_upsample = False + + up_block = get_up_block( + up_block_type, + num_layers=layers_per_block + 1, + in_channels=input_channel, + out_channels=output_channel, + prev_output_channel=prev_output_channel, + temb_channels=time_embed_dim, + add_upsample=add_upsample, + resnet_eps=norm_eps, + resnet_act_fn=act_fn, + resnet_groups=norm_num_groups, + cross_attention_dim=cross_attention_dim, + attn_num_head_channels=reversed_attention_head_dim[i], + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention[i], + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + self.up_blocks.append(up_block) + prev_output_channel = output_channel + + # out + self.conv_norm_out = nn.GroupNorm( + num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps + ) + self.conv_act = nn.SiLU() + self.conv_out = InflatedConv3d( + block_out_channels[0], out_channels, kernel_size=3, padding=1 + ) + + def set_attention_slice(self, slice_size): + r""" + Enable sliced attention computation. + + When this option is enabled, the attention module will split the input tensor in slices, to compute attention + in several steps. This is useful to save some memory in exchange for a small speed decrease. + + Args: + slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): + When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If + `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is + provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` + must be a multiple of `slice_size`. + """ + sliceable_head_dims = [] + + def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module): + if hasattr(module, "set_attention_slice"): + sliceable_head_dims.append(module.sliceable_head_dim) + + for child in module.children(): + fn_recursive_retrieve_slicable_dims(child) + + # retrieve number of attention layers + for module in self.children(): + fn_recursive_retrieve_slicable_dims(module) + + num_slicable_layers = len(sliceable_head_dims) + + if slice_size == "auto": + # half the attention head size is usually a good trade-off between + # speed and memory + slice_size = [dim // 2 for dim in sliceable_head_dims] + elif slice_size == "max": + # make smallest slice possible + slice_size = num_slicable_layers * [1] + + slice_size = ( + num_slicable_layers * [slice_size] + if not isinstance(slice_size, list) + else slice_size + ) + + if len(slice_size) != len(sliceable_head_dims): + raise ValueError( + f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" + f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." + ) + + for i in range(len(slice_size)): + size = slice_size[i] + dim = sliceable_head_dims[i] + if size is not None and size > dim: + raise ValueError(f"size {size} has to be smaller or equal to {dim}.") + + # Recursively walk through all the children. + # Any children which exposes the set_attention_slice method + # gets the message + def fn_recursive_set_attention_slice( + module: torch.nn.Module, slice_size: List[int] + ): + if hasattr(module, "set_attention_slice"): + module.set_attention_slice(slice_size.pop()) + + for child in module.children(): + fn_recursive_set_attention_slice(child, slice_size) + + reversed_slice_size = list(reversed(slice_size)) + for module in self.children(): + fn_recursive_set_attention_slice(module, reversed_slice_size) + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance( + module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D) + ): + module.gradient_checkpointing = value + + def forward( + self, + sample: torch.FloatTensor, + timestep: Union[torch.Tensor, float, int], + encoder_hidden_states: torch.Tensor, + class_labels: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + return_dict: bool = True, + ) -> Union[UNet3DConditionOutput, Tuple]: + r""" + Args: + sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor + timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps + encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple. + + Returns: + [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`: + [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When + returning a tuple, the first element is the sample tensor. + """ + # By default samples have to be AT least a multiple of the overall upsampling factor. + # The overall upsampling factor is equal to 2 ** (# num of upsampling layears). + # However, the upsampling interpolation output size can be forced to fit any upsampling size + # on the fly if necessary. + default_overall_up_factor = 2**self.num_upsamplers + + # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor` + forward_upsample_size = False + upsample_size = None + + if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]): + logger.info("Forward upsample size to force interpolation output size.") + forward_upsample_size = True + + # prepare attention_mask + if attention_mask is not None: + attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0 + attention_mask = attention_mask.unsqueeze(1) + + # center input if necessary + if self.config.center_input_sample: + sample = 2 * sample - 1.0 + + # time + timesteps = timestep + if not torch.is_tensor(timesteps): + # This would be a good case for the `match` statement (Python 3.10+) + is_mps = sample.device.type == "mps" + if isinstance(timestep, float): + dtype = torch.float32 if is_mps else torch.float64 + else: + dtype = torch.int32 if is_mps else torch.int64 + timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) + elif len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + t_emb = self.time_proj(timesteps) + + # timesteps does not contain any weights and will always return f32 tensors + # but time_embedding might actually be running in fp16. so we need to cast here. + # there might be better ways to encapsulate this. + t_emb = t_emb.to(dtype=self.dtype) + emb = self.time_embedding(t_emb) + + if self.class_embedding is not None: + if class_labels is None: + raise ValueError( + "class_labels should be provided when num_class_embeds > 0" + ) + + if self.config.class_embed_type == "timestep": + class_labels = self.time_proj(class_labels) + + class_emb = self.class_embedding(class_labels).to(dtype=self.dtype) + emb = emb + class_emb + + # pre-process + sample = self.conv_in(sample) + + # down + down_block_res_samples = (sample,) + for downsample_block in self.down_blocks: + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + sample, res_samples = downsample_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + ) + else: + sample, res_samples = downsample_block(hidden_states=sample, temb=emb) + + down_block_res_samples += res_samples + + # mid + sample = self.mid_block( + sample, + emb, + encoder_hidden_states=encoder_hidden_states, + attention_mask=attention_mask, + ) + + # up + for i, upsample_block in enumerate(self.up_blocks): + is_final_block = i == len(self.up_blocks) - 1 + + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + # if we have not reached the final block and need to forward the + # upsample size, we do it here + if not is_final_block and forward_upsample_size: + upsample_size = down_block_res_samples[-1].shape[2:] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + encoder_hidden_states=encoder_hidden_states, + upsample_size=upsample_size, + attention_mask=attention_mask, + ) + else: + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + upsample_size=upsample_size, + ) + # post-process + sample = self.conv_norm_out(sample) + sample = self.conv_act(sample) + sample = self.conv_out(sample) + + if not return_dict: + return (sample,) + + return UNet3DConditionOutput(sample=sample) + + @classmethod + def from_pretrained_2d(cls, pretrained_model_path, subfolder=None): + if subfolder is not None: + pretrained_model_path = os.path.join(pretrained_model_path, subfolder) + + config_file = os.path.join(pretrained_model_path, "config.json") + if not os.path.isfile(config_file): + raise RuntimeError(f"{config_file} does not exist") + with open(config_file, "r") as f: + config = json.load(f) + config["_class_name"] = cls.__name__ + config["down_block_types"] = [ + "CrossAttnDownBlock3D", + "CrossAttnDownBlock3D", + "CrossAttnDownBlock3D", + "DownBlock3D", + ] + config["up_block_types"] = [ + "UpBlock3D", + "CrossAttnUpBlock3D", + "CrossAttnUpBlock3D", + "CrossAttnUpBlock3D", + ] + config["mid_block_type"] = "UNetMidBlock3DCrossAttn" + + from diffusers.utils import WEIGHTS_NAME + + model = cls.from_config(config) + model_file = os.path.join( + pretrained_model_path, "diffusion_pytorch_model.fp16_ema.safetensors" + ) + if not os.path.isfile(model_file): + raise RuntimeError(f"{model_file} does not exist") + + import safetensors + + state_dict = safetensors.torch.load_file(model_file, device="cpu") + # for k, v in model.state_dict().items(): + # if '_ip.' in k: + # state_dict.update({k: v}) + # new_weights = torch.zeros_like(model.conv_in.weight) + # new_weights[:, :4] = state_dict["conv_in.weight"] + # state_dict.update({"conv_in.weight": new_weights}) + # model.load_state_dict(state_dict) + model.load_state_dict(state_dict) + return model diff --git a/loomnet/models/blocks/unet_blocks.py b/loomnet/models/blocks/unet_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..2222c4909e2e29e85e650c6dc015cf71ddc05c3d --- /dev/null +++ b/loomnet/models/blocks/unet_blocks.py @@ -0,0 +1,632 @@ +# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py + +import torch +from torch import nn + +from .attention import Transformer3DModel +from .unet_res3d import Downsample3D, ResnetBlock3D, Upsample3D + + +def get_down_block( + down_block_type, + num_layers, + in_channels, + out_channels, + temb_channels, + add_downsample, + resnet_eps, + resnet_act_fn, + attn_num_head_channels, + resnet_groups=None, + cross_attention_dim=None, + downsample_padding=None, + dual_cross_attention=False, + use_linear_projection=False, + only_cross_attention=False, + upcast_attention=False, + resnet_time_scale_shift="default", +): + down_block_type = ( + down_block_type[7:] + if down_block_type.startswith("UNetRes") + else down_block_type + ) + if down_block_type == "DownBlock3D": + return DownBlock3D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif down_block_type == "CrossAttnDownBlock3D": + if cross_attention_dim is None: + raise ValueError( + "cross_attention_dim must be specified for CrossAttnDownBlock3D" + ) + return CrossAttnDownBlock3D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + add_downsample=add_downsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + downsample_padding=downsample_padding, + cross_attention_dim=cross_attention_dim, + attn_num_head_channels=attn_num_head_channels, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + raise ValueError(f"{down_block_type} does not exist.") + + +def get_up_block( + up_block_type, + num_layers, + in_channels, + out_channels, + prev_output_channel, + temb_channels, + add_upsample, + resnet_eps, + resnet_act_fn, + attn_num_head_channels, + resnet_groups=None, + cross_attention_dim=None, + dual_cross_attention=False, + use_linear_projection=False, + only_cross_attention=False, + upcast_attention=False, + resnet_time_scale_shift="default", +): + up_block_type = ( + up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type + ) + if up_block_type == "UpBlock3D": + return UpBlock3D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + elif up_block_type == "CrossAttnUpBlock3D": + if cross_attention_dim is None: + raise ValueError( + "cross_attention_dim must be specified for CrossAttnUpBlock3D" + ) + return CrossAttnUpBlock3D( + num_layers=num_layers, + in_channels=in_channels, + out_channels=out_channels, + prev_output_channel=prev_output_channel, + temb_channels=temb_channels, + add_upsample=add_upsample, + resnet_eps=resnet_eps, + resnet_act_fn=resnet_act_fn, + resnet_groups=resnet_groups, + cross_attention_dim=cross_attention_dim, + attn_num_head_channels=attn_num_head_channels, + dual_cross_attention=dual_cross_attention, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + resnet_time_scale_shift=resnet_time_scale_shift, + ) + raise ValueError(f"{up_block_type} does not exist.") + + +class UNetMidBlock3DCrossAttn(nn.Module): + def __init__( + self, + in_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attn_num_head_channels=1, + output_scale_factor=1.0, + cross_attention_dim=1280, + dual_cross_attention=False, + use_linear_projection=False, + upcast_attention=False, + ): + super().__init__() + + self.has_cross_attention = True + self.attn_num_head_channels = attn_num_head_channels + resnet_groups = ( + resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) + ) + + # there is always at least one resnet + resnets = [ + ResnetBlock3D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ] + attentions = [] + + for _ in range(num_layers): + if dual_cross_attention: + raise NotImplementedError + attentions.append( + Transformer3DModel( + attn_num_head_channels, + in_channels // attn_num_head_channels, + in_channels=in_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + upcast_attention=upcast_attention, + ) + ) + resnets.append( + ResnetBlock3D( + in_channels=in_channels, + out_channels=in_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + def forward( + self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None + ): + hidden_states = self.resnets[0](hidden_states, temb) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + hidden_states = attn( + hidden_states, encoder_hidden_states=encoder_hidden_states + ).sample + hidden_states = resnet(hidden_states, temb) + + return hidden_states + + +class CrossAttnDownBlock3D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attn_num_head_channels=1, + cross_attention_dim=1280, + output_scale_factor=1.0, + downsample_padding=1, + add_downsample=True, + dual_cross_attention=False, + use_linear_projection=False, + only_cross_attention=False, + upcast_attention=False, + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.attn_num_head_channels = attn_num_head_channels + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock3D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + if dual_cross_attention: + raise NotImplementedError + attentions.append( + Transformer3DModel( + attn_num_head_channels, + out_channels // attn_num_head_channels, + in_channels=out_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + ) + ) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample3D( + out_channels, + use_conv=True, + out_channels=out_channels, + padding=downsample_padding, + name="op", + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None + ): + output_states = () + + for resnet, attn in zip(self.resnets, self.attentions): + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(attn, return_dict=False), + hidden_states, + encoder_hidden_states, + )[0] + else: + hidden_states = resnet(hidden_states, temb) + hidden_states = attn( + hidden_states, encoder_hidden_states=encoder_hidden_states + ).sample + + output_states += (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states) + + output_states += (hidden_states,) + + return hidden_states, output_states + + +class DownBlock3D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor=1.0, + add_downsample=True, + downsample_padding=1, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + in_channels = in_channels if i == 0 else out_channels + resnets.append( + ResnetBlock3D( + in_channels=in_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_downsample: + self.downsamplers = nn.ModuleList( + [ + Downsample3D( + out_channels, + use_conv=True, + out_channels=out_channels, + padding=downsample_padding, + name="op", + ) + ] + ) + else: + self.downsamplers = None + + self.gradient_checkpointing = False + + def forward(self, hidden_states, temb=None): + output_states = () + + for resnet in self.resnets: + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb) + + output_states += (hidden_states,) + + if self.downsamplers is not None: + for downsampler in self.downsamplers: + hidden_states = downsampler(hidden_states) + + output_states += (hidden_states,) + + return hidden_states, output_states + + +class CrossAttnUpBlock3D(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + prev_output_channel: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + attn_num_head_channels=1, + cross_attention_dim=1280, + output_scale_factor=1.0, + add_upsample=True, + dual_cross_attention=False, + use_linear_projection=False, + only_cross_attention=False, + upcast_attention=False, + ): + super().__init__() + resnets = [] + attentions = [] + + self.has_cross_attention = True + self.attn_num_head_channels = attn_num_head_channels + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock3D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + if dual_cross_attention: + raise NotImplementedError + attentions.append( + Transformer3DModel( + attn_num_head_channels, + out_channels // attn_num_head_channels, + in_channels=out_channels, + num_layers=1, + cross_attention_dim=cross_attention_dim, + norm_num_groups=resnet_groups, + use_linear_projection=use_linear_projection, + only_cross_attention=only_cross_attention, + upcast_attention=upcast_attention, + ) + ) + + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList( + [Upsample3D(out_channels, use_conv=True, out_channels=out_channels)] + ) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states, + res_hidden_states_tuple, + temb=None, + encoder_hidden_states=None, + upsample_size=None, + attention_mask=None, + ): + for resnet, attn in zip(self.resnets, self.attentions): + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module, return_dict=None): + def custom_forward(*inputs): + if return_dict is not None: + return module(*inputs, return_dict=return_dict) + else: + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(attn, return_dict=False), + hidden_states, + encoder_hidden_states, + )[0] + else: + hidden_states = resnet(hidden_states, temb) + hidden_states = attn( + hidden_states, encoder_hidden_states=encoder_hidden_states + ).sample + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, upsample_size) + + return hidden_states + + +class UpBlock3D(nn.Module): + def __init__( + self, + in_channels: int, + prev_output_channel: int, + out_channels: int, + temb_channels: int, + dropout: float = 0.0, + num_layers: int = 1, + resnet_eps: float = 1e-6, + resnet_time_scale_shift: str = "default", + resnet_act_fn: str = "swish", + resnet_groups: int = 32, + resnet_pre_norm: bool = True, + output_scale_factor=1.0, + add_upsample=True, + ): + super().__init__() + resnets = [] + + for i in range(num_layers): + res_skip_channels = in_channels if (i == num_layers - 1) else out_channels + resnet_in_channels = prev_output_channel if i == 0 else out_channels + + resnets.append( + ResnetBlock3D( + in_channels=resnet_in_channels + res_skip_channels, + out_channels=out_channels, + temb_channels=temb_channels, + eps=resnet_eps, + groups=resnet_groups, + dropout=dropout, + time_embedding_norm=resnet_time_scale_shift, + non_linearity=resnet_act_fn, + output_scale_factor=output_scale_factor, + pre_norm=resnet_pre_norm, + ) + ) + + self.resnets = nn.ModuleList(resnets) + + if add_upsample: + self.upsamplers = nn.ModuleList( + [Upsample3D(out_channels, use_conv=True, out_channels=out_channels)] + ) + else: + self.upsamplers = None + + self.gradient_checkpointing = False + + def forward( + self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None + ): + for resnet in self.resnets: + # pop res hidden states + res_hidden_states = res_hidden_states_tuple[-1] + res_hidden_states_tuple = res_hidden_states_tuple[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + + if self.training and self.gradient_checkpointing: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs) + + return custom_forward + + hidden_states = torch.utils.checkpoint.checkpoint( + create_custom_forward(resnet), hidden_states, temb + ) + else: + hidden_states = resnet(hidden_states, temb) + + if self.upsamplers is not None: + for upsampler in self.upsamplers: + hidden_states = upsampler(hidden_states, upsample_size) + + return hidden_states \ No newline at end of file diff --git a/loomnet/models/blocks/unet_res3d.py b/loomnet/models/blocks/unet_res3d.py new file mode 100644 index 0000000000000000000000000000000000000000..de6663f4d87dbb89c09e8744a7bde423f7d8ac84 --- /dev/null +++ b/loomnet/models/blocks/unet_res3d.py @@ -0,0 +1,247 @@ +# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + + +class InflatedConv3d(nn.Conv2d): + def forward(self, x): + video_length = x.shape[2] + + x = rearrange(x, "b c f h w -> (b f) c h w") + x = super().forward(x) + x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length) + + return x + + +class Upsample3D(nn.Module): + def __init__( + self, + channels, + use_conv=False, + use_conv_transpose=False, + out_channels=None, + name="conv", + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.use_conv_transpose = use_conv_transpose + self.name = name + + conv = None + if use_conv_transpose: + raise NotImplementedError + elif use_conv: + conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1) + + if name == "conv": + self.conv = conv + else: + self.Conv2d_0 = conv + + def forward( + self, + hidden_states, + output_size=None, + cameras=None, + camera_ids=None, + ): + assert hidden_states.shape[1] == self.channels + + if self.use_conv_transpose: + raise NotImplementedError + + # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16 + dtype = hidden_states.dtype + if dtype == torch.bfloat16: + hidden_states = hidden_states.to(torch.float32) + + # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984 + if hidden_states.shape[0] >= 64: + hidden_states = hidden_states.contiguous() + + # if `output_size` is passed we force the interpolation output + # size and do not make use of `scale_factor=2` + if output_size is None: + hidden_states = F.interpolate( + hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest" + ) + else: + hidden_states = F.interpolate( + hidden_states, size=output_size, mode="nearest" + ) + + # If the input is bfloat16, we cast back to bfloat16 + if dtype == torch.bfloat16: + hidden_states = hidden_states.to(dtype) + + if self.use_conv: + if self.name == "conv": + hidden_states = self.conv(hidden_states) + else: + hidden_states = self.Conv2d_0(hidden_states) + + return hidden_states + + +class Downsample3D(nn.Module): + def __init__( + self, channels, use_conv=False, out_channels=None, padding=1, name="conv" + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.padding = padding + stride = 2 + self.name = name + + if use_conv: + conv = InflatedConv3d( + self.channels, self.out_channels, 3, stride=stride, padding=padding + ) + else: + raise NotImplementedError + + if name == "conv": + self.Conv2d_0 = conv + self.conv = conv + elif name == "Conv2d_0": + self.conv = conv + else: + self.conv = conv + + def forward(self, hidden_states): + assert hidden_states.shape[1] == self.channels + if self.use_conv and self.padding == 0: + raise NotImplementedError + + assert hidden_states.shape[1] == self.channels + hidden_states = self.conv(hidden_states) + + return hidden_states + + +class ResnetBlock3D(nn.Module): + def __init__( + self, + *, + in_channels, + out_channels=None, + conv_shortcut=False, + dropout=0.0, + temb_channels=512, + groups=32, + groups_out=None, + pre_norm=True, + eps=1e-6, + non_linearity="swish", + time_embedding_norm="default", + output_scale_factor=1.0, + use_in_shortcut=None, + ): + super().__init__() + self.pre_norm = pre_norm + self.pre_norm = True + self.in_channels = in_channels + out_channels = in_channels if out_channels is None else out_channels + self.out_channels = out_channels + self.use_conv_shortcut = conv_shortcut + self.time_embedding_norm = time_embedding_norm + self.output_scale_factor = output_scale_factor + + if groups_out is None: + groups_out = groups + + self.norm1 = torch.nn.GroupNorm( + num_groups=groups, num_channels=in_channels, eps=eps, affine=True + ) + + self.conv1 = InflatedConv3d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + + if temb_channels is not None: + if self.time_embedding_norm == "default": + time_emb_proj_out_channels = out_channels + elif self.time_embedding_norm == "scale_shift": + time_emb_proj_out_channels = out_channels * 2 + else: + raise ValueError( + f"unknown time_embedding_norm : {self.time_embedding_norm} " + ) + + self.time_emb_proj = torch.nn.Linear( + temb_channels, time_emb_proj_out_channels + ) + else: + self.time_emb_proj = None + + self.norm2 = torch.nn.GroupNorm( + num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True + ) + self.dropout = torch.nn.Dropout(dropout) + self.conv2 = InflatedConv3d( + out_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + + if non_linearity == "swish": + self.nonlinearity = lambda x: F.silu(x) + elif non_linearity == "mish": + self.nonlinearity = Mish() + elif non_linearity == "silu": + self.nonlinearity = nn.SiLU() + + self.use_in_shortcut = ( + self.in_channels != self.out_channels + if use_in_shortcut is None + else use_in_shortcut + ) + + self.conv_shortcut = None + if self.use_in_shortcut: + self.conv_shortcut = InflatedConv3d( + in_channels, out_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, input_tensor, temb): + hidden_states = input_tensor + + hidden_states = self.norm1(hidden_states) + hidden_states = self.nonlinearity(hidden_states) + + hidden_states = self.conv1(hidden_states) + + if temb is not None: + temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None] + + if temb is not None and self.time_embedding_norm == "default": + hidden_states = hidden_states + temb + + hidden_states = self.norm2(hidden_states) + + if temb is not None and self.time_embedding_norm == "scale_shift": + scale, shift = torch.chunk(temb, 2, dim=1) + hidden_states = hidden_states * (1 + scale) + shift + + hidden_states = self.nonlinearity(hidden_states) + + hidden_states = self.dropout(hidden_states) + hidden_states = self.conv2(hidden_states) + + if self.conv_shortcut is not None: + input_tensor = self.conv_shortcut(input_tensor) + + output_tensor = (input_tensor + hidden_states) / self.output_scale_factor + + return output_tensor + + +class Mish(torch.nn.Module): + def forward(self, hidden_states): + return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states)) diff --git a/loomnet/models/extras/__init__.py b/loomnet/models/extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loomnet/models/extras/__pycache__/__init__.cpython-311.pyc b/loomnet/models/extras/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..702cb5ab0200156e20915300495cecb2976b0227 Binary files /dev/null and b/loomnet/models/extras/__pycache__/__init__.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..153f89e1bb9f528611534d22879b184b367cb30b Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_1_to_infinity.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_1_to_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb040d3d5bf41c8b6eeff003ff471fad75bc79a5 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_1_to_infinity.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_global.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_global.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ca03181eb331522bf6be906935b5e156dfeb87f Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_global.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_infinity.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae96144366bac8ba4d4e6ae9ca823addfbcf8fd7 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_infinity.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_triplane.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_triplane.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d9951350bbd6b67d8c494769ff810f152386679 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_triplane.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_triplane_with_3d_conv.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_triplane_with_3d_conv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67d6d000c53e8fe569558cac2b510d7b92911a41 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_triplane_with_3d_conv.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_v10.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_v10.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e0dd4881e835a893a14399f41c77eea68c6faf8 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_v10.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_v12.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_v12.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92c0e3e68465fa9ae1b48e52af2da1fb48c59eb3 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_v12.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_v4.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_v4.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4283145a76bf5884ce4ffb1ba0b563c7062e4e8 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_v4.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_v7.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_v7.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..394feab425c6c530743e1f8cf151d753fe6b4a14 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_v7.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_v8.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_v8.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0fc95065ddebd26638fbdf4530066113e437f4e Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_v8.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_with_distillation.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_with_distillation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0185f0310b1b477c9eeb43f60879d8613474892 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_with_distillation.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/feature_aggregator_with_projection.cpython-311.pyc b/loomnet/models/extras/__pycache__/feature_aggregator_with_projection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16219dd37392391e6aca51ca7a6c5d5deaf37f99 Binary files /dev/null and b/loomnet/models/extras/__pycache__/feature_aggregator_with_projection.cpython-311.pyc differ diff --git a/loomnet/models/extras/__pycache__/geometric_loss.cpython-311.pyc b/loomnet/models/extras/__pycache__/geometric_loss.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cdbc4d2fb1648ca610184c79a5c0d373f14f4f5 Binary files /dev/null and b/loomnet/models/extras/__pycache__/geometric_loss.cpython-311.pyc differ diff --git a/loomnet/models/extras/feature_aggregator_1_to_infinity.py b/loomnet/models/extras/feature_aggregator_1_to_infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b249d75bc56ebd413f4a18416679bd7551c9e3 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_1_to_infinity.py @@ -0,0 +1,1198 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +# class OSGDecoder(nn.Module): +# """ +# Triplane decoder that gives RGB and sigma values from sampled features. +# Using ReLU here instead of Softplus in the original implementation. + +# Reference: +# EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 +# """ +# def __init__(self, n_features: int, +# hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.GELU): +# super().__init__() +# self.net = nn.Sequential( +# nn.Linear(n_features, hidden_dim), +# activation(), +# *itertools.chain(*[[ +# nn.Linear(hidden_dim, hidden_dim), +# nn.LayerNorm(hidden_dim), +# activation(), +# ] for _ in range(num_layers - 2)]), +# nn.Linear(hidden_dim, hidden_dim), +# ) + +# self.to_feature = nn.Linear(hidden_dim, out_dim) +# self.to_sigma = nn.Linear(hidden_dim, 1) + +# # init all bias to zero +# for m in self.modules(): +# if isinstance(m, nn.Linear): +# nn.init.zeros_(m.bias) + +# #sampled_features: (Num_points, 96) +# @torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) +# def forward(self, sampled_features): +# hidden = self.net(sampled_features) + +# f = self.to_feature(hidden) +# sigma = nn.Softplus()(self.to_sigma(hidden)) + +# return f, sigma + + + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolution: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True, + num_views_latent_space: int = 16 + ): + super().__init__() + + self.num_views = num_views-1 + self.num_views_latent_space = num_views_latent_space + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.use_positional_encoding = use_positional_encoding + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + self.splat_plane_resolution = splat_plane_resolution + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.do_latent_rendering: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + #TODO rimuovi il concetto di positional encoding che non è più quello del classico loomnet + self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim if self.use_positional_encoding else self.latent_dim_embedding), hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(torch.cat([global_features, local_xyz_probes_position_embedding.reshape(B, -1, self.ray_embedding_dim + self.ray_sample_embedding_dim)], dim=-1)) + + # #__________________AGGREGATE RAY SAMPLES____________________ + # #[Num_Rays, Num_Samples, C]) + # decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + # decoded_sampled_sigmas = decoded_sampled_sigmas.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, 1) + # sample_depths = sample_depths.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, 1) + + # #________________ LATENT ALPHA COMPOSITING_____________________ + # # Calcolo la distanza tra sample successivi lungo il raggio + # deltas = sample_depths[:, 1:, :] - sample_depths[:, :-1, :] + # deltas = torch.cat([deltas, deltas[:,-1:,:]], dim=1) + # # Converti sigma in alpha: alpha = 1 - exp(-sigma * delta) + # alpha = 1.0 - torch.exp(-decoded_sampled_sigmas * deltas) + # # Cumulative product for transmittance + # eps = 1e-10 # per stabilità numerica + # cumprod = torch.cumprod(1.0 - alpha + eps, dim=1) + # transmittance = torch.cat([torch.ones_like(cumprod[:, :1, :]), cumprod[:, :-1, :]], dim=1) + + # # Final weights: w = alpha * T + # weights = alpha * transmittance # [Num_Rays, Num_Samples, 1] + # # Weighted sum delle feature lungo i raggi + # updated_feature_map = torch.sum(weights * decoded_sampled_features, dim=1) # [Num_Rays, C] + + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3), planes if self.latent_dim == 32 else x + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_epidiff.py b/loomnet/models/extras/feature_aggregator_epidiff.py new file mode 100644 index 0000000000000000000000000000000000000000..d692cffc12af2bf3229783f4c377bf38fe665f54 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_epidiff.py @@ -0,0 +1,164 @@ +# https://github.com/zhizdev/sparsefusion/blob/main/sparsefusion/eft.py +import os +from typing import List + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t_old import ( + AdaLayerNorm, + CrossAttention, + Transformer, +) + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + depth: int = 1, + embed_dim: int = 0, + use_resnet: bool = True, + use_fhw_attn: bool = False, + pos_encs: List[str] = ["abs", "ref"], + ): + super().__init__() + + self.use_resnet = use_resnet + self.use_fhw_attn = use_fhw_attn + self.pos_encs = pos_encs + + # prepare model + self.t1_point_fc = nn.Linear(dim, 1, bias=False) + d_head = 64 + n_heads = dim // d_head + + # feature extract -> t1 -> t2 -> t3 (n s) (n k) (n) + self.T1 = Transformer( + in_channels=dim + len(pos_encs) * (embed_dim + 13), + context_dim=dim + len(pos_encs) * (embed_dim + 13), + # in_channels=dim, + out_channels=dim, + n_heads=n_heads, + d_head=d_head, + depth=depth, + ) + + if use_resnet: + self.resnet1 = ResBlock(dim, 1280, use_scale_shift_norm=True) + if use_fhw_attn: + self.HW = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head) + self.norm = AdaLayerNorm(dim) + self.t_proj = nn.Linear(1280, dim) + + def forward( + self, + images, + projected_points, + mask, + query_plucker, + reference_plucker, + f_views, + t_emb, + ): + """ + images: (B, F, C, H, W) + projected_points: (B, F, K, N, PTS_PER_RAY, 2) + return: + images: (B, F, C, H, W) + T1: (NUM_INPUT_CAM, N, PTS_PER_RAY, FEATURE_DIM) -> (NUM_INPUT_CAM, (N * PTS_PER_RAY), FEATURE_DIM) + T2: (NUM_INPUT_CAM, N, PTS_PER_RAY, FEATURE_DIM) -> (PT_PER_RAY, (NUM_INPUT_CAM * N), FEATURE_DIM) + T2_W: (NUM_INPUT_CAMERAS, N, PTS_PER_RAY, FEATURE_DIM) -> (PT_PER_RAY, N, 1, FEATURE_DIM) + """ + bf, c, h, w = images.shape + if t_emb.shape[0] != bf: + t_emb = repeat(t_emb, "b c -> (b f) c", f=f_views) # + if self.use_resnet: + images = self.resnet1(images, t_emb) + images = rearrange(images, "(b f) c h w -> (b f) h w c", f=f_views) + + n_sample = projected_points.shape[-2] + k_views = projected_points.shape[2] + # save projected_points ((batch*num_views*k_near_views, num_rays, num_points, x, y)) + projected_points = rearrange(projected_points, "b f k n s j -> (b f k) n s j") + feature_map = repeat( + images, "(b f) h w c-> (b f k) c h w", k=k_views, f=f_views + ) + + feature_sampled = F.grid_sample( + feature_map, + projected_points[..., [1, 0]], + align_corners=True, + padding_mode="border", + ) # (B x F x K, C, H x W, N_samples) + + feature_sampled = rearrange( + feature_sampled, + "(b f k) c n s -> b f k n s c", + f=f_views, + k=k_views, + ) + # check nan in feature_sampled + # assert torch.isnan(feature_sampled).sum() == 0 + # exchange information among sampled points which in the same view + t1 = feature_sampled + + if "abs" in self.pos_encs: + t1 = torch.cat((t1, query_plucker), dim=-1) + if "ref" in self.pos_encs: + t1 = torch.cat((t1, reference_plucker), dim=-1) + + #ogni riga mi dice per un raggio i (prima dimensione) a quale view ci stiamo riferendo (seconda dimensione) a quale punto del raggio (terza dimensione) e tutto l'encoding di quel punto (tutta la quarta dimensione) dopo il campionamento + t1 = rearrange(t1, "b f k n s c -> (b f n) k s c") + t1 = t1.to(images.dtype) + + #query: (num_rays, mother_view=1, num_points, activated_embedding) identico a t1, ma stavolta ogni raggio (prima dimensione) fa sempre riferimento alla camera madre + #context: (num_rays, k_near_views-1, num_points, activated_embedding) identico a t1, ma stavolta ogni raggio (prima dimensione) si riferisce solo a uno dei vicini (seconda dimensione) + query, context = t1.split([1, k_views - 1], dim=1) # bfn 1 s c bfn k-1 s c + mask = rearrange(mask, "b f k n s -> (b f n) k s") + #mask: (num_rays, k_near_views-1, num_points) per ogni raggio (prima dimensione) indica della view vicina (seconda dimensione) se un punto (terza dimensione) della madre viene visto dalla vicina + mask = mask[:, 1:] + + #(num_mother_rays, num_points, activated_embedding ) + query = rearrange(query, "bfn 1 s c -> bfn s c") + #(num_rays, tutti i punti su quel raggio di tutti i vicini, activated_embedding) + context = rearrange(context, "bfn k s c -> bfn (k s) c") + #(num_rays, time_embedding) + t_emb = repeat(t_emb, "bf c -> (bf n) c", n=h * w) + out = self.T1(query, t=t_emb, context=context, attention_mask=mask) + + mask = ( + reduce( + mask, + "bfn k s -> bfn s 1", + "sum", + ) + > 0 + ) + weight = self.t1_point_fc(out) + weight = weight.masked_fill(~mask, torch.finfo(weight.dtype).min) + weight = F.softmax(weight, dim=1) + t1 = torch.sum(out * weight, dim=1) + images = rearrange(t1, "(bf h w) c -> bf c h w", bf=bf, h=h, w=w) + + if self.use_fhw_attn: + hw = rearrange(images, "(b f) c h w -> b (f h w) c", f=f_views) + t_emb = rearrange(t_emb, "(b f n) c -> b (f n) c", f=f_views, n=h * w) + t_emb = self.t_proj(t_emb) + hw = self.HW(self.norm(hw, t_emb)) + hw + + images = rearrange(hw, "b (f h w) c -> (b f) c h w", f=f_views, h=h, w=w) + + images = rearrange(images, "bf c h w -> (bf h w) c") + images = rearrange( + # hw, + t1, + "(b f h w) c -> (b f) c h w", + h=h, + w=w, + f=f_views, + ) + return images diff --git a/loomnet/models/extras/feature_aggregator_global.py b/loomnet/models/extras/feature_aggregator_global.py new file mode 100644 index 0000000000000000000000000000000000000000..ee980962f710bd6b27dd7d769cd409ed71479d50 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_global.py @@ -0,0 +1,1224 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class ResUpBlock(nn.Module): + def __init__(self, in_channels, out_channels): + super().__init__() + self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1) + self.norm1 = nn.GroupNorm(32, out_channels) + self.act = nn.SiLU() + self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1) + self.norm2 = nn.GroupNorm(32, out_channels) + self.upsample = nn.ConvTranspose2d(out_channels, out_channels, 4, stride=2, padding=1) + self.skip = nn.Conv2d(in_channels, out_channels, 1) + + def forward(self, x): + identity = self.skip(x) + x = self.act(self.norm1(self.conv1(x))) + x = self.norm2(self.conv2(x)) + identity + x = self.act(x) + x = self.upsample(x) + return x + + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0., plane_res: int = 32): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + self.xy_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.yz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.xz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + + self.xy_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.yz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.xz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [B, num_tokens, D] + # XY: [B, num_views, num_tokens, D_cond] + # YZ: [B, num_views, num_tokens, D_cond] + # YZ: [B, num_views, num_tokens, D_cond] + # mod: [B, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + #positional encoding + query_xy_pe = self.xy_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_yz_pe = self.yz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_xz_pe = self.xz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + + # add positional encodings to query + query_x_XY = query_x_XY + query_xy_pe + query_x_YZ = query_x_YZ + query_yz_pe + query_x_XZ = query_x_XZ + query_xz_pe + + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + key_value_xy_pe = self.xy_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_yz_pe = self.yz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_xz_pe = self.xz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + + #add positional encodings to key-value tokens + key_value_XY = key_value_XY + key_value_xy_pe + key_value_YZ = key_value_YZ + key_value_yz_pe + key_value_XZ = key_value_XZ + key_value_xz_pe + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY_tokens = query_x_XY.reshape(B, num_tokens, C1) + x_YZ_tokens = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ_tokens = query_x_XZ.reshape(B, num_tokens, C1) + + x_tokens = torch.cat([x_XY_tokens, x_YZ_tokens, x_XZ_tokens], dim=1) + before_sa = self.norm2(x_tokens, mod) + x_tokens = x_tokens + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x_tokens = x_tokens + self.mlp(self.norm3(x_tokens, mod)) + return x_tokens + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + # for m in self.modules(): + # if isinstance(m, nn.Linear): + # nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + @torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolution: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True, + triplane_upsample_channel_dim: int = 32 + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.use_positional_encoding = use_positional_encoding + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #TODO ELIMINA + self.expand_init_tokens = nn.Linear(437, 512) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + self.splat_plane_resolution = splat_plane_resolution + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6, plane_res=plane_resolution) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + #Generate the canonica axis of the 3 planes + self.plane_axes = self.generate_planes() + + + if self.do_latent_rendering: + + #self.upsampler = nn.ConvTranspose2d(inner_dim, triplane_upsample_channel_dim, kernel_size=2, stride=2, padding=0) + + self.upsampler = nn.Sequential( + ResUpBlock(512, 256), # 32 → 64 + ResUpBlock(256, 128), # 64 → 128 + ) + + self.decoder = OSGDecoder(n_features=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=self.latent_dim_embedding*2, out_dim=self.latent_dim_embedding) #TODO: Parametrizza 384 + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def generate_planes(self): + """ + Defines planes by the three vectors that form the "axes" of the + plane. Should work with arbitrary number of planes and planes of + arbitrary orientation. + + Bugfix reference: https://github.com/NVlabs/eg3d/issues/67 + """ + return torch.tensor([[[1, 0, 0], + [0, 1, 0], + [0, 0, 1]], + [[1, 0, 0], + [0, 0, 1], + [0, 1, 0]], + [[0, 0, 1], + [0, 1, 0], + [1, 0, 0]]], dtype=torch.float32) + + def project_onto_planes(self, plane_axes, coordinates): + """ + Does a projection of a 3D point onto a batch of 2D planes, + returning 2D plane coordinates. + + Takes plane axes of shape n_planes, 3, 3 + # Takes coordinates of shape N, M, 3 + # returns projections of shape N*n_planes, M, 2 + """ + N, M, C = coordinates.shape + n_planes, _, _ = plane_axes.shape + coordinates = coordinates.unsqueeze(1).expand(-1, n_planes, -1, -1).reshape(N*n_planes, M, 3) + inv_planes = torch.linalg.inv(plane_axes).unsqueeze(0).expand(N, -1, -1, -1).reshape(N*n_planes, 3, 3) + projections = torch.bmm(coordinates, inv_planes) + return projections[..., :2] + + + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + (B*Num_Views, Num_Rays, Num_3D_Points, 3) + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + #(B*Num_Views, Num_Rays, Num_3D_Points, 3) --> (B*Num_Views*Num_Rays, Num_3D_Points, 3) + B_and_num_views, Num_Rays, Num_3D_Points, _ = sample_coordinates.shape + coordinates = sample_coordinates.reshape(B_and_num_views * Num_Rays, Num_3D_Points, 3) + + #( (B*Num_Views*Num_Rays*3, Num_3D_Points, 2) dove il "3" indica che per ogni punto 3D abbaiamo in fila la sua proiezione sul piano 1,2 e 3 + projected_coordinates = self.project_onto_planes(self.plane_axes.to(coordinates.device), coordinates) + + projected_coordinates = projected_coordinates.view(B_and_num_views, Num_Rays, 3, Num_3D_Points, 2) + + # Proiezione sul piano XY (X,Y) + proj_XY = projected_coordinates[:,:,0] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = projected_coordinates[:,:,1] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = projected_coordinates[:,:,2] + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + #TODO: ELIMINA: inizializzo x con la media dei piani + XY_tokens_mean = XY_tokens.mean(dim=1) + YZ_tokens_mean = YZ_tokens.mean(dim=1) + XZ_tokens_mean = XZ_tokens.mean(dim=1) + init_tokens_mean = self.expand_init_tokens(torch.cat([XY_tokens_mean,YZ_tokens_mean,XZ_tokens_mean], dim=1)) + x = x + init_tokens_mean + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(torch.cat([global_features, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1])], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3), planes if self.latent_dim == 32 else x + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() diff --git a/loomnet/models/extras/feature_aggregator_infinity.py b/loomnet/models/extras/feature_aggregator_infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..b761ddf5e0b87b2f56a143714e2d71d053f9ce64 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_infinity.py @@ -0,0 +1,1234 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {}, + aggregate = False #if true aggregates info to update feature map + ): + super().__init__() + + self.num_views = num_views-1 + + self.aggregate = aggregate + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.box_side_lenght = 1.5 + self.n_samples = 16 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #timestep dim + mod_dim = 1280 + + if self.latent_dim in [4]: + num_layers = 3 + num_heads = 4 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [8]: + num_layers = 4 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [16]: + num_layers = 6 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + else: + num_layers = 8 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + + + #risoluzione del triplane + self.plane_resolution = 32 + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + + # self.downsampler_XY = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_YZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_XZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.aggregate: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + self.decoder = OSGDecoder(n_features=inner_dim*3+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + # num_aggregator_layers = 2 + # num_heads_aggregator = 8 + # self.samples_aggregator_layers = nn.ModuleList([ + # TransformerAggregator(inner_dim=self.latent_dim_embedding, + # mod_dim=mod_dim, + # cond_dim=self.latent_dim_embedding, + # num_heads=num_heads_aggregator, + # eps=1e-6) for _ in range(num_aggregator_layers) + # ]) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def compute_projections(self, points, k_nearest_cameras): + """ + points: (B, F, (H x W), N_samples, 3) + k_nearest_cameras: (B, F, K, 32) + return: + pixel_locations: (B, F, K, (H x W), N_samples, 2) + mask: (B, F, K, (H x W), N_samples) + """ + b, f, k, _ = k_nearest_cameras.shape + intrinsics = k_nearest_cameras[..., :16].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + c2w = k_nearest_cameras[..., 16:].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + points_h = torch.cat( + [points, torch.ones_like(points[..., :1])], dim=-1 + ) # (B, F, (H x W), N_samples, 4) + + points_h = repeat(points_h, "b f n s c -> b f k n s c", k=k) + w2p = torch.matmul(intrinsics, torch.inverse(c2w)) # (B, F, K, 4, 4) + projections = torch.einsum("b f k i j, b f k n s j -> b f k n s i", w2p, points_h) + + # TODO: check is this correct + pixel_locations = projections[..., :2] / torch.clamp( + projections[..., 2:3], min=1e-8 + ) + pixel_locations = torch.clamp( + pixel_locations, min=-10, max=10 + ) # to avoid grid sample nan + mask = projections[..., 2] > 0 # opencv camera + inbound = ( + (pixel_locations[..., 0] <= 1.0) + & (pixel_locations[..., 0] >= 0) + & (pixel_locations[..., 1] <= 1.0) + & (pixel_locations[..., 1] >= 0) + ) + mask = mask & inbound + return pixel_locations, mask + + + def get_nearby_activated_points(self, cameras, select_ids=None, ray_origins=None, ray_directions=None, sample_coordinates=None): + + b, f, c = cameras.shape + k_views = select_ids.shape[2] + + full_cameras = repeat(cameras, "b k c -> b f k c", f=f) + k_nearest_cameras = torch.zeros(b, f, k_views, c, device=cameras.device) + b_ids = torch.arange(b)[:, None, None].expand(-1, f, k_views).to(cameras.device) + f_ids = torch.arange(f)[None, :, None].expand(b, -1, k_views).to(cameras.device) + # Use advanced indexing to get k nearest cameras + k_nearest_cameras = full_cameras[b_ids, f_ids, select_ids] # (B, F, K, 32) + + sample_coordinates = rearrange( + sample_coordinates, "(b f) n s c -> b f n s c", f=f, n=self.latent_dim**2 + ) + + #(b, num_views, num_nearest_views, num_rays, num_samples, 2) + projected_points, mask = self.compute_projections( + sample_coordinates, k_nearest_cameras + ) # compute the k views projection + + projected_points = projected_points * 2 - 1 # to [-1, 1] + return projected_points, mask, + + + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed, + derived_noisy_latent_views = None + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + + num_derived_views = derived_noisy_latent_views.shape[1] + derived_views_cameras = cameras[:,-num_derived_views:] + cameras = cameras[:,:-num_derived_views] + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + # XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.aggregate: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map_anchor_views = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ).transpose(2,3) + + + #______________________NOW RENDER DERIVED VIEWS USING TRIPLANE AS GLOBAL CONTEXT AND THE ANCHOR ACTIVATED FEATURES___________________________________ + + B, num_views = derived_views_cameras.shape[0], derived_views_cameras.shape[1] + derived_intrinsics, derived_c2w = derived_views_cameras[:, :, :16], derived_views_cameras[:, :, 16:] + derived_c2w = rearrange(derived_c2w, "b f (i j) -> (b f) i j", i=4, j=4) + derived_intrinsics = rearrange(derived_intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #generate rays from derived cameras + derived_ray_origins, derived_ray_directions, derived_uv_grid = self.ray_sample(derived_c2w, derived_intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + derived_plucker_ray_embedding = self.encode_plucker(derived_ray_origins, derived_ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + derived_sample_coordinates, derived_sample_directions, derived_sample_depths = self.sample_points( + derived_ray_origins, derived_ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #encode each samples along the rays + derived_local_xyz_probes_position_embedding = self.harmonic_embedding(derived_sample_coordinates) + derived_plucker_expanded = derived_plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + derived_local_xyz_probes_position_embedding = torch.cat([derived_plucker_expanded, derived_local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #find what features each samples (from the derived view) activates in each anchor view + #(b, num_views, num_nearest_views, num_rays, num_samples, 2) in [-1,1] + #projected_points, mask = self.get_nearby_activated_points(derived_views_cameras, k_near_cameras, ray_origins, ray_directions, sample_coordinates) + + print("") + + + + + return updated_feature_map.transpose(2,3), planes + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_k.py b/loomnet/models/extras/feature_aggregator_k.py new file mode 100644 index 0000000000000000000000000000000000000000..ab15ff958536d036649c656284f0880b78e4bdfa --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_k.py @@ -0,0 +1,115 @@ +import os + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t_old import FuseTransformer as Transformer + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim, + depth=1, + embed_dim=0, + use_resnet=True, + ): + super().__init__() + + d_head = 64 + n_heads = dim // d_head + # feature extract -> t1 -> t2 -> t3 (n s) (n k) (n) + self.T1 = Transformer( + in_channels=dim + 2 * (embed_dim + 13), + out_channels=dim, + n_heads=n_heads, + d_head=d_head, + depth=depth, + ) + self.view_fuse = nn.Linear(dim, 1, bias=False) + self.T2 = Transformer( + in_channels=dim, + out_channels=dim, + n_heads=n_heads, + d_head=d_head, + depth=depth, + ) + self.ray_fuse = nn.Linear(dim, 1, bias=False) + + if use_resnet: + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + def forward( + self, + images, + projected_points, + mask, + query_plucker, + reference_plucker, + f_views, + t_emb, + ): + """ + images: (B, F, C, H, W) + projected_points: (B, F, K, N, PTS_PER_RAY, 2) + return: + images: (B, F, C, H, W) + T1: (NUM_INPUT_CAM, N, PTS_PER_RAY, FEATURE_DIM) -> (NUM_INPUT_CAM, (N * PTS_PER_RAY), FEATURE_DIM) + T2: (NUM_INPUT_CAM, N, PTS_PER_RAY, FEATURE_DIM) -> (PT_PER_RAY, (NUM_INPUT_CAM * N), FEATURE_DIM) + T2_W: (NUM_INPUT_CAMERAS, N, PTS_PER_RAY, FEATURE_DIM) -> (PT_PER_RAY, N, 1, FEATURE_DIM) + """ + b, f, k, n, s, j = projected_points.shape + bf, c, h, w = images.shape + # images = self.resnet(images, t_emb) + + images = rearrange(images, "(b f) c h w -> (b f) h w c", f=f_views) + + k_views = projected_points.shape[2] + # save projected_points + projected_points = rearrange(projected_points, "b f k n s j -> (b f k) n s j") + feature_map = repeat( + images, "(b f) h w c-> (b f k) c h w", k=k_views, f=f_views + ) + + feature_sampled = F.grid_sample( + feature_map, + projected_points[..., [1, 0]], + align_corners=True, + padding_mode="border", + ) # (B x F x K, C, H x W, N_samples) + + feature_sampled = rearrange( + feature_sampled, "(b f k) c n s -> b f k n s c", f=f_views, k=k_views + ) + + t1 = torch.concat((feature_sampled, query_plucker, reference_plucker), dim=-1) + + # fuse k nearest view + t1 = rearrange(t1, "b f k n s c -> (b f s n) k c").to(images.dtype) + mask = rearrange(mask, "b f k n s -> (b f s n) k") + emb = repeat(t_emb, "bf c -> (bf s n) 1 c", n=n, s=s) + out = self.T1(t1, t=emb, attention_mask=mask) + + mask = rearrange(mask, "... -> ... 1") + weight = self.view_fuse(out) + weight = weight.masked_fill(~mask, torch.finfo(weight.dtype).min) + weight = F.softmax(weight, dim=1) + t1 = torch.sum(out * weight, dim=1) # (bf s n) c + + t2 = rearrange(t1, "(bf s n) c -> (bf n) s c", s=s, n=n) + emb = repeat(t_emb, "bf c -> (bf n) 1 c", n=n) + t2 = self.T2(t2, t=emb) + weight = self.ray_fuse(t2) + weight = F.softmax(weight, dim=1) + t2 = torch.sum(t2 * weight, dim=1) # (b f n) c + + images = rearrange(t2, "(bf h w) c -> bf c h w", bf=bf, h=h, w=w) + if self.resnet is not None: + images = self.resnet(images, t_emb) + images = rearrange(images, "bf c h w -> (bf h w) c") + images = rearrange(images, "(b f h w) c -> (b f) c h w", h=h, w=w, f=f_views) + + return images diff --git a/loomnet/models/extras/feature_aggregator_triplane.py b/loomnet/models/extras/feature_aggregator_triplane.py new file mode 100644 index 0000000000000000000000000000000000000000..06dd58b7c0daed38abaa8056f86139919235d6e6 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_triplane.py @@ -0,0 +1,1389 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + layers.append(nn.InstanceNorm2d(input_dim)) + layers.append(nn.GELU()) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + layers.append(nn.InstanceNorm2d(input_dim)) + layers.append(nn.GELU()) + + self.downsampler = nn.Sequential(*layers) + self.final_linear_conv = nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + ) + + def forward(self, x): + return self.final_linear_conv(self.downsampler(x)) + + + +import torch +import torch.nn as nn + +class HybridUpsampler(nn.Module): + def __init__(self, inner_dim, plane_channel_dim_after_upsample, feat_map_res): + super().__init__() + + # Decide la risoluzione target in base alla risoluzione della feature map di input + if feat_map_res <= 8: + self.target_res = 64 + else: + self.target_res = 128 + + layers = [] + + # Primo step: sempre upsample 32x32 → metà della target_res con conv learnable + mid_res = self.target_res // 2 + layers.append( + nn.ConvTranspose2d( + inner_dim, + plane_channel_dim_after_upsample, + kernel_size=2, + stride=2, + padding=0 + ) + ) # 32x32 → 64x64 + layers.append(nn.SiLU(inplace=True)) + + # Secondo step: se la target_res è 128, facciamo ulteriore upsample + if self.target_res == 128: + layers.append( + nn.Upsample( + scale_factor=2, + mode='bilinear', + align_corners=False + ) + ) # 64x64 → 128x128 + layers.append( + nn.Conv2d( + plane_channel_dim_after_upsample, + plane_channel_dim_after_upsample, + kernel_size=3, + stride=1, + padding=1 + ) + ) + layers.append(nn.SiLU(inplace=True)) + + self.upsample = nn.Sequential(*layers) + + def forward(self, x): + return self.upsample(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0., plane_res: int = 32): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + self.xy_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.yz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.xz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + + self.xy_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.yz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.xz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + #positional encoding + query_xy_pe = self.xy_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_yz_pe = self.yz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_xz_pe = self.xz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + + # add positional encodings to query + query_x_XY = query_x_XY + query_xy_pe + query_x_YZ = query_x_YZ + query_yz_pe + query_x_XZ = query_x_XZ + query_xz_pe + + + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + key_value_xy_pe = self.xy_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_yz_pe = self.yz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_xz_pe = self.xz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + + #add positional encodings to key-value tokens + key_value_XY = key_value_XY + key_value_xy_pe + key_value_YZ = key_value_YZ + key_value_yz_pe + key_value_XZ = key_value_XZ + key_value_xz_pe + + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + all_x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(all_x, mod) + all_x = all_x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + all_x = all_x + self.mlp(self.norm3(all_x, mod)) + return all_x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +# class OSGDecoder(nn.Module): +# """ +# Triplane decoder that gives RGB and sigma values from sampled features. +# Using Softplus as in the original implementation. + +# Reference: +# EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 +# """ +# def __init__(self, n_features: int, +# hidden_dim: int = 640, out_dim: int = 320, num_layers: int = 4, activation: nn.Module = nn.PReLU): +# super().__init__() +# self.net = nn.Sequential( +# nn.Linear(n_features, hidden_dim), +# activation(), +# *itertools.chain(*[[ +# nn.Linear(hidden_dim, hidden_dim), +# activation(), +# ] for _ in range(num_layers - 2)]), +# nn.Linear(hidden_dim, out_dim), +# ) +# # init all to zero +# for m in self.modules(): +# if isinstance(m, nn.Linear): +# #nn.init.zeros_(m.weight) +# nn.init.zeros_(m.bias) + +# #sampled_features: (Num_points, 96) +# #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) +# def forward(self, sampled_features): +# x = self.net(sampled_features) + +# return x + + + + +class FourierFeatures(nn.Module): + """Positional encoding per le coordinate (x,y,z).""" + def __init__(self, num_freqs=10, include_input=True): + super().__init__() + self.num_freqs = num_freqs + self.include_input = include_input + # Frequenze: [1, 2, 4, ..., 2^(num_freqs-1)] + self.freq_bands = 2.0 ** torch.linspace(0, num_freqs - 1, num_freqs) + + def forward(self, x): + """ + x: [..., 3] (coords normalizzate in [-1,1]) + ritorna: [..., 3 * (2*num_freqs + (include_input?1:0))] + """ + out = [] + if self.include_input: + out.append(x) + for freq in self.freq_bands.to(x.device): + out.append(torch.sin(freq * math.pi * x)) + out.append(torch.cos(freq * math.pi * x)) + return torch.cat(out, dim=-1) + + +class OSGDecoder(nn.Module): + """ + Improved Triplane Decoder: + - Fourier features sulle coords + - Skip connection + - CNN finale per sharpen + """ + def __init__(self, + in_dim=320, # feature dal triplane + coord_dim=3, # (x,y,z) + fourier_freqs=10, + hidden_dim=640, + out_dim=320, + num_layers=4, + activation=nn.GELU, + cnn_channels=128): + super().__init__() + + # Fourier encoding per le coordinate + self.pe = FourierFeatures(num_freqs=fourier_freqs, include_input=True) + pe_dim = coord_dim * (2 * fourier_freqs + 1) + + mlp_in_dim = in_dim + pe_dim - 3 + + # MLP stile NeRF + layers = [] + for i in range(num_layers): + if i == 0: + layers.append(nn.Linear(mlp_in_dim, hidden_dim)) + elif i == num_layers // 2: + # Skip connection + layers.append(nn.Linear(hidden_dim + mlp_in_dim, hidden_dim)) + else: + layers.append(nn.Linear(hidden_dim, hidden_dim)) + layers.append(activation()) + self.mlp = nn.Sequential(*layers) + + self.mlp_out = nn.Linear(hidden_dim, out_dim) + + # CNN di affinamento + self.refine = nn.Sequential( + nn.Conv2d(out_dim, cnn_channels, 3, padding=1), + nn.GELU(), + nn.Conv2d(cnn_channels, cnn_channels, 3, padding=1), + nn.GELU(), + nn.Conv2d(cnn_channels, out_dim, 1) # output raffinato + ) + + # Init Xavier/kaiming + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + nn.init.kaiming_uniform_(m.weight, a=math.sqrt(5)) + if m.bias is not None: + fan_in, _ = nn.init._calculate_fan_in_and_fan_out(m.weight) + bound = 1 / math.sqrt(fan_in) + nn.init.uniform_(m.bias, -bound, bound) + elif isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.zeros_(m.bias) + + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features, plucker_coords, coords): + """ + sampled_features: (N*H*W, in_dim) + plucker_coords: già normalizzate con harmonic + coords: (N*H*W, 3) coords normalizzate [-1,1] + """ + pe_coords = self.pe(coords) + x = torch.cat([sampled_features, plucker_coords, pe_coords], dim=-1) + + # Passa attraverso l'MLP con skip + h = x + for i, layer in enumerate(self.mlp): + if isinstance(layer, nn.Linear) and i == (len(self.mlp) // 2): # punto skip + h = torch.cat([h, x], dim=-1) + h = layer(h) + + feat = self.mlp_out(h) # (N*H*W, out_dim) + + return feat # [N, out_dim, H, W] + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolutions: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True, + do_global_rendering = False, + is_last_communication_block = False, + plane_channel_dim_after_upsample = 128 + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.do_global_rendering = do_global_rendering + + self.use_positional_encoding = use_positional_encoding + + self.is_last_communication_block = is_last_communication_block + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + #self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + self.feature_norm_layer = nn.LayerNorm(self.latent_dim_embedding + self.ray_embedding_dim + self.ray_sample_embedding_dim) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + plane_channel_dim_after_upsample = plane_channel_dim_after_upsample + + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + self.splat_plane_resolution = splat_plane_resolutions[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + self.splat_plane_resolution = splat_plane_resolutions[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + self.splat_plane_resolution = splat_plane_resolutions[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + self.splat_plane_resolution = splat_plane_resolutions[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6, plane_res=plane_resolution) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + # if self.is_last_communication_block or self.latent_dim==16: #TODO ELIMINA or self.latent_dim==16 + # self.resnet_final_1 = ResBlock(dim, 1280, use_scale_shift_norm=True) + # self.resnet_final_2 = ResBlock(dim, 1280, use_scale_shift_norm=True) + + + if self.do_latent_rendering: + + self.upsampler = nn.ConvTranspose2d(inner_dim, plane_channel_dim_after_upsample, kernel_size=2, stride=2, padding=0) + #self.upsampler = HybridUpsampler(inner_dim=inner_dim, plane_channel_dim_after_upsample=plane_channel_dim_after_upsample, feat_map_res=self.latent_dim) + + if self.do_global_rendering: + #self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim ), hidden_dim=self.latent_dim_embedding*3, out_dim=self.latent_dim_embedding) + #self.decoder = OSGDecoder(n_features=plane_channel_dim_after_upsample*3 + (self.ray_embedding_dim+self.ray_sample_embedding_dim), hidden_dim=plane_channel_dim_after_upsample*2, out_dim=self.latent_dim_embedding) + self.decoder = OSGDecoder(in_dim=plane_channel_dim_after_upsample*3 + (self.ray_embedding_dim+3), hidden_dim=plane_channel_dim_after_upsample*2, out_dim=self.latent_dim_embedding) + else: + self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + + + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + unet_features*=0 + idx=0 + # # unet_features[idx,:,0,0]=0.1 + # # unet_features[idx,:,0,1]=1 + # # unet_features[idx,:,0,2]=2 + # # unet_features[idx,:,0,3]=3 + # # unet_features[idx,:,1,0]=4 + # # unet_features[idx,:,1,1]=5 + # # unet_features[idx,:,1,2]=6 + unet_features[idx,:,1,3]=100 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + #unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid[...,[1,0]], # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + + #normalizzo per stabilità e per dare stesso peso alle feature posizionali + unet_sampled_features_with_position_embedding = self.feature_norm_layer(unet_sampled_features_with_position_embedding) + + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + if self.do_global_rendering: + #give a identification of each point (use ray position as prefix) + coords = sample_coordinates/ (self.box_side_lenght/2) # --> [-1, 1] + decoded_sampled_features = self.decoder(global_features, plucker_coords = plucker_expanded.reshape(B, -1, plucker_expanded.shape[-1]), coords = coords.reshape(B, -1, coords.shape[-1])) + #decoded_sampled_features = self.decoder(global_features) + + else: + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + # CNN refinement + updated_feature_map = self.decoder.refine(updated_feature_map) + + + if self.is_last_communication_block:# or self.latent_dim==16: #TODO: ELIMINA or self.latent_dim==16 + # updated_feature_map = self.resnet_final_1(updated_feature_map.transpose(2,3), t_emb) + # updated_feature_map = self.resnet_final_2(updated_feature_map, t_emb) + return updated_feature_map.transpose(2,3), planes + else: + return updated_feature_map.transpose(2,3), planes + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_triplane_with_3d_conv.py b/loomnet/models/extras/feature_aggregator_triplane_with_3d_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..c798b696cad152db784afd37144f8ba557347be4 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_triplane_with_3d_conv.py @@ -0,0 +1,1422 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + layers.append(nn.InstanceNorm2d(input_dim)) + layers.append(nn.GELU()) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + layers.append(nn.InstanceNorm2d(input_dim)) + layers.append(nn.GELU()) + + self.downsampler = nn.Sequential(*layers) + self.final_linear_conv = nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + ) + + def forward(self, x): + return self.final_linear_conv(self.downsampler(x)) + + + +import torch +import torch.nn as nn + +class HybridUpsampler(nn.Module): + def __init__(self, inner_dim, plane_channel_dim_after_upsample, feat_map_res): + super().__init__() + + # Decide la risoluzione target in base alla risoluzione della feature map di input + if feat_map_res <= 8: + self.target_res = 64 + else: + self.target_res = 128 + + layers = [] + + # Primo step: sempre upsample 32x32 → metà della target_res con conv learnable + mid_res = self.target_res // 2 + layers.append( + nn.ConvTranspose2d( + inner_dim, + plane_channel_dim_after_upsample, + kernel_size=2, + stride=2, + padding=0 + ) + ) # 32x32 → 64x64 + layers.append(nn.SiLU(inplace=True)) + + # Secondo step: se la target_res è 128, facciamo ulteriore upsample + if self.target_res == 128: + layers.append( + nn.Upsample( + scale_factor=2, + mode='bilinear', + align_corners=False + ) + ) # 64x64 → 128x128 + layers.append( + nn.Conv2d( + plane_channel_dim_after_upsample, + plane_channel_dim_after_upsample, + kernel_size=3, + stride=1, + padding=1 + ) + ) + layers.append(nn.SiLU(inplace=True)) + + self.upsample = nn.Sequential(*layers) + + def forward(self, x): + return self.upsample(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0., plane_res: int = 32): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + self.xy_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.yz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.xz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + + self.xy_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.yz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.xz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + #positional encoding + query_xy_pe = self.xy_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_yz_pe = self.yz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_xz_pe = self.xz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + + # add positional encodings to query + query_x_XY = query_x_XY + query_xy_pe + query_x_YZ = query_x_YZ + query_yz_pe + query_x_XZ = query_x_XZ + query_xz_pe + + + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + key_value_xy_pe = self.xy_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_yz_pe = self.yz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_xz_pe = self.xz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + + #add positional encodings to key-value tokens + key_value_XY = key_value_XY + key_value_xy_pe + key_value_YZ = key_value_YZ + key_value_yz_pe + key_value_XZ = key_value_XZ + key_value_xz_pe + + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + all_x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(all_x, mod) + all_x = all_x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + all_x = all_x + self.mlp(self.norm3(all_x, mod)) + return all_x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +# class OSGDecoder(nn.Module): +# """ +# Triplane decoder that gives RGB and sigma values from sampled features. +# Using Softplus as in the original implementation. + +# Reference: +# EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 +# """ +# def __init__(self, n_features: int, +# hidden_dim: int = 640, out_dim: int = 320, num_layers: int = 4, activation: nn.Module = nn.PReLU): +# super().__init__() +# self.net = nn.Sequential( +# nn.Linear(n_features, hidden_dim), +# activation(), +# *itertools.chain(*[[ +# nn.Linear(hidden_dim, hidden_dim), +# activation(), +# ] for _ in range(num_layers - 2)]), +# nn.Linear(hidden_dim, out_dim), +# ) +# # init all to zero +# for m in self.modules(): +# if isinstance(m, nn.Linear): +# #nn.init.zeros_(m.weight) +# nn.init.zeros_(m.bias) + +# #sampled_features: (Num_points, 96) +# #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) +# def forward(self, sampled_features): +# x = self.net(sampled_features) + +# return x + + + + +class FourierFeatures(nn.Module): + """Positional encoding per le coordinate (x,y,z).""" + def __init__(self, num_freqs=10, include_input=True): + super().__init__() + self.num_freqs = num_freqs + self.include_input = include_input + # Frequenze: [1, 2, 4, ..., 2^(num_freqs-1)] + self.freq_bands = 2.0 ** torch.linspace(0, num_freqs - 1, num_freqs) + + def forward(self, x): + """ + x: [..., 3] (coords normalizzate in [-1,1]) + ritorna: [..., 3 * (2*num_freqs + (include_input?1:0))] + """ + out = [] + if self.include_input: + out.append(x) + for freq in self.freq_bands.to(x.device): + out.append(torch.sin(freq * math.pi * x)) + out.append(torch.cos(freq * math.pi * x)) + return torch.cat(out, dim=-1) + + +class OSGDecoder(nn.Module): + """ + Improved Triplane Decoder: + - Fourier features sulle coords + - Skip connection + - CNN finale per sharpen + """ + def __init__(self, + in_dim=320, # feature dal triplane + coord_dim=3, # (x,y,z) + fourier_freqs=10, + hidden_dim=640, + out_dim=320, + num_layers=4, + activation=nn.GELU, + cnn_channels=128): + super().__init__() + + # Fourier encoding per le coordinate + self.pe = FourierFeatures(num_freqs=fourier_freqs, include_input=True) + pe_dim = coord_dim * (2 * fourier_freqs + 1) + + mlp_in_dim = in_dim + pe_dim - 3 + + # MLP stile NeRF + layers = [] + for i in range(num_layers): + if i == 0: + layers.append(nn.Linear(mlp_in_dim, hidden_dim)) + elif i == num_layers // 2: + # Skip connection + layers.append(nn.Linear(hidden_dim + mlp_in_dim, hidden_dim)) + else: + layers.append(nn.Linear(hidden_dim, hidden_dim)) + layers.append(activation()) + self.mlp = nn.Sequential(*layers) + + self.mlp_out = nn.Linear(hidden_dim, out_dim) + + # CNN di affinamento + self.refine = nn.Sequential( + nn.Conv2d(out_dim, cnn_channels, 3, padding=1), + nn.GELU(), + nn.Conv2d(cnn_channels, cnn_channels, 3, padding=1), + nn.GELU(), + nn.Conv2d(cnn_channels, out_dim, 1) # output raffinato + ) + + # Init Xavier/kaiming + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + nn.init.kaiming_uniform_(m.weight, a=math.sqrt(5)) + if m.bias is not None: + fan_in, _ = nn.init._calculate_fan_in_and_fan_out(m.weight) + bound = 1 / math.sqrt(fan_in) + nn.init.uniform_(m.bias, -bound, bound) + elif isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + if m.bias is not None: + nn.init.zeros_(m.bias) + + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features, plucker_coords, coords): + """ + sampled_features: (N*H*W, in_dim) + plucker_coords: già normalizzate con harmonic + coords: (N*H*W, 3) coords normalizzate [-1,1] + """ + pe_coords = self.pe(coords) + x = torch.cat([sampled_features, plucker_coords, pe_coords], dim=-1) + + # Passa attraverso l'MLP con skip + h = x + for i, layer in enumerate(self.mlp): + if isinstance(layer, nn.Linear) and i == (len(self.mlp) // 2): # punto skip + h = torch.cat([h, x], dim=-1) + h = layer(h) + + feat = self.mlp_out(h) # (N*H*W, out_dim) + + return feat # [N, out_dim, H, W] + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolutions: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True, + do_global_rendering = False, + is_last_communication_block = False, + plane_channel_dim_after_upsample = 128 + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.do_global_rendering = do_global_rendering + + self.use_positional_encoding = use_positional_encoding + + self.is_last_communication_block = is_last_communication_block + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + #self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + self.feature_norm_layer = nn.LayerNorm(self.latent_dim_embedding + self.ray_embedding_dim + self.ray_sample_embedding_dim) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + plane_channel_dim_after_upsample = plane_channel_dim_after_upsample + + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + self.splat_plane_resolution = splat_plane_resolutions[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + self.splat_plane_resolution = splat_plane_resolutions[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + self.splat_plane_resolution = splat_plane_resolutions[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + self.splat_plane_resolution = splat_plane_resolutions[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.conv_3d_XY = nn.Conv3d( + in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + out_channels=640, # vogliamo un canale globale + kernel_size=(self.num_views, 3, 3), # convolviamo su tutte le mappe + piccola finestra XY + padding=(0,1,1) # manteniamo H e W dimension + ) + + self.conv_3d_YZ = nn.Conv3d( + in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + out_channels=640, # vogliamo un canale globale + kernel_size=(self.num_views, 3, 3), # convolviamo su tutte le mappe + piccola finestra XY + padding=(0,1,1) # manteniamo H e W dimension + ) + + self.conv_3d_XZ = nn.Conv3d( + in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + out_channels=640, # vogliamo un canale globale + kernel_size=(self.num_views, 3, 3), # convolviamo su tutte le mappe + piccola finestra XY + padding=(0,1,1) # manteniamo H e W dimension + ) + + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6, plane_res=plane_resolution) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + # if self.is_last_communication_block or self.latent_dim==16: #TODO ELIMINA or self.latent_dim==16 + # self.resnet_final_1 = ResBlock(dim, 1280, use_scale_shift_norm=True) + # self.resnet_final_2 = ResBlock(dim, 1280, use_scale_shift_norm=True) + + + if self.do_latent_rendering: + + self.upsampler = nn.ConvTranspose2d(self.latent_dim_embedding, plane_channel_dim_after_upsample, kernel_size=1, stride=1, padding=0) + #self.upsampler = HybridUpsampler(inner_dim=inner_dim, plane_channel_dim_after_upsample=plane_channel_dim_after_upsample, feat_map_res=self.latent_dim) + + if self.do_global_rendering: + #self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim ), hidden_dim=self.latent_dim_embedding*3, out_dim=self.latent_dim_embedding) + #self.decoder = OSGDecoder(n_features=plane_channel_dim_after_upsample*3 + (self.ray_embedding_dim+self.ray_sample_embedding_dim), hidden_dim=plane_channel_dim_after_upsample*2, out_dim=self.latent_dim_embedding) + self.decoder = OSGDecoder(in_dim=plane_channel_dim_after_upsample*3 + (self.ray_embedding_dim+3), hidden_dim=plane_channel_dim_after_upsample*2, out_dim=self.latent_dim_embedding) + else: + self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + # def reshape_upsample(self, tokens): + # N = tokens.shape[0] + # H = W = self.plane_resolution + # x = tokens.view(N, 3, H, W, -1) + # x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + # x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + # x = self.upsampler(x) # [3*N, D', H', W'] + # x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + # x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + # x = x.contiguous() + # return x + + def reshape_upsample(self, triplane): + B, _, C, H, W = triplane.shape + x = triplane.view(B*3, C, H, W) + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(B, 3, 128, H, W) + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + idx=0 + unet_features[idx,:,0,0]=0 + unet_features[idx,:,0,1]=0 + unet_features[idx,:,0,2]=0 + unet_features[idx,:,0,3]=0 + unet_features[idx,:,1,0]=0 + unet_features[idx,:,1,1]=0 + unet_features[idx,:,1,2]=0 + unet_features[idx,:,1,3]=100 + unet_features[idx,:,2,0]=0 + unet_features[idx,:,2,1]=0 + unet_features[idx,:,2,2]=0 + unet_features[idx,:,2,3]=1 + unet_features[idx,:,3,0]=2 + unet_features[idx,:,3,1]=3 + unet_features[idx,:,3,2]=4 + unet_features[idx,:,3,3]=0 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + #unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid[...,[1,0]], # (160, 16, 1, 2) from left to right, from top to bottom + mode='nearest', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + + + + #normalizzo per stabilità e per dare stesso peso alle feature posizionali + #unet_sampled_features_with_position_embedding = self.feature_norm_layer(unet_sampled_features_with_position_embedding) + + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #permuto --> (b, num_views, num_channels, h, w) to (b, num_channels, num_views, h, w) + XYs = XY.permute(0,2,1,3,4).contiguous() + YZs = YZ.permute(0,2,1,3,4).contiguous() + XZs = XZ.permute(0,2,1,3,4).contiguous() + + XY_global = XYs#self.conv_3d_XY(XYs) + YZ_global = YZs#self.conv_3d_YZ(YZs) + XZ_global = XZs#self.conv_3d_XZ(XZs) + + triplane = torch.cat([XY_global, YZ_global, XZ_global], dim=2).permute(0,2,1,3,4).contiguous() + + + # #downsample and tokenize + # B, T, C, H, W = XY.shape + # #[B, num_views, C, num_tokens] + # XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + # YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + # XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + # mod = t_emb[::self.num_views] + # for layer in self.layers: + # x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + + # #[b, num_tokens, C] + # x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = triplane#self.reshape_upsample(triplane)#TODO rimetti + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + if self.do_global_rendering: + #give a identification of each point (use ray position as prefix) + coords = sample_coordinates/ (self.box_side_lenght/2) # --> [-1, 1] + decoded_sampled_features = self.decoder(global_features, plucker_coords = plucker_expanded.reshape(B, -1, plucker_expanded.shape[-1]), coords = coords.reshape(B, -1, coords.shape[-1])) + #decoded_sampled_features = self.decoder(global_features) + + else: + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + # CNN refinement + updated_feature_map = self.decoder.refine(updated_feature_map) + + + if self.is_last_communication_block:# or self.latent_dim==16: #TODO: ELIMINA or self.latent_dim==16 + # updated_feature_map = self.resnet_final_1(updated_feature_map.transpose(2,3), t_emb) + # updated_feature_map = self.resnet_final_2(updated_feature_map, t_emb) + return updated_feature_map.transpose(2,3), planes + else: + return updated_feature_map.transpose(2,3), planes + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_v1.py b/loomnet/models/extras/feature_aggregator_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..3f54ac6ea1b1bab1b034f6e0438eae27974e7cc9 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v1.py @@ -0,0 +1,544 @@ +# https://github.com/zhizdev/sparsefusion/blob/main/sparsefusion/eft.py +import os +from typing import List + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t_old import ( + AdaLayerNorm, + CrossAttention, + Transformer, + GraphTransformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn_graph +import numpy as np +import math + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.num_points = latent_dim + + #create point cloud selector at that level + self.latent_point_xyz = nn.Parameter(torch.randn(self.num_points, 3)*0.05) + + #create point cloud features at that level + self.latent_point_feat = nn.Parameter(torch.randn(self.num_points, dim)) + + #create offset parameter to give freedom to move to each point projected on the image plan + #self.offset = nn.Parameter(torch.zeros(self.num_views, latent_dim**2, 2)) # shape: [48, 16, 2] + + #pointwise spatial transformer to transform each point in affine manner + self.pointwise_spatial_transformer_model = PointWiseSpatialTransformer(feature_map_spatial_dim=latent_dim, feature_map_channel_dim=dim) + + #network to make cross attention between each 3D latent point and its own activated features in each camera + self.T1 = Transformer( + in_channels= dim, #dimensione embedding query + context_dim=dim+self.latent_dim, #dimensione embedding contesto (aggiungo anche il positional encoding) + # in_channels=dim, + out_channels=dim, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[0], + d_head= d_heads_transformers[0], + depth= depths_transformers[0], + type_of_transformer_block='cross' + ) + + #number of neighbors connection for 3D latent point cloud + # (if middle block, maximum, otherwise the sqrt of spatial resolution ) + if latent_dim == 4: + self.num_neighbor_connection = 16 + elif latent_dim == 8: + self.num_neighbor_connection = 8 + elif latent_dim == 16: + self.num_neighbor_connection = 8 + else: + self.num_neighbor_connection = 16 + + + #graph transformer to do message passing between latent points + self.GT = GraphTransformer(in_channels=self.latent_dim_embedding, + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads=n_heads_transformers[1], + d_head= d_heads_transformers[1], + depth= depths_transformers[1] + ) + + #transformer to update activate features using 3D latent point (updated) + self.T2 = Transformer( + in_channels= self.latent_dim_embedding + self.latent_dim, #dimensione embedding query + pos embedding + context_dim=self.latent_dim_embedding, #dimensione embedding contesto + # in_channels=dim, + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[2], + d_head= d_heads_transformers[2], + depth= depths_transformers[2], + mod_dim=self.latent_dim_embedding, + type_of_transformer_block='self-mod' + ) + + + #final transformer to update feature map with the local activate features + self.T3 = Transformer( + in_channels = self.latent_dim_embedding, #dimensione embedding query + context_dim = self.latent_dim_embedding, #dimensione embedding contesto (aggiungo anche il positional encoding) + # in_channels=dim, + out_channels=dim, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[3], + d_head= d_heads_transformers[3], + depth= depths_transformers[3], + type_of_transformer_block='cross' + ) + + #sigma for gaussian kernel of each splatted point + #self.sigma = torch.nn.Parameter(torch.tensor(0.1)) #inizializzo a 0.1 (maggire è sigma, maggiormente verranno influenzati i pixel lontani dalle feature dei punti) + + #alpha for soft blending between old unet feature map and the new one + #self.alpha = torch.nn.Parameter(torch.tensor(10.0)) #inizializzo a 0 cosi da far passare le feature originali all'inizio + + #uso pac_man function per far si che se supera 1, la differenza si tramuta in una sottrazione da 1, altrimenti in un incremento da 0 + # def pac_man_activation_function(self, x): + # return 0.5*(1-torch.cos(torch.pi*x)) + + + def forward( + self, + images, + t_emb, + pos_views, + num_views, + cameras + ): + """ + images: (B*Num_Views, C, H, W) + t_emb: (B*Num_Views, C) + pos_views: (B*Num_views, 1, D) + return: + images: (B, F, C, H, W) + T1: (NUM_INPUT_CAM, N, PTS_PER_RAY, FEATURE_DIM) -> (NUM_INPUT_CAM, (N * PTS_PER_RAY), FEATURE_DIM) + T2: (NUM_INPUT_CAM, N, PTS_PER_RAY, FEATURE_DIM) -> (PT_PER_RAY, (NUM_INPUT_CAM * N), FEATURE_DIM) + T2_W: (NUM_INPUT_CAMERAS, N, PTS_PER_RAY, FEATURE_DIM) -> (PT_PER_RAY, N, 1, FEATURE_DIM) + """ + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :4, :4] + + + #___________________________ POINT-CLOUD in [-0.2 and 0.2] _____________ + latent_point_xyz = 0.2*nn.Tanh()(self.latent_point_xyz) + + + #plot_pose_cameras_and_latents(c2w, num_views, latent_point_xyz) + + #________________________ PROJECT LATENT POINT TO IMAGE PLANE OF EACH CAMERA ________________________________ + #creo coordinate omogenee dei punti + latent_point_xyz_h = torch.cat([latent_point_xyz, torch.ones_like(latent_point_xyz[..., :1])], dim=-1) # (latent_dim^2, 4) + + #replico per il numero di camere che ci sono (compresi i batch) + latent_point_xyz_h = latent_point_xyz_h.repeat(B*num_views, 1, 1) + + #creo la matrice di proiezione + w2p = torch.matmul(intrinsics, torch.inverse(c2w)) # (B, 4, 4) + #proietto sulle camere + projections = torch.matmul(latent_point_xyz_h, w2p.transpose(1, 2)) #(B, latent_dim^2, 4 ) + + #ora abbiamo punti davanti (z>0) o dietro la camera (z<0). + #mi segno quelli che sono dietro la camera + z_coords = projections[..., 2] # Shape: [32, 4] + # Mask: True dove z >= 0, False dove z < 0 + projection_visibility = z_coords >= 0 + + #divido per z per ottenere quei punti sul piano immagine + pixel_locations = projections[...,:2] / (projections[...,2:3] + 1e-8) + + #ora mi segno tutti i pixel che stanno nel piano immagine [0,1] + # Estrai x e y dalle coordinate + x = pixel_locations[..., 0] # Shape: [32, 4] + y = pixel_locations[..., 1] # Shape: [32, 4] + pixel_visibility = (x >= 0) & (x < 1) & (y >= 0) & (y < 1) + + + + #_____________________________________ POINTWISE SPATIAL TRANSFORMER _______________________________ + #per ogni camera abbiamo le feature della unet + unet_features = images + device = unet_features.device + + #move to [-1,1] + pixel_locations = 2*pixel_locations-1 + + #sinusoidal embedding of each continuous location --> (B*num_views, num_projected_points, dim_sinusoidal_embedding) + pixel_locations_embedding = apply_pos_embed(pixel_locations, feature_map_dimension=self.latent_dim) #torch.zeros(size=(pixel_locations.shape[0], pixel_locations.shape[1], self.latent_dim)) + + #get affine transformation for each point (B*num_views, num_projected_points, 2, 3) + theta = self.pointwise_spatial_transformer_model(unet_features, pixel_locations_embedding.to(device)) + + #apply affine transformation to each projected point + pixel_locations_h = torch.cat([pixel_locations, torch.ones_like(pixel_locations[..., :1]).to(device)], dim=-1) # shape: (48, 16, 3) + + new_pixel_locations = torch.matmul(theta, pixel_locations_h.unsqueeze(-1)).squeeze(-1) + + new_pixel_locations = nn.Tanh()(new_pixel_locations) + #plot_projected_points(camera_idx, pixel_locations) + + + #________________________________ SAMPLE LATENT FEATURE IN EACH PROJECTED LOCATION __________________________ + + # #poichè grid_sample vuole pixel location tra -1 e 1, andiamo a normalizzare + # pixel_locations = 2 * pixel_locations - 1 + + new_pixel_locations = new_pixel_locations.unsqueeze(2) + + # Campionamento bilineare + # - input: feature map (B*Num_Views, C, D, D) + # - input: pixel location tra -1 e 1 (B*Num_Views, NumPoints, 1, 2) + # - output --> (B*Num_Views, latent_dim_embedding, NumPoints, 1) + # uso align_corners per mappare gli angoli della mia griglia a quella della feature map (es. cosi che (1,1) nella mia griglia corrisponde a (1,1) nella feature map) + sampled_features = F.grid_sample(unet_features, new_pixel_locations, mode="bilinear", align_corners=True) + + # #DA ELIMINARE + # upsampled_features = F.interpolate(sampled_features, size=(self.latent_dim, self.latent_dim), mode='bilinear', align_corners=False) + # return upsampled_features + + #SOLO PER TRAINING + #DISTANZA PIXEL (B*num_views, num_pixels, num_distances=num_pixels) + pixel_distances = torch.cdist(new_pixel_locations.squeeze(2), new_pixel_locations.squeeze(2), p=2) + #DIVERSITA' DELLE FEATURE CAMPIONATE + feats = sampled_features.squeeze(-1).permute(0, 2, 1) + feats = F.normalize(feats, dim=-1) + # Cosine sim matrix: (B, P, P) + feature_similarity = torch.matmul(feats, feats.transpose(1, 2)) + #[0,1] + feature_similarity = (feature_similarity+1)/2 + + + #add new positional embedding + new_pixel_locations_embedding = apply_pos_embed(new_pixel_locations.squeeze(2), feature_map_dimension=self.latent_dim) + + sampled_features = torch.cat([sampled_features, new_pixel_locations_embedding.permute(0, 2, 1).unsqueeze(-1)], dim=1) + + #________________________________ USE EACH 3D LATENT POINT AS QUERY AND MAKE CROSS ATTENTION WITH ALL ACTIVATED UNET FEATURES _______________________________ + t = t_emb + + #lo risistemo in forma di (b, num_views, 1280) + t = t.reshape(B, num_views, 1280) + + #prendo l'embedding di ogni batch (ossia tutta la prima dimensione e una a caso della seconda) + t_b = t[:,0] + + #poi lo replichiamo per ogni query. Ogni query è un nodo del grafo. Avendo B batch replicheremo il timestep uguale per ogni nodo, ma diverso per ogni batch + #(b*num_query, timestep_embedding) dove però il timestemp è uguale ogni "num_query" elementi di batch + #(B*num_query, dim_timestemp) + t_query = t_b.repeat(1, self.num_points).reshape(B*self.num_points, 1280) + + #1. SISTEMA QUERY COME (B*num_query, 1, dim_embedding_query) + query = self.latent_point_feat.repeat(B, 1).unsqueeze(1) + + + #2. SISTEMA CONTESTO COME (B*num_query, num_vettori_contesto, dim_embedding_contesto) + #ritorniamo per un momento nella forma di batch + sampled_features = sampled_features.view(B, num_views, self.latent_dim_embedding+self.latent_dim, self.num_points, 1) + #abbiamo N punti su V viste. Aggreghiamo le feature degli stessi punti su tutte le viste + #(B, Num_Points, Num_Views, C, 1) --> quindi per ogni punto ho la feature che appare su ogni vista + aggregated_features = sampled_features.permute(0, 3, 1, 2, 4) + #preparo per self-attention tra stessi punti di viste diverse + #1. Reshape in forma di token --> (b*num_points, num_views, C ) (NB: vengono listati tutti i punti divisi per batch, quindi [p1,p2,....,pN] e poi seguono quelli del successivo batch [p1,p2,...,pN]) + aggregated_features = aggregated_features.reshape(B*self.num_points, num_views, self.latent_dim_embedding+self.latent_dim) + + #FAI CROSS ATTENTION TRA QUERY (PUNTO 3D) E CONTESTO (KEY-VALUE FEATURE ATTIVATE) + latent_3d_points = self.T1(query, t=t_query, context=aggregated_features, attention_mask=None) + + + + #________________________________ DO MESSAGE PASSING BETWEEN LATENT 3D POINTS ______________________________ + edge_index = knn_graph(latent_point_xyz, k=self.num_neighbor_connection, loop=False)#, batch=batch) + + #avendo un certo batch size devo replicare gli edge + off = torch.arange(B) * self.num_points # (B,) + off = off.view(-1, 1, 1).to(device) # (B, 1, 1) + + edge_index = edge_index.unsqueeze(0) + off # (B, 2, E) + + # Reshape in (2, E * B) + edge_index = edge_index.permute(1, 0, 2).reshape(2, -1) + + latent_3d_points = self.GT(latent_3d_points, t_query, edge_index) + + #plot_connected_latent_pointcloud(latent_point_xyz, edge_index) + + + + #_____________________________ Global-to-Local modulation: UPDATE ACTIVATED FEATURES ___________________________ + + #(B*Num_Points, num_views, dim_embedding) + updated_aggregated_features = self.T2(aggregated_features, t=t_query, context=None, attention_mask=None, mod=latent_3d_points) + + + ''' + #_________________________ KERNEL SPLATTING: UPDATE LATENT FEATURE MAP ___________________________________ + #adesso le feature sono raggruppate per punto 3d (ossia per ogni punto 3d abbiamo le 16 feature attivate) + #vogliamo riportare tutto nella forma (B*Num_View, dim_embedding, num_points) + updated_aggregated_features = updated_aggregated_features.reshape(B, self.latent_dim**2, num_views, self.latent_dim_embedding).permute(0,2,3,1).reshape(B*num_views, self.latent_dim_embedding, self.latent_dim**2) + + B, C, H, W = unet_features.shape # 48, 1024, 8, 8 + K = pixel_locations.shape[1] # 64 punti aggiornati + + # 1. Convert normalized pixel_locations (in [0,1]) to grid coordinates in [0, H) x [0, W) + pixel_coords = pixel_locations.squeeze(2) # [B, 64, 2] + # pixel_coords[..., 0] = (pixel_coords[..., 0] + 1) * 0.5 * H # y + # pixel_coords[..., 1] = (pixel_coords[..., 1] + 1) * 0.5 * W # x + pixel_coords = (pixel_coords + 1)*0.5*H + + # 2. Crea una meshgrid per tutti i pixel della feature map (8x8) → shape [H*W, 2] + grid_y, grid_x = torch.meshgrid(torch.arange(H, device=device), torch.arange(W, device=device), indexing='ij') + grid_coords = torch.stack([grid_y, grid_x], dim=-1).view(-1, 2).float() # [64, 2] + + # 3. Calcola distanze: per ogni pixel della grid, distanza da ogni dei 64 punti aggiornati + # Output: [B, H*W, 64] + diff = grid_coords[None, :, None, :] - pixel_coords[:, None, :, :] # [B, 64, 64, 2] -> [B, 64, 64, 2] + + dists_sq = (diff ** 2).sum(dim=-1) # [B, 64*64, 64] + + # 2. Calcola gaussiane (radial basis function) + #lo vincolo tra 0 e 1 + sigma = nn.Sigmoid()(self.sigma) + #quanto peso al pixel ogni gaussiana (centrata su un punto) fornisce + weights = torch.exp(-dists_sq / (2 * sigma ** 2)) # [B, H*W, 64] + # 3. Normalizza per fare weighted average (evita che sommino a più di 1) + weights_sum = weights.sum(dim=-1, keepdim=True) + 1e-8 + weights = weights / weights_sum # [B, H*W, 64] + + # 4. Weighted sum delle feature dei punti aggiornati + # weights: [B, H*W, 64] → vogliamo [B, H*W, C] + features_t = updated_aggregated_features.permute(0, 2, 1) # [B, C, 64] + updated = torch.bmm(weights, features_t) # [B, H*W, C] + + # 5. Ricostruisci la feature map aggiornata [B, C, H, W] + updated_feature_map = updated.permute(0, 2, 1).view(B, C, H, W) + + #7. soft blend: facciamo il blending tra la vecchia unet feature map e la nuova + #unet_features_updated = (1-nn.Sigmoid()(self.alpha))*unet_features + nn.Sigmoid()(self.alpha) * updated_feature_map + #unet_features_updated = updated_feature_map + unet_features + unet_features_updated = updated_feature_map + + return unet_features_updated + + ''' + + #___________________________________ UPDATE LOCAL FEATURE USING THE ACTIVATED FEATURE _____________________________ + #now, aggregate feature has shape (B*Num_Points, num_views, dim_embedding), so for each 3D point we have the activated feature + #in each view. So, now, groupy each activated feature for each view + updated_activated_features_per_view = updated_aggregated_features.view(B, self.num_points, num_views, self.latent_dim_embedding).permute(0,2,1,3).reshape(B*num_views, self.num_points, self.latent_dim_embedding) + + #reshape unet features as tokens + token_unet_features = unet_features.flatten(2).transpose(1, 2) + + #use activated features as ambassadors that have collected global info and transmit them to the feature map + t_query = t_b.repeat(1, num_views).reshape(B*num_views, 1280) + updated_unet_feature_map_tokens = self.T3(token_unet_features, t=t_query, context=updated_activated_features_per_view, attention_mask=None ) + + #reshape token into original unet feature map shape + updated_unet_feature_map = updated_unet_feature_map_tokens.transpose(1, 2).view(B*num_views, self.latent_dim_embedding, self.latent_dim, self.latent_dim) + + + return updated_unet_feature_map, pixel_distances, feature_similarity + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt + +def plot_pose_cameras_and_latents(c2w, num_views, latent_point_xyz): + + + latent_point_xyz_tmp = latent_point_xyz.detach().cpu().numpy() + + x, y, z = latent_point_xyz_tmp[:, 0], latent_point_xyz_tmp[:, 1], latent_point_xyz_tmp[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=10, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + + #visualizzo solo per il batch 0 (ossia 16 viste) + camera_positions = c2w[:num_views, :3, 3].cpu().numpy() + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Crea la figura + fig = go.Figure() + + # Aggiungi punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict( + size=10, + color='black', + ), + name='Punti latenti' + )) + + # Aggiungi posizioni delle camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict( + size=6, + color='blue', + ), + name='Camere' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti e delle camere', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + + +def plot_projected_points(camera_idx, pixel_locations, path_where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/proiezione_punti_latenti_camera.png"): + + plt.clf() + plt.close() + # Estrai i punti della camera scelta (ad esempio, camera_idx = 0) + camera_pixels = pixel_locations[camera_idx] # shape: [16, 2] + + # Crea una figura per visualizzare i punti + fig, ax = plt.subplots(figsize=(6, 6)) + + p = camera_pixels.detach().cpu().numpy() + + #move to [0,1] + p = (p + 1)/2 + + # Disegna i punti sulla figura + ax.scatter(p[...,1], p[..., 0], color='black', s=50) + + # Aggiungi i bordi dell'area [0, 1] su entrambi gli assi + ax.plot([0, 0], [0, 1], color='red', linestyle='--') # Bordo sinistro + ax.plot([1, 1], [0, 1], color='red', linestyle='--') # Bordo destro + ax.plot([0, 1], [0, 0], color='red', linestyle='--') # Bordo inferiore + ax.plot([0, 1], [1, 1], color='red', linestyle='--') # Bordo superiore + + # Imposta i limiti degli assi per vedere meglio i bordi + ax.set_xlim(-0.2, 1.2) + ax.set_ylim(-0.2, 1.2) + + # Aggiungi etichette e titolo + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_title(f'Proiezione dei Punti Latenti - Camera {camera_idx + 1}') + + # Rimuovi le etichette degli assi + ax.set_xticks(np.arange(-0.2, 1.2, 0.2)) + ax.set_yticks(np.arange(-0.2, 1.2, 0.2)) + ax.invert_yaxis() + # Salva l'immagine + plt.savefig(path_where_to_save) + + +def plot_latent_pointcloud(latent_point_xyz, edge_index): + # Crea un dizionario con le coordinate dei punti + x_coords = latent_point_xyz[:,0].detach().cpu().numpy() + y_coords = latent_point_xyz[:,1].detach().cpu().numpy() + z_coords = latent_point_xyz[:,2].detach().cpu().numpy() + + # Crea la traccia per i punti 3D + scatter = go.Scatter3d( + x=x_coords, + y=y_coords, + z=z_coords, + mode='markers', + marker=dict(size=10, color='black') + ) + + # Crea le tracce per gli edge 3D + lines = [] + for i in range(len(edge_index[0])): + try: + # Estrai le coordinate per ogni coppia di punti collegati + x0, y0, z0 = x_coords[edge_index[0][i]], y_coords[edge_index[0][i]], z_coords[edge_index[0][i]] + x1, y1, z1 = x_coords[edge_index[1][i]], y_coords[edge_index[1][i]], z_coords[edge_index[1][i]] + lines.append(go.Scatter3d( + x=[x0, x1], + y=[y0, y1], + z=[z0, z1], + mode='lines', + line=dict(width=2, color='red') + )) + except: + break + + # Combinare le tracce + fig = go.Figure(data=[scatter] + lines) + + # Layout + fig.update_layout( + title="Punti e Connessioni 3D", + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + showlegend=False + ) + + # Mostra la figura + fig.show() \ No newline at end of file diff --git a/loomnet/models/extras/feature_aggregator_v10.py b/loomnet/models/extras/feature_aggregator_v10.py new file mode 100644 index 0000000000000000000000000000000000000000..4e3308cf9d71ba21e57123f7ce1b7d991c8688e1 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v10.py @@ -0,0 +1,1312 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + + +''' + Latent Importance Sampling + + STEP1: GET UNIFORM SAMPLED DEPTH to obtain_ + colors_coarse --> [b, num_rays, num_sample_points, 3] + densities_coarse torch.Size([b, num_rays, num_sample_points, 1]) + + + STEP3: Sample pdf. + Ex. self.sample_pdf(torch.tensor([[a,b,c,d,e]]), torch.tensor([[0.1,0.3,0.1,0.5]]),N) + Means that the importance for the bin 1 (all the number between [a,b]) is 10%. N means how many sample to sample from pdf + +''' + +class LatentImportanceSampling(nn.Module): + def __init__(self): + super().__init__() + + def sample_importance(self, z_vals, weights, N_importance): + """ + Return depths of importance sampled points along rays. See NeRF importance sampling for more. + """ + with torch.no_grad(): + batch_size_num_views_num_rays, samples_per_ray, _ = z_vals.shape + + z_vals = z_vals.reshape(batch_size_num_views_num_rays, samples_per_ray) + weights = weights.reshape(batch_size_num_views_num_rays, -1) # -1 to account for loss of 1 sample in MipRayMarcher + + # smooth weights + weights = torch.nn.functional.max_pool1d(weights.unsqueeze(1).float(), 2, 1, padding=1) + weights = torch.nn.functional.avg_pool1d(weights, 2, 1).squeeze() + weights = weights + 0.01 + + z_vals_mid = 0.5 * (z_vals[: ,:-1] + z_vals[: ,1:]) + importance_z_vals = self.sample_pdf(z_vals_mid, weights[:, 1:-1], + N_importance).detach()#.reshape(batch_size, num_rays, N_importance, 1) + return importance_z_vals + + def sample_pdf(self, bins, weights, N_importance, det=False, eps=1e-5): + """ + Sample @N_importance samples from @bins with distribution defined by @weights. + Inputs: + bins: (N_rays, N_samples_+1) where N_samples_ is "the number of coarse samples per ray - 2" + weights: (N_rays, N_samples_) + N_importance: the number of samples to draw from the distribution + det: deterministic or not + eps: a small number to prevent division by zero + Outputs: + samples: the sampled samples + """ + N_rays, N_samples_ = weights.shape + weights = weights + eps # prevent division by zero (don't do inplace op!) + pdf = weights / torch.sum(weights, -1, keepdim=True) # (N_rays, N_samples_) + cdf = torch.cumsum(pdf, -1) # (N_rays, N_samples), cumulative distribution function + cdf = torch.cat([torch.zeros_like(cdf[: ,:1]), cdf], -1) # (N_rays, N_samples_+1) + # padded to 0~1 inclusive + + if det: + u = torch.linspace(0, 1, N_importance, device=bins.device) + u = u.expand(N_rays, N_importance) + else: + u = torch.rand(N_rays, N_importance, device=bins.device) + u = u.contiguous() + + inds = torch.searchsorted(cdf, u, right=True) + below = torch.clamp_min(inds-1, 0) + above = torch.clamp_max(inds, N_samples_) + + inds_sampled = torch.stack([below, above], -1).view(N_rays, 2*N_importance) + cdf_g = torch.gather(cdf, 1, inds_sampled).view(N_rays, N_importance, 2) + bins_g = torch.gather(bins, 1, inds_sampled).view(N_rays, N_importance, 2) + + denom = cdf_g[...,1]-cdf_g[...,0] + denom[denom torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureCorrectionDecoder(nn.Module): + def __init__(self, in_dim=1397, out_dim=1280, hidden_dim=512, num_layers=6): + super().__init__() + self.input = nn.Linear(in_dim, hidden_dim) + self.layers = nn.ModuleList([ + nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + nn.LayerNorm(hidden_dim) # opzionale, migliora la stabilità + ) for _ in range(num_layers) + ]) + self.output = nn.Linear(hidden_dim, out_dim) + + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, x): + x = self.input(x) + for layer in self.layers: + x = x + layer(x) # Residual connection + return self.output(x) + + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {}, + aggregate = False #if true aggregates info to update feature map + ): + super().__init__() + + self.num_views = num_views-1 + + self.aggregate = aggregate + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.box_side_lenght = 1.5 + self.n_samples = 16 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #timestep dim + mod_dim = 1280 + + if self.latent_dim in [4]: + num_layers = 3 + num_heads = 4 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [8]: + num_layers = 4 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [16]: + num_layers = 6 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + else: + num_layers = 8 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + + + #risoluzione del triplane + self.plane_resolution = 32 + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + + # self.downsampler_XY = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_YZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_XZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.aggregate: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + #self.decoder = FeatureCorrectionDecoder(in_dim=inner_dim*3+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=512, out_dim=self.latent_dim_embedding) + self.decoder = OSGDecoder(n_features=inner_dim*3+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding, num_layers=6) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + self.sample_importance = LatentImportanceSampling() + + # num_aggregator_layers = 2 + # num_heads_aggregator = 8 + # self.samples_aggregator_layers = nn.ModuleList([ + # TransformerAggregator(inner_dim=self.latent_dim_embedding, + # mod_dim=mod_dim, + # cond_dim=self.latent_dim_embedding, + # num_heads=num_heads_aggregator, + # eps=1e-6) for _ in range(num_aggregator_layers) + # ]) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def sample_points_using_predefined_depth(self, ray_origins, ray_directions, depths): + + batch_size, num_rays, samples_per_ray, _ = depths.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + # XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.aggregate: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + + + ##_________________LATENT IMPORTANCE SAMPLING___________________________ + coarse_depths = sample_depths.reshape(B_and_num_views*self.latent_dim**2, self.n_samples, 1) + + fine_depths = self.sample_importance(coarse_depths, weight, self.n_samples) + + fine_depths = fine_depths.reshape(B_and_num_views, self.latent_dim**2, self.n_samples, 1) + + #resample + sample_coordinates, sample_directions, sample_depths = self.sample_points_using_predefined_depth( + ray_origins, ray_directions, fine_depths + ) + + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1) + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) + + #recompute projections + proj_XY = sample_coordinates[..., :2] + proj_YZ = sample_coordinates[..., 1:] + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + #resample features from triplane + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + + + + #__________________________ AGGREGATION ______________________________ + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3), planes + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_v12.py b/loomnet/models/extras/feature_aggregator_v12.py new file mode 100644 index 0000000000000000000000000000000000000000..ceac7f9b85bc6ef49fd717774303e6db186ce5da --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v12.py @@ -0,0 +1,1285 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + @torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {}, + aggregate = False #if true aggregates info to update feature map + ): + super().__init__() + + self.num_views = num_views-1 + + self.aggregate = aggregate + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.box_side_lenght = 1.5 + self.n_samples = 16 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #timestep dim + mod_dim = 1280 + + if self.latent_dim in [4]: + num_layers = 3 + num_heads = 4 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [8]: + num_layers = 4 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [16]: + num_layers = 6 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + else: + num_layers = 8 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + + + #risoluzione del triplane + self.plane_resolution = 32 + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + + # self.downsampler_XY = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_YZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_XZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.aggregate: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + self.decoder = OSGDecoder(n_features=inner_dim*3+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + # num_aggregator_layers = 2 + # num_heads_aggregator = 8 + # self.samples_aggregator_layers = nn.ModuleList([ + # TransformerAggregator(inner_dim=self.latent_dim_embedding, + # mod_dim=mod_dim, + # cond_dim=self.latent_dim_embedding, + # num_heads=num_heads_aggregator, + # eps=1e-6) for _ in range(num_aggregator_layers) + # ]) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + + def compute_projections(self, points, k_nearest_cameras): + """ + points: (B, F, (H x W), N_samples, 3) + k_nearest_cameras: (B, F, K, 32) + return: + pixel_locations: (B, F, K, (H x W), N_samples, 2) + mask: (B, F, K, (H x W), N_samples) + """ + b, f, k, _ = k_nearest_cameras.shape + intrinsics = k_nearest_cameras[..., :16].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + c2w = k_nearest_cameras[..., 16:].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + points_h = torch.cat( + [points, torch.ones_like(points[..., :1])], dim=-1 + ) # (B, F, (H x W), N_samples, 4) + + points_h = repeat(points_h, "b f n s c -> b f k n s c", k=k) + w2p = torch.matmul(intrinsics, torch.inverse(c2w)) # (B, F, K, 4, 4) + projections = torch.einsum("b f k i j, b f k n s j -> b f k n s i", w2p, points_h) + + # TODO: check is this correct + pixel_locations = projections[..., :2] / torch.clamp( + projections[..., 2:3], min=1e-8 + ) + pixel_locations = torch.clamp( + pixel_locations, min=-10, max=10 + ) # to avoid grid sample nan + mask = projections[..., 2] > 0 # opencv camera + inbound = ( + (pixel_locations[..., 0] <= 1.0) + & (pixel_locations[..., 0] >= 0) + & (pixel_locations[..., 1] <= 1.0) + & (pixel_locations[..., 1] >= 0) + ) + mask = mask & inbound + return pixel_locations, mask + + + def get_nearby_activated_points(self, cameras, select_ids=None, ray_origins=None, ray_directions=None, sample_coordinates=None): + + b, f, c = cameras.shape + k_views = select_ids.shape[2] + + full_cameras = repeat(cameras, "b k c -> b f k c", f=f) + k_nearest_cameras = torch.zeros(b, f, k_views, c, device=cameras.device) + b_ids = torch.arange(b)[:, None, None].expand(-1, f, k_views).to(cameras.device) + f_ids = torch.arange(f)[None, :, None].expand(b, -1, k_views).to(cameras.device) + # Use advanced indexing to get k nearest cameras + k_nearest_cameras = full_cameras[b_ids, f_ids, select_ids] # (B, F, K, 32) + + sample_coordinates = rearrange( + sample_coordinates, "(b f) n s c -> b f n s c", f=f, n=self.latent_dim**2 + ) + + #(b, num_views, num_nearest_views, num_rays, num_samples, 2) + projected_points, mask = self.compute_projections( + sample_coordinates, k_nearest_cameras + ) # compute the k views projection + + projected_points = projected_points * 2 - 1 # to [-1, 1] + return projected_points, mask, + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + #TODO ELIMINA + unet_features*=0 + idx=0 + unet_features[idx,:,0,0]=0.1 + unet_features[idx,:,0,1]=1 + unet_features[idx,:,0,2]=2 + unet_features[idx,:,0,3]=3 + unet_features[idx,:,1,0]=4 + unet_features[idx,:,1,1]=5 + unet_features[idx,:,1,2]=6 + unet_features[idx,:,1,3]=7 + unet_features[idx,:,2,0]=8 + unet_features[idx,:,2,1]=9 + unet_features[idx,:,2,2]=10 + unet_features[idx,:,2,3]=11 + unet_features[idx,:,3,0]=12 + unet_features[idx,:,3,1]=13 + unet_features[idx,:,3,2]=14 + unet_features[idx,:,3,3]=15 + idx=4 + unet_features[idx,:,0,0]=0.1 + unet_features[idx,:,0,1]=10 + unet_features[idx,:,0,2]=20 + unet_features[idx,:,0,3]=30 + unet_features[idx,:,1,0]=40 + unet_features[idx,:,1,1]=50 + unet_features[idx,:,1,2]=60 + unet_features[idx,:,1,3]=70 + unet_features[idx,:,2,0]=80 + unet_features[idx,:,2,1]=90 + unet_features[idx,:,2,2]=100 + unet_features[idx,:,2,3]=110 + unet_features[idx,:,3,0]=120 + unet_features[idx,:,3,1]=130 + unet_features[idx,:,3,2]=140 + unet_features[idx,:,3,3]=150 + idx=8 + unet_features[idx,:,0,0]=0.1 + unet_features[idx,:,0,1]=11 + unet_features[idx,:,0,2]=12 + unet_features[idx,:,0,3]=13 + unet_features[idx,:,1,0]=14 + unet_features[idx,:,1,1]=15 + unet_features[idx,:,1,2]=16 + unet_features[idx,:,1,3]=17 + unet_features[idx,:,2,0]=18 + unet_features[idx,:,2,1]=19 + unet_features[idx,:,2,2]=20 + unet_features[idx,:,2,3]=21 + unet_features[idx,:,3,0]=22 + unet_features[idx,:,3,1]=23 + unet_features[idx,:,3,2]=24 + unet_features[idx,:,3,3]=25 + + #____ + #TODO: decommenta + #unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + # XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.aggregate: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + + #__________________ FIND WHAT FEATURES EACH NODE ACTIVATES ON THE OTHER FEATURE MAPS _____________________ + + ''' + Each views have K neighbors views. + Each views have NumRays rays, each of one has num_samples samples. + Projected_points will contain the pixel (x,y) activated by each one of the num_samples in each neighbor view. + ''' + K = k_near_cameras.shape[-1] + + #(b, num_views, num_nearest_views, num_rays, num_samples, 2) in [-1,1] + projected_points, mask = self.get_nearby_activated_points(cameras,k_near_cameras, ray_origins, ray_directions, sample_coordinates) + + projected_points = projected_points.reshape(B*num_views*K, self.latent_dim**2, self.n_samples, 2) + + # Compute shift per batch + offsets = (torch.arange(B).view(B, 1, 1) * num_views).to(k_near_cameras.device) # [b, 1, 1] + global_k_near_cameras_indices = k_near_cameras + offsets # [b, num_views, k] + + #(b, num_views, num_neighbors, C, H, W) + nearby_unet_features = unet_features[global_k_near_cameras_indices] + + nearby_unet_features = nearby_unet_features.reshape(B*num_views*K, self.latent_dim_embedding, self.latent_dim, self.latent_dim) + + ''' + Ogni riga indica quanto segue: prendi un punto sul raggio, vedi dove si splatta nella vista. Prendi il secondo e vedi dove si splatta nella stessa vista e cosi via. + ''' + #(B*num_views*num_nearest_views, C, num_rays, num_samples) + #find what features each projected point activates + neighbors_activated_features = F.grid_sample( + nearby_unet_features, + projected_points, + align_corners=True, + padding_mode="border", + mode="nearest" #TODO: metti bilinear + ) + + # query.shape + # torch.Size([512, 8, 1371]) + # context.shape + # torch.Size([512, 120, 1371]) + + #(Tot_Num_Rays, num_samples, C) + ray_query_local_features = neighbors_activated_features.permute(0,2,3,1).reshape(B*num_views*K*self.latent_dim**2,self.n_samples, self.latent_dim_embedding) + + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3), planes + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + +def plot_projected_ray(projected_points, batch_idx, ray_idx, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/griglia.png", grid_size=5): + """ + Plotta i punti 2D di un singolo raggio in una data vista. + + """ + points = projected_points[batch_idx, ray_idx] # shape: (num_points, 2) + + fig, ax = plt.subplots(figsize=(5, 5)) + ax.set_xlim(-2, 2) + ax.set_ylim(-2, 2) + + grid_lines = np.linspace(-1, 1, grid_size) + + ax.grid(False) + + # Linee verticali continue tra y=-1 e y=1 + for x in grid_lines: + ax.plot([x, x], [-1, 1], color='gray', linewidth=1.2, alpha=0.7, zorder=0) + + # Linee orizzontali continue tra x=-1 e x=1 + for y in grid_lines: + ax.plot([-1, 1], [y, y], color='gray', linewidth=1.2, alpha=0.7, zorder=0) + + ax.set_xticks(grid_lines) + ax.set_yticks(grid_lines) + + ax.invert_xaxis() + ax.invert_yaxis() + + x = points[:, 0].cpu().numpy() + y = points[:, 1].cpu().numpy() + ax.scatter(x, y, color='red', label='Projected Points') + + for i, (xi, yi) in enumerate(zip(x, y)): + ax.text(xi, yi, str(i), fontsize=8, color='black', ha='center', va='center') + + ax.set_title(f'Batch {batch_idx}, Ray {ray_idx}') + ax.set_xticklabels([]) + ax.set_yticklabels([]) + + plt.tight_layout() + plt.savefig(where_to_save) + plt.close(fig) + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_v2.py b/loomnet/models/extras/feature_aggregator_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..7e50afd0278d3275ae4f4920b60f5be6bf04ffe4 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v2.py @@ -0,0 +1,617 @@ +# https://github.com/zhizdev/sparsefusion/blob/main/sparsefusion/eft.py +import os +from typing import List + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t_old import ( + AdaLayerNorm, + CrossAttention, + Transformer, + GraphTransformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = 32, + number_nearby_hubs_per_projected_point = 8, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {} + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.num_points = num_latent_points + + self.sphere_radius = sphere_radius + + #create point cloud hubs at that level + self.register_buffer('latent_point_xyz', torch.from_numpy(fibonacci_sphere(self.num_points, radius=sphere_radius)).to(torch.float32)) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + self.harmonic_embedding = HarmonicEmbedding() + self.plucker_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + #create point cloud features at that level + self.latent_point_feat = nn.Parameter(torch.randn(self.num_points, self.latent_dim_embedding + self.plucker_dim)) + + #pointwise spatial transformer to transform sample grid in affine manner + self.pointwise_spatial_transformer_model = PointWiseSpatialTransformer(feature_map_spatial_dim=self.latent_dim, feature_map_channel_dim=self.latent_dim_embedding) + + + self.size_grid = ambassadors_feature_grid_resolution[latent_dim] + + #network to make self attention between hubs + self.T1 = Transformer( + in_channels= self.latent_dim_embedding, #dimensione embedding query + context_dim= self.latent_dim_embedding, #dimensione embedding contesto (aggiungo anche il positional encoding) + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[0], + d_head= d_heads_transformers[0], + depth= depths_transformers[0], + type_of_transformer_block='self' + ) + + + #graph transformer to do message passing between latent points + self.GT = GraphTransformer(in_channels=self.latent_dim_embedding + self.plucker_dim, + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query + n_heads=n_heads_transformers[1], + d_head= d_heads_transformers[1], + num_grid_points = self.size_grid**2, + num_views = self.num_views + ) + + self.number_nearby_hubs_per_projected_point = number_nearby_hubs_per_projected_point + + + #transformer to update original feature map (used as query) using updated hubs (used as key-value) + self.T2 = Transformer( + in_channels= self.latent_dim_embedding + self.plucker_dim, #dimensione embedding feature locale + ray embedding + context_dim=self.latent_dim_embedding, #dimensione embedding contesto + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[2], + d_head= d_heads_transformers[2], + depth= depths_transformers[2], + type_of_transformer_block='cross' + ) + + # self.augmenter = UpSampleDecoder(in_channels=self.latent_dim_embedding, + # middle_channels=self.latent_dim_embedding, + # up_factor=math.ceil(math.log2(latent_dim / self.size_grid)), + # group_channels=self.latent_dim_embedding//32) + + self.feature_map_enhancer = FeatureEnhancer(grid_channels=self.latent_dim_embedding, feature_channels=self.latent_dim_embedding, mlp_hidden_dim=self.latent_dim_embedding*2, grid_encoder_hidden_dim=self.latent_dim_embedding, depth=2, gamma_init_values=0) + + #self.splatter = ResnetBlock2D(in_channels=self.latent_dim_embedding, middle_channels=self.latent_dim_embedding, group_channels=32, kernel_size=self.latent_dim//self.size_grid, padding=0 ) + + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + + def forward( + self, + unet_features, + t_emb, + cameras + ): + device = unet_features.device + + #___________________________ FIX (IF NEEDED) UNET FEATURE MAP _____________________ + unet_features = self.resnet(unet_features, t_emb) + + #plot_latent_pointcloud(self.latent_point_xyz.detach().cpu().numpy()) + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + + #plot_pose_cameras_and_latents(c2w.cpu().numpy(), self.latent_point_xyz.detach().cpu().numpy(), self.num_views, 0) + + + #_____________________________________ POINTWISE SPATIAL TRANSFORMER _______________________________ + #____________ Predict the best sample grid to find ambassadors features of each feature map ________ + + #get affine transformation for each grid (B*num_views, num_projected_points, 2, 3) + ambassadors_features, grid = self.pointwise_spatial_transformer_model(unet_features, self.size_grid) + + #plot_grid(grid.detach().cpu(), 0, self.latent_dim) + + + + #________________PROJECT EACH CAMERA SELECTED POINT ON THE SURFACE OF THE LATENT SPHERE _________ + #______ Projects every point in the camera grid space into the world until it intersects the sphere _________ + ray_origins, ray_directions = ray_sample(c2w, intrinsics, grid) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + + local_features_3d_locations, valid_local_features = intersect_ray_sphere_batch(ray_origins=ray_origins.to(device), ray_dirs=ray_directions.to(device), sphere_center=torch.tensor([0,0,0]).to(device), sphere_radius=self.sphere_radius) + + #plot_sphere_cameras_and_projected_points(c2w.cpu().numpy(), self.latent_point_xyz.detach().cpu().numpy(), local_features_3d_locations.detach().cpu().numpy(), self.num_views, 0) + + + #_____________________CONNECT EACH PROJECTED POINT WITH THE NEAREST 3D LATENT POINT (HUB) ____________________________ + #_____________ For each projected point find the closest hubs. Connections are unidirectional!______________________________ + + # Troviamo gli N hub più vicini per ogni punto x proiettato sulla superficie della sfera + B_and_num_views, num_grid_points, _ = local_features_3d_locations.shape + #(B_and_num_views, num_grid_points, 3) -> (B_and_num_views*num_grid_points, 3) + local_features_3d_locations = local_features_3d_locations.view(B_and_num_views*num_grid_points, 3) + + edge_index = knn(x=self.latent_point_xyz, y=local_features_3d_locations, k=self.number_nearby_hubs_per_projected_point) # Edges: da x verso anchors + + #plot_projected_points_connection_with_hubs(self.latent_point_xyz.detach().cpu().numpy(), local_features_3d_locations.detach().cpu().numpy(), edge_index, self.num_views, num_grid_points, self.number_nearby_hubs_per_projected_point, 0) + + + #___________LET EACH PROJECTED POINT COMMUNICATE WITH THE NEIGHBOURING LATENT POINTS FOUND _______________ + #(b, num_views, 1280) + t = t_emb.reshape(B, self.num_views, 1280) + t_b = t[:,0] + #(B*num_views,num_grid_points, C) + ambassadors_features = ambassadors_features.view(B_and_num_views, self.latent_dim_embedding,-1).permute(0,2,1) + #add plucker encoding + ambassadors_features = torch.cat( + (plucker_ray_embedding, ambassadors_features), dim=-1 + ) + #(B, num_views*num_grid_points, C) + ambassadors_features = ambassadors_features.reshape(B, num_views*num_grid_points, self.latent_dim_embedding + self.plucker_dim) + #(B*num_latent_points, C) + updated_hubs = self.GT(ambassadors_features=ambassadors_features, latent_points=self.latent_point_feat, t=t_b, edge_index=edge_index) + #(B, num_latent_points, C) + updated_hubs = updated_hubs.view(B, self.num_points, self.latent_dim_embedding) + + + #________________________ SELF-ATTENTION between hubs _______________________ + #(B, num_latent_points, C) + updated_hubs = self.T1(updated_hubs, t=t_b, context=None, attention_mask=None) + + + #_____________ AMBASSADORS FEATURES UPDATE WITH LATENT POINTS __________ + #(B, num_views*num_grid_points, C) + updated_ambassadors_features = self.T2(ambassadors_features, t_b, context=updated_hubs) + + + + # #____________________________________ RECONSTRUCT FEATURE MAP FROM AMBASSADORS _____________________________________ + # #(B*num_views, num_grid_points, C) + # updated_ambassadors_features = updated_ambassadors_features.view(B*num_views, num_grid_points, self.latent_dim_embedding) + + # #ritorno alla forma matriciale --> (B*num_views, C, latent_dim, latent_dim) + # updated_ambassadors_features = updated_ambassadors_features.permute(0,2,1).reshape(B*num_views, self.latent_dim_embedding, self.size_grid, self.size_grid) + + # updated_feature_map = self.augmenter(updated_ambassadors_features) + + # return updated_feature_map + + + + + + #__________________________________ + + + # #(B*num_views, num_grid_points, C) + # updated_ambassadors_features = updated_ambassadors_features.view(B*num_views, num_grid_points, self.latent_dim_embedding) + + # #ritorno alla forma matriciale --> (B*num_views, C, latent_dim, latent_dim) + # updated_ambassadors_features = updated_ambassadors_features.permute(0,2,1).reshape(B*num_views, self.latent_dim_embedding, self.size_grid, self.size_grid) + + # B, C, H, W = unet_features.shape + # _, _, h, w = updated_ambassadors_features.shape + + + # # Convert normalized grid to pixel coordinates + # x = ((grid[..., 0] + 1) * 0.5) * (self.latent_dim - 1) # shape [B, h, w] + # y = ((grid[..., 1] + 1) * 0.5) * (self.latent_dim - 1) + + # #for each point on the grid find the 4 pixels (y0,x0),(y0,x1),(y1,x0) and (y1,x1) that generated it + # x0 = x.floor().clamp(0, self.latent_dim - 1) + # x1 = (x0 + 1).clamp(0, self.latent_dim - 1) + # y0 = y.floor().clamp(0, self.latent_dim - 1) + # y1 = (y0 + 1).clamp(0, self.latent_dim - 1) + + # # Compute interpolation weights + # wa = (x1 - x) * (y1 - y) + # wb = (x1 - x) * (y - y0) + # wc = (x - x0) * (y1 - y) + # wd = (x - x0) * (y - y0) + + # # Create list of target coordinates and weights + # target_coords = [(x0, y0, wa), (x0, y1, wb), (x1, y0, wc), (x1, y1, wd)] + + # # + # buffer = torch.zeros_like(unet_features) + # # norm = torch.zeros_like(unet_features) + + # #for each near pixel (4 in total) + # for x_idx, y_idx, w in target_coords: + # # [B, h, w] -> [B, 1, h, w] + # w = w.unsqueeze(1) + + # # weight the value of the ambassador feature for the current near pixel (x_idx, y_idx) + # weighted_vals = updated_ambassadors_features * w # [B, C, h, w] + + # # Flatten spatial dims + # for b in range(B): + # xi = x_idx[b].view(-1) # [h*w] + # yi = y_idx[b].view(-1) # [h*w] + # idx = yi * W + xi # Linear index into HxW + + # idx = idx.to(torch.int64) + + # val = weighted_vals[b].reshape(C, -1).transpose(0, 1) # [N, C] + # #norm_w = w[b].reshape(1, -1).repeat(C, 1).transpose(0, 1) # [N, C] + + # buffer[b].view(C, -1).scatter_add_(1, idx.unsqueeze(0).expand(C, -1), val.transpose(0, 1)) + # #norm[b].view(C, -1).scatter_add_(1, idx.unsqueeze(0).expand(C, -1), norm_w.transpose(0, 1)) + + # # # Normalize where updates were applied + # # unet_features_updated = unet_features_updated / (norm + 1e-6) + + # # mask = (norm > 1e-6).float() # 1 dove è stato scritto, 0 altrove + # # unet_features_updated = mask * unet_features_updated + (1 - mask) * unet_features + + # unet_features = unet_features + buffer + + # unet_features = self.splatter(unet_features) + + + # #____________________________________ ENHANCE UNET_FEATURE_MAP USING INFO COLLECTED FROM AMBASSADORS _____________________________________ + #(B*num_views, num_grid_points, C) + updated_ambassadors_features = updated_ambassadors_features.view(B*num_views, num_grid_points, self.latent_dim_embedding) + + # #ritorno alla forma matriciale --> (B*num_views, C, latent_dim, latent_dim) + updated_ambassadors_features = updated_ambassadors_features.permute(0,2,1).reshape(B*num_views, self.latent_dim_embedding, self.size_grid, self.size_grid) + + #enhance feature map + unet_features = self.feature_map_enhancer(unet_features, updated_ambassadors_features) + + + return unet_features + + + + + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt + +def plot_pose_cameras_and_latents(c2w, latent_point_xyz, num_views, batch_idx): + + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=10, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + + #visualizzo solo per il batch 0 (ossia 16 viste) + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Crea la figura + fig = go.Figure() + + # Aggiungi punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict( + size=10, + color='black', + ), + name='Punti latenti' + )) + + # Aggiungi posizioni delle camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict( + size=6, + color='blue', + ), + name='Camere' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti e delle camere', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + + +def plot_projected_points(camera_idx, pixel_locations, path_where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/proiezione_punti_latenti_camera.png"): + + plt.clf() + plt.close() + # Estrai i punti della camera scelta (ad esempio, camera_idx = 0) + camera_pixels = pixel_locations[camera_idx] # shape: [16, 2] + + # Crea una figura per visualizzare i punti + fig, ax = plt.subplots(figsize=(6, 6)) + + p = camera_pixels.detach().cpu().numpy() + + #move to [0,1] + p = (p + 1)/2 + + # Disegna i punti sulla figura + ax.scatter(p[...,1], p[..., 0], color='black', s=50) + + # Aggiungi i bordi dell'area [0, 1] su entrambi gli assi + ax.plot([0, 0], [0, 1], color='red', linestyle='--') # Bordo sinistro + ax.plot([1, 1], [0, 1], color='red', linestyle='--') # Bordo destro + ax.plot([0, 1], [0, 0], color='red', linestyle='--') # Bordo inferiore + ax.plot([0, 1], [1, 1], color='red', linestyle='--') # Bordo superiore + + # Imposta i limiti degli assi per vedere meglio i bordi + ax.set_xlim(-0.2, 1.2) + ax.set_ylim(-0.2, 1.2) + + # Aggiungi etichette e titolo + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_title(f'Proiezione dei Punti Latenti - Camera {camera_idx + 1}') + + # Rimuovi le etichette degli assi + ax.set_xticks(np.arange(-0.2, 1.2, 0.2)) + ax.set_yticks(np.arange(-0.2, 1.2, 0.2)) + ax.invert_yaxis() + # Salva l'immagine + plt.savefig(path_where_to_save) + + +def plot_latent_pointcloud(latent_point_xyz): + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=5, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + +def plot_grid(grid, camera_idx, feature_map_size, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/griglia.png"): + + grid_sample = grid[camera_idx].detach().cpu() + fig, ax = plt.subplots() + x = grid_sample[..., 1].numpy() # colonna + y = grid_sample[..., 0].numpy() # riga + + ax.set_title(f"Grid Sample {camera_idx}") + ax.set_xlim([-1, 1]) + ax.set_ylim([-1, 1]) + ax.set_aspect('equal') + ax.invert_yaxis() + + # disegna griglia di pixel NxN in [-1, 1] + ticks = np.linspace(-1, 1, feature_map_size + 1) + for t in ticks: + ax.axhline(t, color='gray', linestyle='--', linewidth=0.5) + ax.axvline(t, color='gray', linestyle='--', linewidth=0.5) + + # Mostra punti + ax.scatter(x, y, color='red') + + # Mostra etichette delle coordinate + for i in range(x.shape[0]): + for j in range(x.shape[1]): + coord = f"({x[i,j]:.2f}, {y[i,j]:.2f})" + ax.text(x[i,j], y[i,j], coord, fontsize=8, ha='center', va='center') + + fig.savefig(where_to_save) + plt.close(fig) + + +def plot_sphere_cameras_and_projected_points(c2w, latent_point_xyz, local_features_3d_locations, num_views, batch_idx=0,): + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Genera una lista di colori (Set3 ha colori pastello carini) + colors = pc.qualitative.Set3 + num_colors = len(colors) + + # Inizia con la figura esistente + fig = go.Figure() + + # Punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict(size=8, color='black'), + name='Punti latenti' + )) + + # Camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict(size=6, color='blue'), + name='Camere' + )) + + # Aggiungi punti proiettati sulla sfera per ciascuna camera + for i in range(num_views): # usa solo le prime 16 + points = local_features_3d_locations[i] + color = colors[i % num_colors] + + fig.add_trace(go.Scatter3d( + x=points[:, 0], + y=points[:, 1], + z=points[:, 2], + mode='markers', + marker=dict(size=5, color=color), + name=f'Proj Cam {i}' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + aspectmode='manual', + aspectratio=dict(x=1, y=1, z=1) # <-- forzatura aspetto 1:1:1 + ), + title='Punti latenti, Camere e Proiezioni sulla sfera', + margin=dict(l=0, r=0, b=0, t=30), + showlegend=True + ) + + fig.show() + + + + +def plot_projected_points_connection_with_hubs(latent_point_xyz, local_features_3d_locations, edge_index, num_views, num_grid_points, num_nearest_connections, batch_idx): + + latent = latent_point_xyz + latent_scatter = go.Scatter3d( + x=latent[:, 0], + y=latent[:, 1], + z=latent[:, 2], + mode='markers', + marker=dict(size=8, color='black'), + name='Latent Points' + ) + + # 2. Punti rossi (local_features_3d_locations) + local = local_features_3d_locations[batch_idx*(num_views*num_grid_points):batch_idx*(num_views*num_grid_points) + num_views*num_grid_points,:] + local_scatter = go.Scatter3d( + x=local[:, 0], + y=local[:, 1], + z=local[:, 2], + mode='markers', + marker=dict(size=4, color='red'), + name='Local Features' + ) + + # 3. Connessioni blu (edges) + edges = [] + edge_index_np = edge_index[:,batch_idx*(num_views*num_grid_points*num_nearest_connections):batch_idx*(num_views*num_grid_points*num_nearest_connections) + num_views*num_grid_points*num_nearest_connections] + for i in range(edge_index_np.shape[1]): + local_idx = edge_index_np[0, i] + latent_idx = edge_index_np[1, i] + x = [local[local_idx, 0], latent[latent_idx, 0], None] + y = [local[local_idx, 1], latent[latent_idx, 1], None] + z = [local[local_idx, 2], latent[latent_idx, 2], None] + edges.append(go.Scatter3d( + x=x, y=y, z=z, + mode='lines', + line=dict(color='blue', width=2), + showlegend=False + )) + + # Creazione della figura + fig = go.Figure(data=[latent_scatter, local_scatter] + edges) + fig.update_layout(scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='Z' + ), title='3D Feature to Latent Point Mapping') + + fig.show() \ No newline at end of file diff --git a/loomnet/models/extras/feature_aggregator_v3.py b/loomnet/models/extras/feature_aggregator_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..82aaf86ec668ba80c8a798e03ff3c1a8690c5fb5 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v3.py @@ -0,0 +1,528 @@ +# https://github.com/zhizdev/sparsefusion/blob/main/sparsefusion/eft.py +import os +from typing import List + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t_old import ( + AdaLayerNorm, + CrossAttention, + Transformer, + GraphTransformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = 32, + number_nearby_hubs_per_projected_point = 8, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {} + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.num_points = num_latent_points + + self.sphere_radius = sphere_radius + + #create point cloud hubs at that level + self.register_buffer('latent_point_xyz', torch.from_numpy(fibonacci_sphere(self.num_points, radius=sphere_radius)).to(torch.float32)) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + self.harmonic_embedding = HarmonicEmbedding() + self.plucker_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + #create positional embedding of each fibonacci point + latent_point_origins = torch.zeros(self.num_points, 3).unsqueeze(0) + self.plucker_latent_point_embedding = self.encode_plucker(latent_point_origins, self.latent_point_xyz.unsqueeze(0)).squeeze(0) + + #create point cloud features at that level + self.latent_point_feat = nn.Parameter(torch.randn(self.num_points, self.latent_dim_embedding)) + + #pointwise spatial transformer to transform sample grid in affine manner + self.pointwise_spatial_transformer_model = PointWiseSpatialTransformer(feature_map_spatial_dim=self.latent_dim, feature_map_channel_dim=self.latent_dim_embedding) + + + self.size_grid = ambassadors_feature_grid_resolution[latent_dim] + + #network to make self attention between hubs + self.T1 = Transformer( + in_channels= self.latent_dim_embedding, #dimensione embedding query + context_dim= self.latent_dim_embedding, #dimensione embedding contesto (aggiungo anche il positional encoding) + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[0], + d_head= d_heads_transformers[0], + depth= depths_transformers[0], + type_of_transformer_block='self', + zero_out_proj = True + ) + + + #graph transformer to do message passing between latent points + self.GT = GraphTransformer(in_channels=self.latent_dim_embedding + self.plucker_dim, + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query + n_heads=n_heads_transformers[1], + d_head= d_heads_transformers[1], + num_grid_points = self.size_grid**2, + num_views = self.num_views + ) + + self.number_nearby_hubs_per_projected_point = number_nearby_hubs_per_projected_point + + + #transformer to update original feature map (used as query) using updated hubs (used as key-value) + self.T2 = Transformer( + in_channels= self.latent_dim_embedding, #dimensione embedding feature unet token + context_dim=self.latent_dim_embedding, #dimensione embedding contesto + out_channels=self.latent_dim_embedding, #dimensione finale in uscita della query, io lascerei uguale o al massimo comprimerla un pò se la GNN pesa + n_heads= n_heads_transformers[2], + d_head= d_heads_transformers[2], + depth= depths_transformers[2], + type_of_transformer_block='cross', + zero_out_proj = True + ) + + + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + + def forward( + self, + unet_features, + t_emb, + cameras + ): + device = unet_features.device + + #___________________________ FIX (IF NEEDED) UNET FEATURE MAP _____________________ + unet_features = self.resnet(unet_features, t_emb) + + #plot_latent_pointcloud(self.latent_point_xyz.detach().cpu().numpy()) + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + + #plot_pose_cameras_and_latents(c2w.cpu().numpy(), self.latent_point_xyz.detach().cpu().numpy(), self.num_views, 0) + + + #_____________________________________ POINTWISE SPATIAL TRANSFORMER _______________________________ + #____________ Predict the best sample grid to find ambassadors features of each feature map ________ + + #get affine transformation for each grid (B*num_views, num_projected_points, 2, 3) + ambassadors_features, grid = self.pointwise_spatial_transformer_model(unet_features, self.size_grid) + + #plot_grid(grid.detach().cpu(), 0, self.latent_dim) + + + + #________________PROJECT EACH CAMERA SELECTED POINT ON THE SURFACE OF THE LATENT SPHERE _________ + #______ Projects every point in the camera grid space into the world until it intersects the sphere _________ + ray_origins, ray_directions = ray_sample(c2w, intrinsics, grid) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + + local_features_3d_locations, valid_local_features = intersect_ray_sphere_batch(ray_origins=ray_origins.to(device), ray_dirs=ray_directions.to(device), sphere_center=torch.tensor([0,0,0]).to(device), sphere_radius=self.sphere_radius) + + #plot_sphere_cameras_and_projected_points(c2w.cpu().numpy(), self.latent_point_xyz.detach().cpu().numpy(), local_features_3d_locations.detach().cpu().numpy(), self.num_views, 0) + + + #_____________________CONNECT EACH PROJECTED POINT WITH THE NEAREST 3D LATENT POINT (HUB) ____________________________ + #_____________ For each projected point find the closest hubs. Connections are unidirectional!______________________________ + + # Troviamo gli N hub più vicini per ogni punto x proiettato sulla superficie della sfera + B_and_num_views, num_grid_points, _ = local_features_3d_locations.shape + #(B_and_num_views, num_grid_points, 3) -> (B_and_num_views*num_grid_points, 3) + local_features_3d_locations = local_features_3d_locations.view(B_and_num_views*num_grid_points, 3) + + edge_index = knn(x=self.latent_point_xyz, y=local_features_3d_locations, k=self.number_nearby_hubs_per_projected_point) # Edges: da x verso anchors + + #plot_projected_points_connection_with_hubs(self.latent_point_xyz.detach().cpu().numpy(), local_features_3d_locations.detach().cpu().numpy(), edge_index, self.num_views, num_grid_points, self.number_nearby_hubs_per_projected_point, 0) + + + #___________LET EACH PROJECTED POINT COMMUNICATE WITH THE NEIGHBOURING LATENT POINTS FOUND _______________ + #(b, num_views, 1280) + t = t_emb.reshape(B, self.num_views, 1280) + t_b = t[:,0] + #(B*num_views,num_grid_points, C) + ambassadors_features = ambassadors_features.view(B_and_num_views, self.latent_dim_embedding,-1).permute(0,2,1) + #add plucker encoding + ambassadors_features = torch.cat( + (plucker_ray_embedding, ambassadors_features), dim=-1 + ) + #(B, num_views*num_grid_points, C) + ambassadors_features = ambassadors_features.reshape(B, num_views*num_grid_points, self.latent_dim_embedding + self.plucker_dim) + + #add plucker embedding to latent points + latent_points_with_plucker_embedding = torch.cat( (self.plucker_latent_point_embedding.to(self.latent_point_feat.device), self.latent_point_feat), dim=-1) + + #(B*num_latent_points, C) + updated_hubs = self.GT(ambassadors_features=ambassadors_features, latent_points=latent_points_with_plucker_embedding, t=t_b, edge_index=edge_index) + #(B, num_latent_points, C) + updated_hubs = updated_hubs.view(B, self.num_points, self.latent_dim_embedding) + + + #________________________ SELF-ATTENTION between hubs _______________________ + #(B, num_latent_points, C) + updated_hubs = self.T1(updated_hubs, t=t_b, context=None, attention_mask=None) + + + #_____________ AMBASSADORS FEATURES UPDATE WITH LATENT POINTS __________ + #(B, num_views*num_grid_points, C) + B, C, H, W = unet_features.shape + unet_features_tokens = to_tokens(unet_features, B, C, H, W) + updated_hubs = updated_hubs.repeat_interleave(num_views,dim=0) + updated_unet_features_tokens = self.T2(unet_features_tokens, t_b, context=updated_hubs) + + updated_unet_features = from_tokens(updated_unet_features_tokens, H, W) + + + return updated_unet_features + + + + + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt + +def plot_pose_cameras_and_latents(c2w, latent_point_xyz, num_views, batch_idx): + + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=10, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + + #visualizzo solo per il batch 0 (ossia 16 viste) + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Crea la figura + fig = go.Figure() + + # Aggiungi punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict( + size=10, + color='black', + ), + name='Punti latenti' + )) + + # Aggiungi posizioni delle camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict( + size=6, + color='blue', + ), + name='Camere' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti e delle camere', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + + +def plot_projected_points(camera_idx, pixel_locations, path_where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/proiezione_punti_latenti_camera.png"): + + plt.clf() + plt.close() + # Estrai i punti della camera scelta (ad esempio, camera_idx = 0) + camera_pixels = pixel_locations[camera_idx] # shape: [16, 2] + + # Crea una figura per visualizzare i punti + fig, ax = plt.subplots(figsize=(6, 6)) + + p = camera_pixels.detach().cpu().numpy() + + #move to [0,1] + p = (p + 1)/2 + + # Disegna i punti sulla figura + ax.scatter(p[...,1], p[..., 0], color='black', s=50) + + # Aggiungi i bordi dell'area [0, 1] su entrambi gli assi + ax.plot([0, 0], [0, 1], color='red', linestyle='--') # Bordo sinistro + ax.plot([1, 1], [0, 1], color='red', linestyle='--') # Bordo destro + ax.plot([0, 1], [0, 0], color='red', linestyle='--') # Bordo inferiore + ax.plot([0, 1], [1, 1], color='red', linestyle='--') # Bordo superiore + + # Imposta i limiti degli assi per vedere meglio i bordi + ax.set_xlim(-0.2, 1.2) + ax.set_ylim(-0.2, 1.2) + + # Aggiungi etichette e titolo + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_title(f'Proiezione dei Punti Latenti - Camera {camera_idx + 1}') + + # Rimuovi le etichette degli assi + ax.set_xticks(np.arange(-0.2, 1.2, 0.2)) + ax.set_yticks(np.arange(-0.2, 1.2, 0.2)) + ax.invert_yaxis() + # Salva l'immagine + plt.savefig(path_where_to_save) + + +def plot_latent_pointcloud(latent_point_xyz): + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=5, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + +def plot_grid(grid, camera_idx, feature_map_size, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/griglia.png"): + + grid_sample = grid[camera_idx].detach().cpu() + fig, ax = plt.subplots() + x = grid_sample[..., 1].numpy() # colonna + y = grid_sample[..., 0].numpy() # riga + + ax.set_title(f"Grid Sample {camera_idx}") + ax.set_xlim([-1, 1]) + ax.set_ylim([-1, 1]) + ax.set_aspect('equal') + ax.invert_yaxis() + + # disegna griglia di pixel NxN in [-1, 1] + ticks = np.linspace(-1, 1, feature_map_size + 1) + for t in ticks: + ax.axhline(t, color='gray', linestyle='--', linewidth=0.5) + ax.axvline(t, color='gray', linestyle='--', linewidth=0.5) + + # Mostra punti + ax.scatter(x, y, color='red') + + # Mostra etichette delle coordinate + for i in range(x.shape[0]): + for j in range(x.shape[1]): + coord = f"({x[i,j]:.2f}, {y[i,j]:.2f})" + ax.text(x[i,j], y[i,j], coord, fontsize=8, ha='center', va='center') + + fig.savefig(where_to_save) + plt.close(fig) + + +def plot_sphere_cameras_and_projected_points(c2w, latent_point_xyz, local_features_3d_locations, num_views, batch_idx=0,): + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Genera una lista di colori (Set3 ha colori pastello carini) + colors = pc.qualitative.Set3 + num_colors = len(colors) + + # Inizia con la figura esistente + fig = go.Figure() + + # Punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict(size=8, color='black'), + name='Punti latenti' + )) + + # Camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict(size=6, color='blue'), + name='Camere' + )) + + # Aggiungi punti proiettati sulla sfera per ciascuna camera + for i in range(num_views): # usa solo le prime 16 + points = local_features_3d_locations[i] + color = colors[i % num_colors] + + fig.add_trace(go.Scatter3d( + x=points[:, 0], + y=points[:, 1], + z=points[:, 2], + mode='markers', + marker=dict(size=5, color=color), + name=f'Proj Cam {i}' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + aspectmode='manual', + aspectratio=dict(x=1, y=1, z=1) # <-- forzatura aspetto 1:1:1 + ), + title='Punti latenti, Camere e Proiezioni sulla sfera', + margin=dict(l=0, r=0, b=0, t=30), + showlegend=True + ) + + fig.show() + + + + +def plot_projected_points_connection_with_hubs(latent_point_xyz, local_features_3d_locations, edge_index, num_views, num_grid_points, num_nearest_connections, batch_idx): + + latent = latent_point_xyz + latent_scatter = go.Scatter3d( + x=latent[:, 0], + y=latent[:, 1], + z=latent[:, 2], + mode='markers', + marker=dict(size=8, color='black'), + name='Latent Points' + ) + + # 2. Punti rossi (local_features_3d_locations) + local = local_features_3d_locations[batch_idx*(num_views*num_grid_points):batch_idx*(num_views*num_grid_points) + num_views*num_grid_points,:] + local_scatter = go.Scatter3d( + x=local[:, 0], + y=local[:, 1], + z=local[:, 2], + mode='markers', + marker=dict(size=4, color='red'), + name='Local Features' + ) + + # 3. Connessioni blu (edges) + edges = [] + edge_index_np = edge_index[:,batch_idx*(num_views*num_grid_points*num_nearest_connections):batch_idx*(num_views*num_grid_points*num_nearest_connections) + num_views*num_grid_points*num_nearest_connections] + for i in range(edge_index_np.shape[1]): + local_idx = edge_index_np[0, i] + latent_idx = edge_index_np[1, i] + x = [local[local_idx, 0], latent[latent_idx, 0], None] + y = [local[local_idx, 1], latent[latent_idx, 1], None] + z = [local[local_idx, 2], latent[latent_idx, 2], None] + edges.append(go.Scatter3d( + x=x, y=y, z=z, + mode='lines', + line=dict(color='blue', width=2), + showlegend=False + )) + + # Creazione della figura + fig = go.Figure(data=[latent_scatter, local_scatter] + edges) + fig.update_layout(scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='Z' + ), title='3D Feature to Latent Point Mapping') + + fig.show() \ No newline at end of file diff --git a/loomnet/models/extras/feature_aggregator_v4.py b/loomnet/models/extras/feature_aggregator_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..e4495a31cdca53570b569ca718d9563070bc45ee --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v4.py @@ -0,0 +1,1482 @@ +# https://github.com/zhizdev/sparsefusion/blob/main/sparsefusion/eft.py +import os +from typing import List + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + + + +# pyramid pooling +class MultiScalePPM(nn.Module): + def __init__(self, in_channels=1397, out_channels=512, pool_scales=(1, 2, 4, 8, 16)): + super(MultiScalePPM, self).__init__() + self.ppm = nn.ModuleList([ + nn.Sequential( + nn.AdaptiveAvgPool2d(scale), + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(inplace=True) + ) + for scale in pool_scales + ]) + + # Output will be original input + all pooled features + self.output_dim = in_channels + len(pool_scales) * out_channels + + def forward(self, x): + input_size = x.size() + ppm_out = [x] # include original input + for pool in self.ppm: + pooled = pool(x) + upsampled = F.interpolate(pooled, size=input_size[2:], mode='bilinear', align_corners=False) + ppm_out.append(upsampled) + + multiscale_features = torch.cat(ppm_out, dim=1) # (B, in_channels + n * out_channels, H, W) + return multiscale_features + + + +class TriplaneEncoderDecoder(nn.Module): + def __init__(self, plane_resolution = 64, plane_channel_dim = 128): + super().__init__() + self.plane_embeddings = nn.ParameterList([nn.Parameter(torch.randn(1,plane_channel_dim, plane_resolution, plane_resolution)*0.001) for _ in range(3)]) + + # self.decoder = nn.Sequential( + # FuorierTransform(32, 64, scale=1), + # nn.Linear(128, ) + # ) + + def forward(self, coordinates): + + print("") + + +class GroupNorm32(nn.GroupNorm): + def forward(self, x): + return super().forward(x.float()).type(x.dtype) + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + +class TriplaneModulation(nn.Module): + """ + Fonde un triplane learnable con i piani splattati tramite modulation spaziale. + """ + def __init__(self, channels: int, out_channels: int, dropout=0.0): + super().__init__() + + def make_gamma_net(): + return nn.Sequential( + nn.InstanceNorm2d(channels), + nn.Conv2d(channels, channels, kernel_size=3, padding=2, dilation=2), + nn.GELU(), + nn.Conv2d(channels, out_channels*2, kernel_size=3, padding=2, dilation=2), + #nn.Sigmoid() # gamma ∈ [0, 1] + ) + + def make_triplane_linear_layer(): + return nn.Sequential( + GroupNorm32(32, out_channels), + nn.SiLU(), + nn.Conv2d(out_channels, out_channels, 3, padding=1), + ) + + def make_triplane_out_layers(): + return nn.Sequential( + nn.SiLU(), + nn.Dropout(p=dropout), + + nn.Conv2d(out_channels, out_channels, 3, padding=1) + #zero_module( + # nn.Conv2d(out_channels, out_channels, 3, padding=1) + # ), + ) + + self.triplane_linear_layer_XY = make_triplane_linear_layer() + self.triplane_linear_layer_YZ = make_triplane_linear_layer() + self.triplane_linear_layer_XZ = make_triplane_linear_layer() + + self.modulator_xy = make_gamma_net() + self.modulator_yz = make_gamma_net() + self.modulator_xz = make_gamma_net() + + self.out_layer_XY = make_triplane_out_layers() + self.out_layer_YZ = make_triplane_out_layers() + self.out_layer_XZ = make_triplane_out_layers() + + self.norm_XY = GroupNorm32(32, out_channels) + self.norm_YZ = GroupNorm32(32, out_channels) + self.norm_XZ = GroupNorm32(32, out_channels) + + def forward(self, triplaneXY, triplaneYZ, triplaneXZ, + splatted_triplaneXY, splatted_triplaneYZ, splatted_triplaneXZ ): + """ + Args: + T_base: dict con 'xy', 'xz', 'yz' → ciascuno [B, C, H, W] + delta_T: dict con 'xy', 'xz', 'yz' splattati da N viste → [B, C, H, W] + + Returns: + T_final: dict con i triplane condizionati [B, C, H, W] + """ + + B, C, H, W = splatted_triplaneXY.shape + _, C0, _, _ = triplaneXY.shape + + #repeat per batch + triplaneXY = triplaneXY.expand(B, C0, H, W) + triplaneYZ = triplaneYZ.repeat(B, C0, H, W) + triplaneXZ = triplaneXZ.repeat(B, C0, H, W) + + #pass triplane to linear layer + triplaneXY_ = self.triplane_linear_layer_XY(triplaneXY) + triplaneYZ_ = self.triplane_linear_layer_YZ(triplaneYZ) + triplaneXZ_ = self.triplane_linear_layer_XZ(triplaneXZ) + + + #pass splatted triplane into modulator to obtain scale and shift + scale_XY, shift_XY = torch.chunk(self.modulator_xy(splatted_triplaneXY), 2, dim=1) + scale_YZ, shift_YZ = torch.chunk(self.modulator_yz(splatted_triplaneYZ), 2, dim=1) + scale_XZ, shift_XZ = torch.chunk(self.modulator_xz(splatted_triplaneXZ), 2, dim=1) + + # out( norm(h) * (1 + scale) + shift ) + final_triplaneXY = self.out_layer_XY( self.norm_XY(triplaneXY_) * (1+scale_XY) + shift_XY ) + final_triplaneYZ = self.out_layer_YZ(self.norm_YZ(triplaneYZ_) * (1+scale_YZ) + shift_YZ ) + final_triplaneXZ = self.out_layer_XZ(self.norm_XZ(triplaneXZ_) * (1+scale_XZ) + shift_XZ ) + + + + #TODO penso sia errato in quanto triplaneXY ha dimensione 1 + return final_triplaneXY + triplaneXY, final_triplaneYZ + triplaneYZ, final_triplaneXZ + triplaneXZ + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {} + ): + super().__init__() + + self.box_side_lenght = 1.5 + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + #numero di punti da prendere su ogni raggio + self.n_samples = 8 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + #self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + if self.latent_dim == 4: + self.plane_resolution = 256 + elif self.latent_dim == 8: + self.plane_resolution = 256 + elif self.latent_dim == 16: + self.plane_resolution = 256 + elif self.latent_dim == 32: + self.plane_resolution = 256 + + self.plane_dim_channel = 2560 #must be divisible by 5 + + self.resnetfpn_XY = ResnetFPN(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, final_channel_dim = self.plane_dim_channel) + self.resnetfpn_YZ = ResnetFPN(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, final_channel_dim = self.plane_dim_channel) + self.resnetfpn_XZ = ResnetFPN(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, final_channel_dim = self.plane_dim_channel) + + # self.triplane_encoder_decoder = TriplaneEncoderDecoder(plane_resolution=self.plane_resolution, plane_channel_dim=self.latent_dim_embedding) + + # self.triplane_modulator = TriplaneModulation(channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, out_channels = self.latent_dim_embedding) + + self.T1 = Transformer( + in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + context_dim=self.latent_dim_embedding, + out_channels=self.latent_dim_embedding, + n_heads=8, + d_head=32, + depth=2, + ) + + + #to match local context channel dim + # self.transform_XY = nn.Linear(len(pool_scales)*dim_scale+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.latent_dim_embedding, bias=False) + # self.transform_YZ = nn.Linear(len(pool_scales)*dim_scale+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.latent_dim_embedding, bias=False) + # self.transform_XZ = nn.Linear(len(pool_scales)*dim_scale+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.latent_dim_embedding, bias=False) + self.transform_XY = nn.Linear(1280, self.latent_dim_embedding, bias=False) + self.transform_YZ = nn.Linear(1280, self.latent_dim_embedding, bias=False) + self.transform_XZ = nn.Linear(1280, self.latent_dim_embedding, bias=False) + + + #weight each sample contribution + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + self.transform_to_weights = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + + def generate_voxel_centered_points(self, center, side_length, N): + k = round(N ** (1/3)) + assert k ** 3 == N, "N deve essere un cubo perfetto (es. 8, 27, 64...)" + + # Lato del singolo voxel + voxel_size = side_length / k + half = side_length / 2 + + # Offset per centrare i punti nei voxel (mezzo voxel rispetto agli spigoli) + offsets = np.linspace(-half + voxel_size/2, half - voxel_size/2, k) + + # Mesh 3D + x, y, z = np.meshgrid(offsets, offsets, offsets, indexing='ij') + + # Stack e traslazione rispetto al centro del cubo + points = np.stack([x, y, z], axis=-1).reshape(-1, 3) + points += np.array(center) + + return points + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def replicate_edge_index(self, edge_index, N, offset): + edge_list = [] + + for i in range(N): + # Calcola offset per questa replica + delta = i * offset + # Aggiungi offset ai nodi + edge_i = edge_index + delta + edge_list.append(edge_i) + + # Concatenazione lungo la seconda dimension (colonne) + return torch.cat(edge_list, dim=1) + + + def bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid.to(triplane.dtype), mode='bilinear', align_corners=True) + + return sampled + + + + def compute_projections(self, points, cameras): + """ + points: (B, F, (H x W), N_samples, 3) + cameras: (B, F, K, 32) + return: + pixel_locations: (B, F, K, (H x W), N_samples, 2) + mask: (B, F, K, (H x W), N_samples) + """ + b, f, k, _ = cameras.shape + intrinsics = cameras[..., :16].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + c2w = cameras[..., 16:].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + + points = rearrange( + points, "(b f) n s c -> b f n s c", f=f, n=self.latent_dim**2 + ) + points_h = torch.cat( + [points, torch.ones_like(points[..., :1])], dim=-1 + ) # (B, F, (H x W), N_samples, 4) + + points_h = repeat(points_h, "b f n s c -> b f k n s c", k=k) + w2p = torch.matmul(intrinsics, torch.inverse(c2w)) # (B, F, K, 4, 4) + projections = torch.einsum("b f k i j, b f k n s j -> b f k n s i", w2p, points_h) + + pixel_locations = projections[..., :2] / torch.clamp( + projections[..., 2:3], min=1e-8 + ) + pixel_locations = torch.clamp( + pixel_locations, min=-10, max=10 + ) # to avoid grid sample nan + mask = projections[..., 2] > 0 # opencv camera + inbound = ( + (pixel_locations[..., 0] <= 1.0) + & (pixel_locations[..., 0] >= 0) + & (pixel_locations[..., 1] <= 1.0) + & (pixel_locations[..., 1] >= 0) + ) + mask = mask & inbound + pixel_locations = pixel_locations * 2 - 1 + return pixel_locations, mask + + + def fuse_triplane_information_via_pyramid(self, XY, YZ, XZ): + + P2_XY, P3_XY, P4_XY, P5_XY, P6_XY = self.resnetfpn_XY(XY) + _,_, new_H, new_W = P2_XY.shape + # Upsample tutto a 128x128 (risoluzione di P2 / x) + P3_XY_up = F.interpolate(P3_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + P4_XY_up = F.interpolate(P4_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + P5_XY_up = F.interpolate(P5_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + P6_XY_up = F.interpolate(P6_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + # Concatena tutto + fused_XY = torch.cat([P2_XY, P3_XY_up, P4_XY_up, P5_XY_up, P6_XY_up], dim=1) # shape: [B, 256*5, 128, 128] + + + P2_YZ, P3_YZ, P4_YZ, P5_YZ, P6_YZ = self.resnetfpn_YZ(YZ) + # Upsample tutto a 128x128 (risoluzione di P2 / x) + P3_YZ_up = F.interpolate(P3_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P4_YZ_up = F.interpolate(P4_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P5_YZ_up = F.interpolate(P5_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P6_YZ_up = F.interpolate(P6_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + # Concatena tutto + fused_YZ = torch.cat([P2_YZ, P3_YZ_up, P4_YZ_up, P5_YZ_up, P6_YZ_up], dim=1) # shape: [B, 256*5, 128, 128] + + + P2_XZ, P3_XZ, P4_XZ, P5_XZ, P6_XZ = self.resnetfpn_XZ(XZ) + P3_XZ_up = F.interpolate(P3_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P4_XZ_up = F.interpolate(P4_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P5_XZ_up = F.interpolate(P5_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P6_XZ_up = F.interpolate(P6_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + # Concatena tutto + fused_XZ = torch.cat([P2_XZ, P3_XZ_up, P4_XZ_up, P5_XZ_up, P6_XZ_up], dim=1) # shape: [B, 256*5, 128, 128] + + return fused_XY, fused_YZ, fused_XZ + + def fuse_triplane_information_via_pooled_pyramid(self, XY, YZ, XZ): + + multiscale_XY = self.multiscale_XY(XY) + multiscale_YZ = self.multiscale_YZ(YZ) + multiscale_XZ = self.multiscale_XZ(XZ) + + return multiscale_XY, multiscale_YZ, multiscale_XZ + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras + ): + device = unet_features.device + + #___________________________ FIX (IF NEEDED) UNET FEATURE MAP _____________________ + #unet_features = self.resnet(unet_features, t_emb) + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + + #plot_pose_cameras_and_latents(c2w.cpu().numpy(), self.latent_point_xyz.detach().cpu().numpy(), self.num_views, 0) + + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(unet_features.dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid.to(unet_features.dtype), # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features = unet_sampled_features.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + #local_xyz_probes_position_embedding = torch.ones_like(local_xyz_probes_position_embedding) #TODO da eliminare + #TODO DA ELIMINARE I 3 + # XY = self.bilinear_splatting(proj_XY_normalized, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1]), H=128, W=128) + # YZ = self.bilinear_splatting(proj_YZ_normalized, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1]), H=128, W=128) + # XZ = self.bilinear_splatting(proj_XZ_normalized, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1]), H=128, W=128) + + XY = self.bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.plane_resolution, W=self.plane_resolution).to(unet_features.dtype) + YZ = self.bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.plane_resolution, W=self.plane_resolution).to(unet_features.dtype) + XZ = self.bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.plane_resolution, W=self.plane_resolution).to(unet_features.dtype) + + + XY_fused, YZ_fused, XZ_fused = self.fuse_triplane_information_via_pyramid(XY, YZ, XZ) + + #________________ FIND FOR EACH 3D POINT WHAT FEATURES IN OTHER VIEWS ARE ACTIVATED ________________________ + b, f, c = cameras.shape + k_views = k_near_cameras.shape[2] + full_cameras = repeat(cameras, "b k c -> b f k c", f=f) + k_nearest_cameras = torch.zeros(b, f, k_views, c, device=cameras.device) + b_ids = torch.arange(b)[:, None, None].expand(-1, f, k_views).to(cameras.device) + f_ids = torch.arange(f)[None, :, None].expand(b, -1, k_views).to(cameras.device) + # Use advanced indexing to get k nearest cameras + k_nearest_cameras = full_cameras[b_ids, f_ids, k_near_cameras] # (B, F, K, 32) + + # projected_points, mask = self.compute_projections( + # sample_coordinates, k_nearest_cameras + # ) + + #_______________ CREATE CONTEXT: TRIPLANE GLOBAL FEATURE + (LOCAL) PROJECTED FEATURES ________ + ''' + Each ray has 8 samples. In order to update the feature of the ray we will aggregate all the feature + of each sample points. But to update each sample point we need to find what triplane features each one + activate (global context) and what view feature activate (local context of each point) + ''' + #global context___________________________ + global_features_XY = self.sample_triplane(XY_fused, proj_XY_normalized) + global_features_YZ = self.sample_triplane(YZ_fused, proj_YZ_normalized) + global_features_XZ = self.sample_triplane(XZ_fused, proj_XZ_normalized) + + #local context_____________________________ + #(b, num_cameras, num_k_nearest camera) + # global_near_camera_indexes = k_near_cameras + torch.arange(B).unsqueeze(1).unsqueeze(1).to(device) * f + # global_near_camera_indexes = global_near_camera_indexes.reshape(b*f, k_views) + # #((B*num_views*k_near_views, num_rays, num_points, x, y)) + # projected_points_per_near_views = rearrange(projected_points, "b f k n s j -> (b f k) n s j") + # #(B*num_views*k_near_views, C, dim, dim) + # near_unet_features = unet_features[global_near_camera_indexes.reshape(-1)] + + # local_context = F.grid_sample( + # near_unet_features, + # projected_points_per_near_views, + # align_corners=True, + # padding_mode="zeros", + # mode="bilinear" + # ) + + + #____________ CROSS ATTENTION BETWEEN SAMPLE POINTS AND LOCAL/GLOBAL CONTEXT ___________________ + t_emb = repeat(t_emb, "bf c -> (bf n) c", n=self.latent_dim**2) + #(B*Num_Views, Num_Rays, Num_Samples, C) --> (B*Num_Views*Num_Rays, Num_Samples, C) + B_and_num_views, num_rays, num_samples, C = unet_sampled_features_with_position_embedding.shape + query = unet_sampled_features_with_position_embedding.reshape( B_and_num_views*num_rays, num_samples, C) + + # context_local = rearrange( + # local_context, + # "(b f k) c n s -> b f k n s c", + # f=f, + # k=k_views, + # ) + # context_local = rearrange(context_local, "b f k n s c -> (b f n) k s c") + # context_local = rearrange(context_local, "bfn k s c -> bfn (k s) c") + + #indicates what projected point is visible + #mask = rearrange(mask, "b f k n s -> (b f n) k s") + + context_global_XY = self.transform_XY(rearrange(global_features_XY, "b c a (f s n) -> (b f s) n (a c)", f=f, s=num_rays, n=num_samples)) + context_global_YZ = self.transform_YZ(rearrange(global_features_YZ, "b c a (f s n) -> (b f s) n (a c)", f=f, s=num_rays, n=num_samples)) + context_global_XZ = self.transform_XZ(rearrange(global_features_XZ, "b c a (f s n) -> (b f s) n (a c)", f=f, s=num_rays, n=num_samples)) + + ''' + We can remove, for each ray the first n_samples for the local context due to the fact that + this information is equal to the query. + Then we add another mask values (True) for global context + ''' + + # Crea un tensore di True di shape [batch_size, N, last_dim] + #true_padding = torch.ones((mask.shape[0], 3, self.n_samples), dtype=torch.bool).to(device) + #concatenate but remove info equal to the query + #mask = torch.cat((true_padding, mask[:,1:]), dim=1) + #concatenate local and global context and remove info equal to the query + #context = torch.cat([context_global_XY, context_global_YZ, context_global_XZ, context_local[:,num_samples:]], dim=1) + context = torch.cat([context_global_XY, context_global_YZ, context_global_XZ], dim=1) + + + out = self.T1(query, t=t_emb, context=context, attention_mask=None) + + #_______________________ AGGREGATE SAMPLES ALONG ITS RAY ___________________________________ + ''' + Now determines the feature of the feature map pixel aggregating with a softmax + the contribution of each sample along its ray (only the one which is visible at least by one view) + ''' + # mask = ( + # reduce( + # mask[:,3:], + # "bfn k s -> bfn s 1", + # "sum", + # ) + # > 0 + # ) + weight = self.weight_sample(out) + #weight = weight.masked_fill(~mask, torch.finfo(weight.dtype).min) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(out * weight, dim=1) + updated_feature_map = rearrange(updated_feature_map, "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=f, + ) + + + return updated_feature_map + + + + + + + + + + + + + + + + + + + + + + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt + + + + + + +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_projected_points(batch_id, target_cam_id, nearby_cam_id, ray_id, projected_points, grid_size=4, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/projected.png"): + + + def draw_grid(ax, K=10): + ticks = torch.linspace(-1, 1, steps=K+1) + for t in ticks: + ax.plot([-1, 1], [t, t], color='gray', linewidth=0.5, linestyle='--') # orizzontali + ax.plot([t, t], [-1, 1], color='gray', linewidth=0.5, linestyle='--') # verticali + + # Estrai i punti + points = projected_points[batch_id, target_cam_id, nearby_cam_id, ray_id].detach().cpu() # shape: (8, 2) + + # Crea immagine + fig, ax = plt.subplots(figsize=(6, 6)) + ax.set_xlim([-1.1, 1.1]) + ax.set_ylim([-1.1, 1.1]) + ax.set_aspect('equal') + ax.set_title('Ray Points with Labels') + ax.invert_xaxis() + ax.invert_yaxis() + ax.set_xlim([2.5, -2.5]) + ax.set_ylim([2.5, -2.5]) + + + # Disegna quadrato blu + square = patches.Rectangle((-1, -1), 2, 2, linewidth=2, edgecolor='blue', facecolor='none') + ax.add_patch(square) + + # Griglia KxK + draw_grid(ax, K=grid_size) + + # Disegna punti in rosso + x, y = points[:, 0].numpy(), points[:, 1].numpy() + ax.plot(x, y, 'ro-') + + # Aggiungi etichette numeriche + for i, (xi, yi) in enumerate(zip(x, y)): + ax.text(xi, yi, str(i), color='black', fontsize=12, ha='center', va='center') + + # Griglia, salvataggio e visualizzazione + plt.grid(True) + plt.savefig(where_to_save) + plt.show() + + + + +def save_plane_projections(sample_coordinates, filename='/raid/homes/giulio.federico/LoomNet/src/da_eliminare/proiezioni_piani.png'): + """ + Visualizza e salva un'immagine con le proiezioni dei punti 3D sui piani XY, YZ e XZ. + Ogni batch (elemento) è evidenziato con un colore diverso. + + Args: + sample_coordinates (torch.Tensor): tensor di shape [8, 16, 8, 3] con punti 3D. + filename (str): nome del file immagine da salvare. + """ + # Calcolo proiezioni + proj_XY = sample_coordinates[..., :2] # (X,Y) + proj_YZ = sample_coordinates[..., 1:] # (Y,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) # (X,Z) + + # Colori per gli 8 elementi + num_elements = sample_coordinates.shape[0] + colors = plt.cm.get_cmap('tab10', num_elements) + + # Creo una figura con 3 subplot: uno per ogni piano + fig, axes = plt.subplots(1, 3, figsize=(18,6)) + + planes = ['XY', 'YZ', 'XZ'] + projections = [proj_XY, proj_YZ, proj_XZ] + + for ax, plane, proj in zip(axes, planes, projections): + ax.set_title(f'Proiezione sul piano {plane}') + ax.set_xlabel(f'{plane[0]}') + ax.set_ylabel(f'{plane[1]}') + + # Per ogni elemento (batch) + for i in range(num_elements): + # estraggo i punti per l'elemento i: shape [16,8,2] + points = proj[i] # [16,8,2] + # Li appiattisco in 2D [16*8, 2] + points_2d = points.reshape(-1, 2).cpu().numpy() + + ax.scatter(points_2d[:,0], points_2d[:,1], + color=colors(i), s=10, alpha=0.7) + + ax.legend() + + plt.tight_layout() + plt.savefig(filename) + plt.close(fig) # chiudo la figura per liberare memoria + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6, + latent_point = None): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + # --- Punti equidistanti interni al cubo --- + if latent_point is not None: + fig.add_trace(go.Scatter3d( + x=latent_point[:, 0], + y=latent_point[:, 1], + z=latent_point[:, 2], + mode='markers', + marker=dict(size=3, color='black'), + name='Punti Interni' + )) + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +def plot_pose_cameras_and_latents(c2w, latent_point_xyz, num_views, batch_idx): + + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=10, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + + #visualizzo solo per il batch 0 (ossia 16 viste) + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Crea la figura + fig = go.Figure() + + # Aggiungi punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict( + size=10, + color='black', + ), + name='Punti latenti' + )) + + # Aggiungi posizioni delle camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict( + size=6, + color='blue', + ), + name='Camere' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti e delle camere', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + + + + +def plot_latent_pointcloud(latent_point_xyz): + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=5, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + +def plot_grid(grid, camera_idx, feature_map_size, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/griglia.png"): + + grid_sample = grid[camera_idx].detach().cpu() + fig, ax = plt.subplots() + x = grid_sample[..., 1].numpy() # colonna + y = grid_sample[..., 0].numpy() # riga + + ax.set_title(f"Grid Sample {camera_idx}") + ax.set_xlim([-1, 1]) + ax.set_ylim([-1, 1]) + ax.set_aspect('equal') + ax.invert_yaxis() + + # disegna griglia di pixel NxN in [-1, 1] + ticks = np.linspace(-1, 1, feature_map_size + 1) + for t in ticks: + ax.axhline(t, color='gray', linestyle='--', linewidth=0.5) + ax.axvline(t, color='gray', linestyle='--', linewidth=0.5) + + # Mostra punti + ax.scatter(x, y, color='red') + + # Mostra etichette delle coordinate + for i in range(x.shape[0]): + for j in range(x.shape[1]): + coord = f"({x[i,j]:.2f}, {y[i,j]:.2f})" + ax.text(x[i,j], y[i,j], coord, fontsize=8, ha='center', va='center') + + fig.savefig(where_to_save) + plt.close(fig) + + +def plot_sphere_cameras_and_projected_points(c2w, latent_point_xyz, local_features_3d_locations, num_views, batch_idx=0,): + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Genera una lista di colori (Set3 ha colori pastello carini) + colors = pc.qualitative.Set3 + num_colors = len(colors) + + # Inizia con la figura esistente + fig = go.Figure() + + # Punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict(size=8, color='black'), + name='Punti latenti' + )) + + # Camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict(size=6, color='blue'), + name='Camere' + )) + + # Aggiungi punti proiettati sulla sfera per ciascuna camera + for i in range(num_views): # usa solo le prime 16 + points = local_features_3d_locations[i] + color = colors[i % num_colors] + + fig.add_trace(go.Scatter3d( + x=points[:, 0], + y=points[:, 1], + z=points[:, 2], + mode='markers', + marker=dict(size=5, color=color), + name=f'Proj Cam {i}' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + aspectmode='manual', + aspectratio=dict(x=1, y=1, z=1) # <-- forzatura aspetto 1:1:1 + ), + title='Punti latenti, Camere e Proiezioni sulla sfera', + margin=dict(l=0, r=0, b=0, t=30), + showlegend=True + ) + + fig.show() + + + + +def plot_projected_points_connection_with_hubs(latent_point_xyz, local_features_3d_locations, edge_index, num_views, num_grid_points, num_nearest_connections, batch_idx): + + latent = latent_point_xyz + latent_scatter = go.Scatter3d( + x=latent[:, 0], + y=latent[:, 1], + z=latent[:, 2], + mode='markers', + marker=dict(size=8, color='black'), + name='Latent Points' + ) + + # 2. Punti rossi (local_features_3d_locations) + local = local_features_3d_locations[batch_idx*(num_views*num_grid_points):batch_idx*(num_views*num_grid_points) + num_views*num_grid_points,:] + local_scatter = go.Scatter3d( + x=local[:, 0], + y=local[:, 1], + z=local[:, 2], + mode='markers', + marker=dict(size=4, color='red'), + name='Local Features' + ) + + # 3. Connessioni blu (edges) + edges = [] + edge_index_np = edge_index[:,batch_idx*(num_views*num_grid_points*num_nearest_connections):batch_idx*(num_views*num_grid_points*num_nearest_connections) + num_views*num_grid_points*num_nearest_connections] + for i in range(edge_index_np.shape[1]): + local_idx = edge_index_np[0, i] + latent_idx = edge_index_np[1, i] + x = [local[local_idx, 0], latent[latent_idx, 0], None] + y = [local[local_idx, 1], latent[latent_idx, 1], None] + z = [local[local_idx, 2], latent[latent_idx, 2], None] + edges.append(go.Scatter3d( + x=x, y=y, z=z, + mode='lines', + line=dict(color='blue', width=2), + showlegend=False + )) + + # Creazione della figura + fig = go.Figure(data=[latent_scatter, local_scatter] + edges) + fig.update_layout(scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='Z' + ), title='3D Feature to Latent Point Mapping') + + fig.show() \ No newline at end of file diff --git a/loomnet/models/extras/feature_aggregator_v6.py b/loomnet/models/extras/feature_aggregator_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..09dc105c6beab1022d0783146ca6215ec207f429 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v6.py @@ -0,0 +1,1485 @@ +# https://github.com/zhizdev/sparsefusion/blob/main/sparsefusion/eft.py +import os +from typing import List + +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + + + +# pyramid pooling +class MultiScalePPM(nn.Module): + def __init__(self, in_channels=1397, out_channels=512, pool_scales=(1, 2, 4, 8, 16)): + super(MultiScalePPM, self).__init__() + self.ppm = nn.ModuleList([ + nn.Sequential( + nn.AdaptiveAvgPool2d(scale), + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(inplace=True) + ) + for scale in pool_scales + ]) + + # Output will be original input + all pooled features + self.output_dim = in_channels + len(pool_scales) * out_channels + + def forward(self, x): + input_size = x.size() + ppm_out = [x] # include original input + for pool in self.ppm: + pooled = pool(x) + upsampled = F.interpolate(pooled, size=input_size[2:], mode='bilinear', align_corners=False) + ppm_out.append(upsampled) + + multiscale_features = torch.cat(ppm_out, dim=1) # (B, in_channels + n * out_channels, H, W) + return multiscale_features + + + +class TriplaneEncoderDecoder(nn.Module): + def __init__(self, plane_resolution = 64, plane_channel_dim = 128): + super().__init__() + self.plane_embeddings = nn.ParameterList([nn.Parameter(torch.randn(1,plane_channel_dim, plane_resolution, plane_resolution)*0.001) for _ in range(3)]) + + # self.decoder = nn.Sequential( + # FuorierTransform(32, 64, scale=1), + # nn.Linear(128, ) + # ) + + def forward(self, coordinates): + + print("") + + +class GroupNorm32(nn.GroupNorm): + def forward(self, x): + return super().forward(x.float()).type(x.dtype) + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + +class TriplaneModulation(nn.Module): + """ + Fonde un triplane learnable con i piani splattati tramite modulation spaziale. + """ + def __init__(self, channels: int, out_channels: int, dropout=0.0): + super().__init__() + + def make_gamma_net(): + return nn.Sequential( + nn.InstanceNorm2d(channels), + nn.Conv2d(channels, channels, kernel_size=3, padding=2, dilation=2), + nn.GELU(), + nn.Conv2d(channels, out_channels*2, kernel_size=3, padding=2, dilation=2), + #nn.Sigmoid() # gamma ∈ [0, 1] + ) + + def make_triplane_linear_layer(): + return nn.Sequential( + GroupNorm32(32, out_channels), + nn.SiLU(), + nn.Conv2d(out_channels, out_channels, 3, padding=1), + ) + + def make_triplane_out_layers(): + return nn.Sequential( + nn.SiLU(), + nn.Dropout(p=dropout), + + nn.Conv2d(out_channels, out_channels, 3, padding=1) + #zero_module( + # nn.Conv2d(out_channels, out_channels, 3, padding=1) + # ), + ) + + self.triplane_linear_layer_XY = make_triplane_linear_layer() + self.triplane_linear_layer_YZ = make_triplane_linear_layer() + self.triplane_linear_layer_XZ = make_triplane_linear_layer() + + self.modulator_xy = make_gamma_net() + self.modulator_yz = make_gamma_net() + self.modulator_xz = make_gamma_net() + + self.out_layer_XY = make_triplane_out_layers() + self.out_layer_YZ = make_triplane_out_layers() + self.out_layer_XZ = make_triplane_out_layers() + + self.norm_XY = GroupNorm32(32, out_channels) + self.norm_YZ = GroupNorm32(32, out_channels) + self.norm_XZ = GroupNorm32(32, out_channels) + + def forward(self, triplaneXY, triplaneYZ, triplaneXZ, + splatted_triplaneXY, splatted_triplaneYZ, splatted_triplaneXZ ): + """ + Args: + T_base: dict con 'xy', 'xz', 'yz' → ciascuno [B, C, H, W] + delta_T: dict con 'xy', 'xz', 'yz' splattati da N viste → [B, C, H, W] + + Returns: + T_final: dict con i triplane condizionati [B, C, H, W] + """ + + B, C, H, W = splatted_triplaneXY.shape + _, C0, _, _ = triplaneXY.shape + + #repeat per batch + triplaneXY = triplaneXY.expand(B, C0, H, W) + triplaneYZ = triplaneYZ.repeat(B, C0, H, W) + triplaneXZ = triplaneXZ.repeat(B, C0, H, W) + + #pass triplane to linear layer + triplaneXY_ = self.triplane_linear_layer_XY(triplaneXY) + triplaneYZ_ = self.triplane_linear_layer_YZ(triplaneYZ) + triplaneXZ_ = self.triplane_linear_layer_XZ(triplaneXZ) + + + #pass splatted triplane into modulator to obtain scale and shift + scale_XY, shift_XY = torch.chunk(self.modulator_xy(splatted_triplaneXY), 2, dim=1) + scale_YZ, shift_YZ = torch.chunk(self.modulator_yz(splatted_triplaneYZ), 2, dim=1) + scale_XZ, shift_XZ = torch.chunk(self.modulator_xz(splatted_triplaneXZ), 2, dim=1) + + # out( norm(h) * (1 + scale) + shift ) + final_triplaneXY = self.out_layer_XY( self.norm_XY(triplaneXY_) * (1+scale_XY) + shift_XY ) + final_triplaneYZ = self.out_layer_YZ(self.norm_YZ(triplaneYZ_) * (1+scale_YZ) + shift_YZ ) + final_triplaneXZ = self.out_layer_XZ(self.norm_XZ(triplaneXZ_) * (1+scale_XZ) + shift_XZ ) + + + + #TODO penso sia errato in quanto triplaneXY ha dimensione 1 + return final_triplaneXY + triplaneXY, final_triplaneYZ + triplaneYZ, final_triplaneXZ + triplaneXZ + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {} + ): + super().__init__() + + self.box_side_lenght = 1.5 + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + #numero di punti da prendere su ogni raggio + self.n_samples = 8 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + self.plane_resolution = 256 + self.plane_dim_channel = 2560 #must be divisible by 5 + + self.resnetfpn_XY = ResnetFPN(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, final_channel_dim = self.plane_dim_channel) + self.resnetfpn_YZ = ResnetFPN(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, final_channel_dim = self.plane_dim_channel) + self.resnetfpn_XZ = ResnetFPN(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, final_channel_dim = self.plane_dim_channel) + #pool_scales = (2,4,8,16) + # dim_scale = 512 + # self.multiscale_XY = MultiScalePPM(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, out_channels=dim_scale, pool_scales=pool_scales) + # self.multiscale_YZ = MultiScalePPM(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, out_channels=dim_scale, pool_scales=pool_scales) + # self.multiscale_XZ = MultiScalePPM(in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, out_channels=dim_scale, pool_scales=pool_scales) + + # self.triplane_encoder_decoder = TriplaneEncoderDecoder(plane_resolution=self.plane_resolution, plane_channel_dim=self.latent_dim_embedding) + + # self.triplane_modulator = TriplaneModulation(channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, out_channels = self.latent_dim_embedding) + + self.T1 = Transformer( + in_channels=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + context_dim=self.latent_dim_embedding, + out_channels=self.latent_dim_embedding, + n_heads=8, + d_head=32, + depth=2, + ) + + + #to match local context channel dim + # self.transform_XY = nn.Linear(len(pool_scales)*dim_scale+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.latent_dim_embedding, bias=False) + # self.transform_YZ = nn.Linear(len(pool_scales)*dim_scale+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.latent_dim_embedding, bias=False) + # self.transform_XZ = nn.Linear(len(pool_scales)*dim_scale+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.latent_dim_embedding, bias=False) + self.transform_XY = nn.Linear(1280, self.latent_dim_embedding, bias=False) + self.transform_YZ = nn.Linear(1280, self.latent_dim_embedding, bias=False) + self.transform_XZ = nn.Linear(1280, self.latent_dim_embedding, bias=False) + + + #weight each sample contribution + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + self.transform_to_weights = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + + def generate_voxel_centered_points(self, center, side_length, N): + k = round(N ** (1/3)) + assert k ** 3 == N, "N deve essere un cubo perfetto (es. 8, 27, 64...)" + + # Lato del singolo voxel + voxel_size = side_length / k + half = side_length / 2 + + # Offset per centrare i punti nei voxel (mezzo voxel rispetto agli spigoli) + offsets = np.linspace(-half + voxel_size/2, half - voxel_size/2, k) + + # Mesh 3D + x, y, z = np.meshgrid(offsets, offsets, offsets, indexing='ij') + + # Stack e traslazione rispetto al centro del cubo + points = np.stack([x, y, z], axis=-1).reshape(-1, 3) + points += np.array(center) + + return points + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def replicate_edge_index(self, edge_index, N, offset): + edge_list = [] + + for i in range(N): + # Calcola offset per questa replica + delta = i * offset + # Aggiungi offset ai nodi + edge_i = edge_index + delta + edge_list.append(edge_i) + + # Concatenazione lungo la seconda dimension (colonne) + return torch.cat(edge_list, dim=1) + + + def bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + + + def compute_projections(self, points, cameras): + """ + points: (B, F, (H x W), N_samples, 3) + cameras: (B, F, K, 32) + return: + pixel_locations: (B, F, K, (H x W), N_samples, 2) + mask: (B, F, K, (H x W), N_samples) + """ + b, f, k, _ = cameras.shape + intrinsics = cameras[..., :16].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + c2w = cameras[..., 16:].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + + points = rearrange( + points, "(b f) n s c -> b f n s c", f=f, n=self.latent_dim**2 + ) + points_h = torch.cat( + [points, torch.ones_like(points[..., :1])], dim=-1 + ) # (B, F, (H x W), N_samples, 4) + + points_h = repeat(points_h, "b f n s c -> b f k n s c", k=k) + w2p = torch.matmul(intrinsics, torch.inverse(c2w)) # (B, F, K, 4, 4) + projections = torch.einsum("b f k i j, b f k n s j -> b f k n s i", w2p, points_h) + + pixel_locations = projections[..., :2] / torch.clamp( + projections[..., 2:3], min=1e-8 + ) + pixel_locations = torch.clamp( + pixel_locations, min=-10, max=10 + ) # to avoid grid sample nan + mask = projections[..., 2] > 0 # opencv camera + inbound = ( + (pixel_locations[..., 0] <= 1.0) + & (pixel_locations[..., 0] >= 0) + & (pixel_locations[..., 1] <= 1.0) + & (pixel_locations[..., 1] >= 0) + ) + mask = mask & inbound + pixel_locations = pixel_locations * 2 - 1 + return pixel_locations, mask + + + def fuse_triplane_information_via_pyramid(self, XY, YZ, XZ): + + P2_XY, P3_XY, P4_XY, P5_XY, P6_XY = self.resnetfpn_XY(XY) + _,_, new_H, new_W = P2_XY.shape + # Upsample tutto a 128x128 (risoluzione di P2 / x) + P3_XY_up = F.interpolate(P3_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + P4_XY_up = F.interpolate(P4_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + P5_XY_up = F.interpolate(P5_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + P6_XY_up = F.interpolate(P6_XY, size=(new_H, new_W), mode='bilinear', align_corners=False) + # Concatena tutto + fused_XY = torch.cat([P2_XY, P3_XY_up, P4_XY_up, P5_XY_up, P6_XY_up], dim=1) # shape: [B, 256*5, 128, 128] + + + P2_YZ, P3_YZ, P4_YZ, P5_YZ, P6_YZ = self.resnetfpn_YZ(YZ) + # Upsample tutto a 128x128 (risoluzione di P2 / x) + P3_YZ_up = F.interpolate(P3_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P4_YZ_up = F.interpolate(P4_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P5_YZ_up = F.interpolate(P5_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P6_YZ_up = F.interpolate(P6_YZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + # Concatena tutto + fused_YZ = torch.cat([P2_YZ, P3_YZ_up, P4_YZ_up, P5_YZ_up, P6_YZ_up], dim=1) # shape: [B, 256*5, 128, 128] + + + P2_XZ, P3_XZ, P4_XZ, P5_XZ, P6_XZ = self.resnetfpn_XZ(XZ) + P3_XZ_up = F.interpolate(P3_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P4_XZ_up = F.interpolate(P4_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P5_XZ_up = F.interpolate(P5_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + P6_XZ_up = F.interpolate(P6_XZ, size=(new_H, new_W), mode='bilinear', align_corners=False) + # Concatena tutto + fused_XZ = torch.cat([P2_XZ, P3_XZ_up, P4_XZ_up, P5_XZ_up, P6_XZ_up], dim=1) # shape: [B, 256*5, 128, 128] + + return fused_XY, fused_YZ, fused_XZ + + def fuse_triplane_information_via_pooled_pyramid(self, XY, YZ, XZ): + + multiscale_XY = self.multiscale_XY(XY) + multiscale_YZ = self.multiscale_YZ(YZ) + multiscale_XZ = self.multiscale_XZ(XZ) + + return multiscale_XY, multiscale_YZ, multiscale_XZ + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras + ): + device = unet_features.device + + #___________________________ FIX (IF NEEDED) UNET FEATURE MAP _____________________ + unet_features = self.resnet(unet_features, t_emb) + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + + #plot_pose_cameras_and_latents(c2w.cpu().numpy(), self.latent_point_xyz.detach().cpu().numpy(), self.num_views, 0) + + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features = unet_sampled_features.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + #local_xyz_probes_position_embedding = torch.ones_like(local_xyz_probes_position_embedding) #TODO da eliminare + #TODO DA ELIMINARE I 3 + # XY = self.bilinear_splatting(proj_XY_normalized, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1]), H=128, W=128) + # YZ = self.bilinear_splatting(proj_YZ_normalized, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1]), H=128, W=128) + # XZ = self.bilinear_splatting(proj_XZ_normalized, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1]), H=128, W=128) + + XY = self.bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.plane_resolution, W=self.plane_resolution) + YZ = self.bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.plane_resolution, W=self.plane_resolution) + XZ = self.bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.plane_resolution, W=self.plane_resolution) + #XY,YZ,XZ = torch.rand((1,self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding,256,256)).to(device), torch.rand((1,self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding,256,256)).to(device), torch.rand((1,self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding,256,256)).to(device) + #________________ CONDITION TRIPLANE_________________________________ + ''' + Given the XY, YZ and XZ planes, use them to condition the triplane embeddings + ''' + + #spread info + XY_fused, YZ_fused, XZ_fused = self.fuse_triplane_information_via_pyramid(XY, YZ, XZ) + #XY, YZ, XZ = self.fuse_triplane_information_via_pooled_pyramid(XY, YZ, XZ) + + + #________________ FIND FOR EACH 3D POINT WHAT FEATURES IN OTHER VIEWS ARE ACTIVATED ________________________ + b, f, c = cameras.shape + k_views = k_near_cameras.shape[2] + full_cameras = repeat(cameras, "b k c -> b f k c", f=f) + k_nearest_cameras = torch.zeros(b, f, k_views, c, device=cameras.device) + b_ids = torch.arange(b)[:, None, None].expand(-1, f, k_views).to(cameras.device) + f_ids = torch.arange(f)[None, :, None].expand(b, -1, k_views).to(cameras.device) + # Use advanced indexing to get k nearest cameras + k_nearest_cameras = full_cameras[b_ids, f_ids, k_near_cameras] # (B, F, K, 32) + + projected_points, mask = self.compute_projections( + sample_coordinates, k_nearest_cameras + ) + + #_______________ CREATE CONTEXT: TRIPLANE GLOBAL FEATURE + (LOCAL) PROJECTED FEATURES ________ + ''' + Each ray has 8 samples. In order to update the feature of the ray we will aggregate all the feature + of each sample points. But to update each sample point we need to find what triplane features each one + activate (global context) and what view feature activate (local context of each point) + ''' + #global context___________________________ + global_features_XY = self.sample_triplane(XY_fused, proj_XY_normalized) + global_features_YZ = self.sample_triplane(YZ_fused, proj_YZ_normalized) + global_features_XZ = self.sample_triplane(XZ_fused, proj_XZ_normalized) + + #local context_____________________________ + #(b, num_cameras, num_k_nearest camera) + global_near_camera_indexes = k_near_cameras + torch.arange(B).unsqueeze(1).unsqueeze(1).to(device) * f + global_near_camera_indexes = global_near_camera_indexes.reshape(b*f, k_views) + #((B*num_views*k_near_views, num_rays, num_points, x, y)) + projected_points_per_near_views = rearrange(projected_points, "b f k n s j -> (b f k) n s j") + #(B*num_views*k_near_views, C, dim, dim) + near_unet_features = unet_features[global_near_camera_indexes.reshape(-1)] + + local_context = F.grid_sample( + near_unet_features, + projected_points_per_near_views, + align_corners=True, + padding_mode="zeros", + mode="bilinear" + ) + + + #____________ CROSS ATTENTION BETWEEN SAMPLE POINTS AND LOCAL/GLOBAL CONTEXT ___________________ + t_emb = repeat(t_emb, "bf c -> (bf n) c", n=self.latent_dim**2) + #(B*Num_Views, Num_Rays, Num_Samples, C) --> (B*Num_Views*Num_Rays, Num_Samples, C) + B_and_num_views, num_rays, num_samples, C = unet_sampled_features_with_position_embedding.shape + query = unet_sampled_features_with_position_embedding.reshape( B_and_num_views*num_rays, num_samples, C) + + context_local = rearrange( + local_context, + "(b f k) c n s -> b f k n s c", + f=f, + k=k_views, + ) + context_local = rearrange(context_local, "b f k n s c -> (b f n) k s c") + context_local = rearrange(context_local, "bfn k s c -> bfn (k s) c") + + #indicates what projected point is visible + mask = rearrange(mask, "b f k n s -> (b f n) k s") + + context_global_XY = self.transform_XY(rearrange(global_features_XY, "b c a (f s n) -> (b f s) n (a c)", f=f, s=num_rays, n=num_samples)) + context_global_YZ = self.transform_YZ(rearrange(global_features_YZ, "b c a (f s n) -> (b f s) n (a c)", f=f, s=num_rays, n=num_samples)) + context_global_XZ = self.transform_XZ(rearrange(global_features_XZ, "b c a (f s n) -> (b f s) n (a c)", f=f, s=num_rays, n=num_samples)) + + ''' + We can remove, for each ray the first n_samples for the local context due to the fact that + this information is equal to the query. + Then we add another mask values (True) for global context + ''' + + # Crea un tensore di True di shape [batch_size, N, last_dim] + true_padding = torch.ones((mask.shape[0], 3, self.n_samples), dtype=torch.bool).to(device) + #concatenate but remove info equal to the query + mask = torch.cat((true_padding, mask[:,1:]), dim=1) + #concatenate local and global context and remove info equal to the query + context = torch.cat([context_global_XY, context_global_YZ, context_global_XZ, context_local[:,num_samples:]], dim=1) + + + out = self.T1(query, t=t_emb, context=context, attention_mask=mask) + + #_______________________ AGGREGATE SAMPLES ALONG ITS RAY ___________________________________ + ''' + Now determines the feature of the feature map pixel aggregating with a softmax + the contribution of each sample along its ray (only the one which is visible at least by one view) + ''' + mask = ( + reduce( + mask[:,3:], + "bfn k s -> bfn s 1", + "sum", + ) + > 0 + ) + weight = self.weight_sample(out) + weight = weight.masked_fill(~mask, torch.finfo(weight.dtype).min) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(out * weight, dim=1) + updated_feature_map = rearrange(updated_feature_map, "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=f, + ) + + + return updated_feature_map + + + + + + + + + + + + + + + + + + + + + + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt + + + + + + +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_projected_points(batch_id, target_cam_id, nearby_cam_id, ray_id, projected_points, grid_size=4, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/projected.png"): + + + def draw_grid(ax, K=10): + ticks = torch.linspace(-1, 1, steps=K+1) + for t in ticks: + ax.plot([-1, 1], [t, t], color='gray', linewidth=0.5, linestyle='--') # orizzontali + ax.plot([t, t], [-1, 1], color='gray', linewidth=0.5, linestyle='--') # verticali + + # Estrai i punti + points = projected_points[batch_id, target_cam_id, nearby_cam_id, ray_id].detach().cpu() # shape: (8, 2) + + # Crea immagine + fig, ax = plt.subplots(figsize=(6, 6)) + ax.set_xlim([-1.1, 1.1]) + ax.set_ylim([-1.1, 1.1]) + ax.set_aspect('equal') + ax.set_title('Ray Points with Labels') + ax.invert_xaxis() + ax.invert_yaxis() + ax.set_xlim([2.5, -2.5]) + ax.set_ylim([2.5, -2.5]) + + + # Disegna quadrato blu + square = patches.Rectangle((-1, -1), 2, 2, linewidth=2, edgecolor='blue', facecolor='none') + ax.add_patch(square) + + # Griglia KxK + draw_grid(ax, K=grid_size) + + # Disegna punti in rosso + x, y = points[:, 0].numpy(), points[:, 1].numpy() + ax.plot(x, y, 'ro-') + + # Aggiungi etichette numeriche + for i, (xi, yi) in enumerate(zip(x, y)): + ax.text(xi, yi, str(i), color='black', fontsize=12, ha='center', va='center') + + # Griglia, salvataggio e visualizzazione + plt.grid(True) + plt.savefig(where_to_save) + plt.show() + + + + +def save_plane_projections(sample_coordinates, filename='/raid/homes/giulio.federico/LoomNet/src/da_eliminare/proiezioni_piani.png'): + """ + Visualizza e salva un'immagine con le proiezioni dei punti 3D sui piani XY, YZ e XZ. + Ogni batch (elemento) è evidenziato con un colore diverso. + + Args: + sample_coordinates (torch.Tensor): tensor di shape [8, 16, 8, 3] con punti 3D. + filename (str): nome del file immagine da salvare. + """ + # Calcolo proiezioni + proj_XY = sample_coordinates[..., :2] # (X,Y) + proj_YZ = sample_coordinates[..., 1:] # (Y,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) # (X,Z) + + # Colori per gli 8 elementi + num_elements = sample_coordinates.shape[0] + colors = plt.cm.get_cmap('tab10', num_elements) + + # Creo una figura con 3 subplot: uno per ogni piano + fig, axes = plt.subplots(1, 3, figsize=(18,6)) + + planes = ['XY', 'YZ', 'XZ'] + projections = [proj_XY, proj_YZ, proj_XZ] + + for ax, plane, proj in zip(axes, planes, projections): + ax.set_title(f'Proiezione sul piano {plane}') + ax.set_xlabel(f'{plane[0]}') + ax.set_ylabel(f'{plane[1]}') + + # Per ogni elemento (batch) + for i in range(num_elements): + # estraggo i punti per l'elemento i: shape [16,8,2] + points = proj[i] # [16,8,2] + # Li appiattisco in 2D [16*8, 2] + points_2d = points.reshape(-1, 2).cpu().numpy() + + ax.scatter(points_2d[:,0], points_2d[:,1], + color=colors(i), s=10, alpha=0.7) + + ax.legend() + + plt.tight_layout() + plt.savefig(filename) + plt.close(fig) # chiudo la figura per liberare memoria + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6, + latent_point = None): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + # --- Punti equidistanti interni al cubo --- + if latent_point is not None: + fig.add_trace(go.Scatter3d( + x=latent_point[:, 0], + y=latent_point[:, 1], + z=latent_point[:, 2], + mode='markers', + marker=dict(size=3, color='black'), + name='Punti Interni' + )) + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +def plot_pose_cameras_and_latents(c2w, latent_point_xyz, num_views, batch_idx): + + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=10, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + + #visualizzo solo per il batch 0 (ossia 16 viste) + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Crea la figura + fig = go.Figure() + + # Aggiungi punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict( + size=10, + color='black', + ), + name='Punti latenti' + )) + + # Aggiungi posizioni delle camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict( + size=6, + color='blue', + ), + name='Camere' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti e delle camere', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + + + + +def plot_latent_pointcloud(latent_point_xyz): + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + fig = go.Figure(data=[go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', # <-- solo markers, nessuna linea + marker=dict( + size=5, + color='black', + ) + )]) + + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + ), + title='Posizioni dei punti latenti', + margin=dict(l=0, r=0, b=0, t=30) + ) + + fig.show() + + +def plot_grid(grid, camera_idx, feature_map_size, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/griglia.png"): + + grid_sample = grid[camera_idx].detach().cpu() + fig, ax = plt.subplots() + x = grid_sample[..., 1].numpy() # colonna + y = grid_sample[..., 0].numpy() # riga + + ax.set_title(f"Grid Sample {camera_idx}") + ax.set_xlim([-1, 1]) + ax.set_ylim([-1, 1]) + ax.set_aspect('equal') + ax.invert_yaxis() + + # disegna griglia di pixel NxN in [-1, 1] + ticks = np.linspace(-1, 1, feature_map_size + 1) + for t in ticks: + ax.axhline(t, color='gray', linestyle='--', linewidth=0.5) + ax.axvline(t, color='gray', linestyle='--', linewidth=0.5) + + # Mostra punti + ax.scatter(x, y, color='red') + + # Mostra etichette delle coordinate + for i in range(x.shape[0]): + for j in range(x.shape[1]): + coord = f"({x[i,j]:.2f}, {y[i,j]:.2f})" + ax.text(x[i,j], y[i,j], coord, fontsize=8, ha='center', va='center') + + fig.savefig(where_to_save) + plt.close(fig) + + +def plot_sphere_cameras_and_projected_points(c2w, latent_point_xyz, local_features_3d_locations, num_views, batch_idx=0,): + + x, y, z = latent_point_xyz[:, 0], latent_point_xyz[:, 1], latent_point_xyz[:, 2] + + camera_positions = c2w[batch_idx*num_views:batch_idx*num_views+num_views, :3, 3] + cam_x, cam_y, cam_z = camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2] + + # Genera una lista di colori (Set3 ha colori pastello carini) + colors = pc.qualitative.Set3 + num_colors = len(colors) + + # Inizia con la figura esistente + fig = go.Figure() + + # Punti latenti (neri) + fig.add_trace(go.Scatter3d( + x=x, + y=y, + z=z, + mode='markers', + marker=dict(size=8, color='black'), + name='Punti latenti' + )) + + # Camere (blu) + fig.add_trace(go.Scatter3d( + x=cam_x, + y=cam_y, + z=cam_z, + mode='markers', + marker=dict(size=6, color='blue'), + name='Camere' + )) + + # Aggiungi punti proiettati sulla sfera per ciascuna camera + for i in range(num_views): # usa solo le prime 16 + points = local_features_3d_locations[i] + color = colors[i % num_colors] + + fig.add_trace(go.Scatter3d( + x=points[:, 0], + y=points[:, 1], + z=points[:, 2], + mode='markers', + marker=dict(size=5, color=color), + name=f'Proj Cam {i}' + )) + + # Layout + fig.update_layout( + scene=dict( + xaxis=dict(title='X', range=[-1.6, 1.6]), + yaxis=dict(title='Y', range=[-1.6, 1.6]), + zaxis=dict(title='Z', range=[-1.6, 1.6]), + aspectmode='manual', + aspectratio=dict(x=1, y=1, z=1) # <-- forzatura aspetto 1:1:1 + ), + title='Punti latenti, Camere e Proiezioni sulla sfera', + margin=dict(l=0, r=0, b=0, t=30), + showlegend=True + ) + + fig.show() + + + + +def plot_projected_points_connection_with_hubs(latent_point_xyz, local_features_3d_locations, edge_index, num_views, num_grid_points, num_nearest_connections, batch_idx): + + latent = latent_point_xyz + latent_scatter = go.Scatter3d( + x=latent[:, 0], + y=latent[:, 1], + z=latent[:, 2], + mode='markers', + marker=dict(size=8, color='black'), + name='Latent Points' + ) + + # 2. Punti rossi (local_features_3d_locations) + local = local_features_3d_locations[batch_idx*(num_views*num_grid_points):batch_idx*(num_views*num_grid_points) + num_views*num_grid_points,:] + local_scatter = go.Scatter3d( + x=local[:, 0], + y=local[:, 1], + z=local[:, 2], + mode='markers', + marker=dict(size=4, color='red'), + name='Local Features' + ) + + # 3. Connessioni blu (edges) + edges = [] + edge_index_np = edge_index[:,batch_idx*(num_views*num_grid_points*num_nearest_connections):batch_idx*(num_views*num_grid_points*num_nearest_connections) + num_views*num_grid_points*num_nearest_connections] + for i in range(edge_index_np.shape[1]): + local_idx = edge_index_np[0, i] + latent_idx = edge_index_np[1, i] + x = [local[local_idx, 0], latent[latent_idx, 0], None] + y = [local[local_idx, 1], latent[latent_idx, 1], None] + z = [local[local_idx, 2], latent[latent_idx, 2], None] + edges.append(go.Scatter3d( + x=x, y=y, z=z, + mode='lines', + line=dict(color='blue', width=2), + showlegend=False + )) + + # Creazione della figura + fig = go.Figure(data=[latent_scatter, local_scatter] + edges) + fig.update_layout(scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='Z' + ), title='3D Feature to Latent Point Mapping') + + fig.show() \ No newline at end of file diff --git a/loomnet/models/extras/feature_aggregator_v7.py b/loomnet/models/extras/feature_aggregator_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..136c23e62e79fea5d0a363a50e9ed5eacd236b84 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v7.py @@ -0,0 +1,1085 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + @torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {} + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.box_side_lenght = 1.5 + self.n_samples = 16 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + #timestep dim + mod_dim = 1280 + + if self.latent_dim in [4]: + num_layers = 2 + num_heads = 4 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [8]: + num_layers = 3 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [16]: + num_layers = 4 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + else: + num_layers = 6 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + + + #risoluzione del triplane + self.plane_resolution = 32 + + ''' + TRIPLANE TOKENS + ''' + self.pos_embed = nn.Parameter(torch.randn(1, 3*self.plane_resolution**2, inner_dim) * (1. / inner_dim) ** 0.5) + + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + + # self.downsampler_XY = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_YZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_XZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + # nn.init.zeros_(self.upsampler.weight) + # nn.init.zeros_(self.upsampler.bias) + + self.decoder = OSGDecoder(n_features=inner_dim*3+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + x = self.pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features = unet_sampled_features.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + # XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + updated_feature_map = rearrange(updated_feature_map, "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3) + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_v8.py b/loomnet/models/extras/feature_aggregator_v8.py new file mode 100644 index 0000000000000000000000000000000000000000..5d28fcfad0b0081541ff4181f93d896bc16281c9 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v8.py @@ -0,0 +1,1149 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolution: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True, + do_global_rendering = False, + is_last_communication_block = False + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.do_global_rendering = do_global_rendering + + self.use_positional_encoding = use_positional_encoding + + self.is_last_communication_block = is_last_communication_block + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + self.splat_plane_resolution = splat_plane_resolution + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.do_latent_rendering: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + if self.do_global_rendering: + self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim ), hidden_dim=self.latent_dim_embedding*3, out_dim=self.latent_dim_embedding) + else: + self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + if self.do_global_rendering: + decoded_sampled_features = self.decoder(torch.cat([global_features, local_xyz_probes_position_embedding.reshape(B, -1, local_xyz_probes_position_embedding.shape[-1])], dim=-1)) + else: + decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + if self.is_last_communication_block: + return updated_feature_map.transpose(2,3), planes + else: + return updated_feature_map.transpose(2,3), x + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_v8_test.py b/loomnet/models/extras/feature_aggregator_v8_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5eaefbdf502d4edcf883a0cd5c2426b3079cbf81 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_v8_test.py @@ -0,0 +1,1137 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + #@torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + embed_dim: int = 0, + latent_dim: int = 0, + sphere_radius = 0.8, + num_latent_points = {}, + number_nearby_hubs_per_projected_point = {}, # numero di hub a cui ogni punto proiettato invierà la sua info + n_heads_transformers: List=[], + d_heads_transformers: List=[], + depths_transformers: List=[], + ambassadors_feature_grid_resolution = {}, + aggregate = False #if true aggregates info to update feature map + ): + super().__init__() + + self.num_views = num_views-1 + + self.aggregate = aggregate + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.box_side_lenght = 1.5 + self.n_samples = 16 + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + #timestep dim + mod_dim = 1280 + + if self.latent_dim in [4]: + num_layers = 3 + num_heads = 4 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [8]: + num_layers = 4 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + elif self.latent_dim in [16]: + num_layers = 6 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + else: + num_layers = 8 + num_heads = 8 + self.splat_plane_resolution = 64 + inner_dim = 512 + + + #risoluzione del triplane + self.plane_resolution = 32 + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + + # self.downsampler_XY = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_YZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + # self.downsampler_XZ = nn.Conv2d(self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, kernel_size=2, stride=2, padding=0) + + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.aggregate: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + self.decoder = OSGDecoder(n_features=inner_dim*3+self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding, hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + # num_aggregator_layers = 2 + # num_heads_aggregator = 8 + # self.samples_aggregator_layers = nn.ModuleList([ + # TransformerAggregator(inner_dim=self.latent_dim_embedding, + # mod_dim=mod_dim, + # cond_dim=self.latent_dim_embedding, + # num_heads=num_heads_aggregator, + # eps=1e-6) for _ in range(num_aggregator_layers) + # ]) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='nearest', align_corners=True) #TODO METTI BILINEARE + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='nearest', #TODO METTI BILINEAR + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + #TODO DECOMMENTARE PRIMA + #unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features2[:,:,:,:117], unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + # XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + # XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution) + + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.aggregate: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #TODO DECOMMENTA PRIMA + # #__________________ DECODE SAMPLED FEATURES__________________ + # decoded_sampled_features = self.decoder(torch.cat([unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), global_features], dim=-1)) + decoded_sampled_features = unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]) + + #TODO DECOMMENTA PRIMA + # #__________________AGGREGATE RAY SAMPLES____________________ + # #[Num_Rays, Num_Samples, C]) + # decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, 437) + + + #TODO DECOMMENTA LE 3 + # weight = self.weight_sample(decoded_sampled_features) + # weight = F.softmax(weight, dim=1) + # updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + updated_feature_map = decoded_sampled_features[:,0,-320:] + + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return unet_features, planes #updated_feature_map.transpose(2,3), planes #TODO METTI UPDATE... + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_with_distillation.py b/loomnet/models/extras/feature_aggregator_with_distillation.py new file mode 100644 index 0000000000000000000000000000000000000000..92b04ce01f0264cd78411dd4810f23dbef40a2a7 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_with_distillation.py @@ -0,0 +1,1165 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [N, num_tokens, D] + # cond: [N, num_views, num_tokens, D_cond] + # mod: [N, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY = query_x_XY.reshape(B, num_tokens, C1) + x_YZ = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ = query_x_XZ.reshape(B, num_tokens, C1) + + x = torch.cat([x_XY, x_YZ, x_XZ], dim=1) + before_sa = self.norm2(x, mod) + x = x + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x = x + self.mlp(self.norm3(x, mod)) + return x + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + @torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolution: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.use_positional_encoding = use_positional_encoding + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + self.splat_plane_resolution = splat_plane_resolution + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + + if self.do_latent_rendering: + + self.upsampler = nn.ConvTranspose2d(inner_dim, inner_dim, kernel_size=2, stride=2, padding=0) + + self.decoder = OSGDecoder(n_features=inner_dim*3+ (self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), hidden_dim=self.latent_dim_embedding, out_dim=self.latent_dim_embedding) + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed, + global_step = None, + training = True + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + # Proiezione sul piano XY (X,Y) + proj_XY = sample_coordinates[..., :2] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = sample_coordinates[..., 1:] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = torch.stack((sample_coordinates[..., 0], sample_coordinates[..., 2]), dim=-1) + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + #TODO: usa random (iniezione rumore) solo durante training + if global_step <= 37544: #TODO SOSTITUISCI 37000 NEL CONFIG + fl = unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]) + fl = fl * torch.rand_like(fl)*0.01 if training else fl + global_features = global_features * torch.rand_like(global_features)*0.01 if training else global_features + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = self.decoder(torch.cat([fl, global_features], dim=-1)) + decoded_sampled_features_by_teacher = None + alpha = 1.0 + else: + # Annealing fl + anneal_steps = 15000 #TODO SOSTITUISCI 15000 nel config + alpha = max(0.0, 1.0 - (global_step - 37544) / anneal_steps) #TODO sostituisci 37544 nel config + + fl = unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]) + #fl = fl * torch.rand_like(fl)*0.01 if training else fl + fl_masked = torch.zeros_like(fl)#fl * (torch.rand_like(fl) < alpha).float() + global_features = global_features * torch.rand_like(global_features)*0.01 if training else global_features + + # Forward teacher + with torch.no_grad(): + decoded_sampled_features_by_teacher = self.decoder(torch.cat([fl, global_features], dim=-1)) + decoded_sampled_features_by_teacher = decoded_sampled_features_by_teacher.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + #forward student + decoded_sampled_features_by_student = self.decoder(torch.cat([fl_masked, global_features], dim=-1)) + + decoded_sampled_features = decoded_sampled_features_by_student + + + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3), planes, decoded_sampled_features, decoded_sampled_features_by_teacher, alpha if self.latent_dim == 32 else x + + else: + return unet_features, x, None, None, None + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/loomnet/models/extras/feature_aggregator_with_projection.py b/loomnet/models/extras/feature_aggregator_with_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..a34abf252c295f21f4b4d28e936ad8b712f83926 --- /dev/null +++ b/loomnet/models/extras/feature_aggregator_with_projection.py @@ -0,0 +1,1223 @@ +import os +from typing import List +import itertools +import torch +import torch.nn.functional as F +from einops import rearrange, reduce, repeat +from torch import nn + +from loomnet.models.blocks.resnet import ResBlock +from loomnet.models.blocks.transformer_t import ( + Transformer +) +from loomnet.models.blocks.pointwise_spatial_transformer import PointWiseSpatialTransformer, apply_pos_embed +import torch_geometric +from torch_cluster import knn, radius_graph, knn_graph +import numpy as np +import math +from loomnet.utils.generic_utils import fibonacci_sphere, ray_sample, intersect_ray_sphere_batch +from loomnet.models.blocks.generic_blocks import FeatureEnhancer, HarmonicEmbedding, to_tokens, from_tokens +from loomnet.models.blocks.resnet_fpn import ResnetFPN + + +import math + +class ResUpBlock(nn.Module): + def __init__(self, in_channels, out_channels): + super().__init__() + self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1) + self.norm1 = nn.GroupNorm(32, out_channels) + self.act = nn.SiLU() + self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1) + self.norm2 = nn.GroupNorm(32, out_channels) + self.upsample = nn.ConvTranspose2d(out_channels, out_channels, 4, stride=2, padding=1) + self.skip = nn.Conv2d(in_channels, out_channels, 1) + + def forward(self, x): + identity = self.skip(x) + x = self.act(self.norm1(self.conv1(x))) + x = self.norm2(self.conv2(x)) + identity + x = self.act(x) + x = self.upsample(x) + return x + + +class Downsampler(nn.Module): + def __init__(self, input_dim, splat_plane_resolution, target_resolution=32): + super().__init__() + assert splat_plane_resolution % target_resolution == 0, "La risoluzione deve essere multipla di quella target" + num_downsamples = int(math.log2(splat_plane_resolution // target_resolution)) + + layers = [] + if num_downsamples!=0: + for _ in range(num_downsamples): + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=2, + stride=2, + padding=0 + )) + else: + layers.append(nn.Conv2d( + in_channels=input_dim, + out_channels=input_dim, + kernel_size=1, + stride=1, + padding=0 + )) + + self.downsampler = nn.Sequential(*layers) + + def forward(self, x): + return self.downsampler(x) + + +class ModLN(nn.Module): + """ + Modulation with adaLN. + + References: + DiT: https://github.com/facebookresearch/DiT/blob/main/models.py#L101 + """ + def __init__(self, inner_dim: int, mod_dim: int, eps: float): + super().__init__() + self.norm = nn.LayerNorm(inner_dim, eps=eps) + self.mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(mod_dim, inner_dim * 2), + ) + + @staticmethod + def modulate(x, shift, scale): + # x: [N, L, D] + # shift, scale: [N, D] + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + shift, scale = self.mlp(mod).chunk(2, dim=-1) # [N, D] + return self.modulate(self.norm(x), shift, scale) # [N, L, D] + + +class ConditionModulationBlock(nn.Module): + + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0., plane_res: int = 32): + super().__init__() + self.norm1_XY = ModLN(inner_dim, mod_dim, eps) + self.norm1_YZ = ModLN(inner_dim, mod_dim, eps) + self.norm1_XZ = ModLN(inner_dim, mod_dim, eps) + self.cross_attn_XY = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_YZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.cross_attn_XZ = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + + self.norm2 = ModLN(inner_dim, mod_dim, eps) + self.self_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, + dropout=attn_drop, bias=attn_bias, batch_first=True) + self.norm3 = ModLN(inner_dim, mod_dim, eps) + self.mlp = nn.Sequential( + nn.Linear(inner_dim, int(inner_dim * mlp_ratio)), + nn.GELU(), + nn.Dropout(mlp_drop), + nn.Linear(int(inner_dim * mlp_ratio), inner_dim), + nn.Dropout(mlp_drop), + ) + + self.xy_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.yz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + self.xz_embed = nn.Parameter(torch.randn(plane_res, plane_res, inner_dim)) + + self.xy_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.yz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + self.xz_embed_splatted = nn.Parameter(torch.randn(plane_res, plane_res, cond_dim)) + + ''' + The learnable triplane has 3 planes: XY, YZ and XZ. + The splatted planes are Num_Views. + Now we want to make cross attention between each pixel of each triplane plane and the other + Num_Views feature vector in the same position + ''' + def forward(self, x, mod, XY, YZ, XZ): + # x: [B, num_tokens, D] + # XY: [B, num_views, num_tokens, D_cond] + # YZ: [B, num_views, num_tokens, D_cond] + # YZ: [B, num_views, num_tokens, D_cond] + # mod: [B, D_mod] + + x_XY, x_YZ, x_XZ = torch.chunk(x, chunks=3, dim=1) + + B, num_tokens, C1 = x_XY.shape + query_x_XY = x_XY.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_YZ = x_YZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + query_x_XZ = x_XZ.reshape(B*num_tokens, 1, C1) #[B*num_tokens, 1, C1] + + #positional encoding + query_xy_pe = self.xy_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_yz_pe = self.yz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + query_xz_pe = self.xz_embed.reshape(-1, C1).unsqueeze(0).repeat(B, 1, 1).reshape(B * num_tokens, 1, C1) # [1024, D] + + # add positional encodings to query + query_x_XY = query_x_XY + query_xy_pe + query_x_YZ = query_x_YZ + query_yz_pe + query_x_XZ = query_x_XZ + query_xz_pe + + + B, V, N, C2 = XY.shape + key_value_XY = XY.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_YZ = YZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + key_value_XZ = XZ.permute(0,2,1,3).reshape(B*num_tokens, V, C2) + + key_value_xy_pe = self.xy_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_yz_pe = self.yz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + key_value_xz_pe = self.xz_embed_splatted.reshape(-1, C2).unsqueeze(0).repeat(B, 1, V).reshape(B * num_tokens, V, C2) + + #add positional encodings to key-value tokens + key_value_XY = key_value_XY + key_value_xy_pe + key_value_YZ = key_value_YZ + key_value_yz_pe + key_value_XZ = key_value_XZ + key_value_xz_pe + + query_mod = mod.repeat_interleave(num_tokens, dim=0) + query_x_XY = query_x_XY + self.cross_attn_XY(self.norm1_XY(query_x_XY, query_mod), key_value_XY, key_value_XY, need_weights=False)[0] + query_x_YZ = query_x_YZ + self.cross_attn_YZ(self.norm1_YZ(query_x_YZ, query_mod), key_value_YZ, key_value_YZ, need_weights=False)[0] + query_x_XZ = query_x_XZ + self.cross_attn_XZ(self.norm1_XZ(query_x_XZ, query_mod), key_value_XZ, key_value_XZ, need_weights=False)[0] + + x_XY_tokens = query_x_XY.reshape(B, num_tokens, C1) + x_YZ_tokens = query_x_YZ.reshape(B, num_tokens, C1) + x_XZ_tokens = query_x_XZ.reshape(B, num_tokens, C1) + + x_tokens = torch.cat([x_XY_tokens, x_YZ_tokens, x_XZ_tokens], dim=1) + before_sa = self.norm2(x_tokens, mod) + x_tokens = x_tokens + self.self_attn(before_sa, before_sa, before_sa, need_weights=False)[0] + x_tokens = x_tokens + self.mlp(self.norm3(x_tokens, mod)) + return x_tokens + + + +class TransformerAggregator(nn.Module): + def __init__(self, inner_dim: int, mod_dim: int, cond_dim: int, num_heads: int, eps: float, + attn_drop: float = 0., attn_bias: bool = False, + mlp_ratio: float = 4., mlp_drop: float = 0.): + super().__init__() + + self.norm = ModLN(inner_dim, mod_dim, eps) + self.cross_attn = nn.MultiheadAttention( + embed_dim=inner_dim, num_heads=num_heads, kdim=cond_dim, vdim=cond_dim, + dropout=attn_drop, bias=attn_bias, batch_first=True) + + def forward(self, x, mod, cond): + # original_feature: [B*num_views*num_rays, 1, C]) + # cond: [Num_Rays, Num_Samples, C]) + # mod: [N, D_mod] + B, _ = mod.shape + B_num_view_num_rays, _, _ = x.shape + + query_mod = mod.repeat_interleave(B_num_view_num_rays//B, dim=0) + x = x + self.cross_attn(self.norm(x, query_mod), cond, cond, need_weights=False)[0] + return x + +class OSGDecoder(nn.Module): + """ + Triplane decoder that gives RGB and sigma values from sampled features. + Using ReLU here instead of Softplus in the original implementation. + + Reference: + EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112 + """ + def __init__(self, n_features: int, + hidden_dim: int = 64, out_dim: int = 4, num_layers: int = 4, activation: nn.Module = nn.ReLU): + super().__init__() + self.net = nn.Sequential( + nn.Linear(n_features, hidden_dim), + activation(), + *itertools.chain(*[[ + nn.Linear(hidden_dim, hidden_dim), + activation(), + ] for _ in range(num_layers - 2)]), + nn.Linear(hidden_dim, out_dim), + ) + # init all bias to zero + # for m in self.modules(): + # if isinstance(m, nn.Linear): + # nn.init.zeros_(m.bias) + + #sampled_features: (Num_points, 96) + @torch.compile #TODO(NB: COMMENTA SOLO PER DEBUG ALTRIMENTI NON TI ENTRA) + def forward(self, sampled_features): + x = self.net(sampled_features) + + return x + + + +class FeatureAggregator(nn.Module): + def __init__( + self, + dim: int, + num_views: int = 1, + n_samples_per_ray: int = 16, + num_weaving_layers_per_decoder_block: List=[], + num_weaving_heads_per_decoder_block: List=[], + plane_channel_dim: int = 512, + plane_resolution: int = 32, + splat_plane_resolution: int = 64, + latent_rendering_stages: List=[], + do_local_bilinear_splatting = True, + embed_dim: int = 0, + latent_dim: int = 0, + use_positional_encoding: bool = True, + triplane_upsample_channel_dim: int = 32 + ): + super().__init__() + + self.num_views = num_views-1 + + #risoluzione spaziale (H o W) della latente a quel livello + self.latent_dim = latent_dim + + #number of channels of the latent at that level + self.latent_dim_embedding = dim + + self.do_local_bilinear_splatting = do_local_bilinear_splatting + + self.use_positional_encoding = use_positional_encoding + + self.box_side_lenght = 1.5 + self.n_samples = n_samples_per_ray + + self.harmonic_embedding = HarmonicEmbedding() + self.ray_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + self.ray_sample_embedding_dim = HarmonicEmbedding.get_output_dim_static( + 3, n_harmonic_functions=6, append_input=True + ) + + self.resnet = ResBlock(dim, 1280, use_scale_shift_norm=True) + + self.expand_init_tokens = nn.Linear(437, 512) + + #timestep dim + mod_dim = 1280 + + inner_dim = plane_channel_dim + + self.splat_plane_resolution = splat_plane_resolution + + if self.latent_dim in [4]: + num_layers = num_weaving_layers_per_decoder_block[0] + num_heads = num_weaving_heads_per_decoder_block[0] + self.do_latent_rendering = latent_rendering_stages[0] + elif self.latent_dim in [8]: + num_layers = num_weaving_layers_per_decoder_block[1] + num_heads = num_weaving_heads_per_decoder_block[1] + self.do_latent_rendering = latent_rendering_stages[1] + elif self.latent_dim in [16]: + num_layers = num_weaving_layers_per_decoder_block[2] + num_heads = num_weaving_heads_per_decoder_block[2] + self.do_latent_rendering = latent_rendering_stages[2] + else: + num_layers = num_weaving_layers_per_decoder_block[3] + num_heads = num_weaving_heads_per_decoder_block[3] + self.do_latent_rendering = latent_rendering_stages[3] + + + #risoluzione del triplane + self.plane_resolution = plane_resolution + + self.downsampler_XY = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_YZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + self.downsampler_XZ = Downsampler(input_dim=self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + splat_plane_resolution=self.splat_plane_resolution, + target_resolution=self.plane_resolution) + + self.layers = nn.ModuleList([ + ConditionModulationBlock(inner_dim, + mod_dim, + self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding, + num_heads=num_heads, eps=1e-6, plane_res=plane_resolution) + for _ in range(num_layers) + ]) + self.norm = nn.LayerNorm(inner_dim, eps=1e-6) + + #Generate the canonica axis of the 3 planes + self.plane_axes = self.generate_planes() + + + if self.do_latent_rendering: + + #self.upsampler = nn.ConvTranspose2d(inner_dim, triplane_upsample_channel_dim, kernel_size=2, stride=2, padding=0) + + self.upsampler = nn.Sequential( + ResUpBlock(512, 256), # 32 → 64 + ResUpBlock(256, 128), # 64 → 128 + ) + + self.decoder = OSGDecoder(n_features=384, hidden_dim=self.latent_dim_embedding*2, out_dim=self.latent_dim_embedding) #TODO: Parametrizza 384 + + self.weight_sample = nn.Linear(self.latent_dim_embedding, 1, bias=False) + + + def forward_layer(self, layer, x, mod, XY, YZ, XZ): + return layer(x, mod, XY, YZ, XZ) + + def ray_sample(self, cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs, uv + + + def encode_plucker(self, ray_origins, ray_dirs): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = self.harmonic_embedding(plucker) + return plucker + + def sample_stratified( + self, + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, + ): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = self.linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + def linspace(self, start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + def get_ray_limits_box(self, rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + def sample_points(self, ray_origins, ray_directions, box_side_lenght=None, n_samples=8, disparity_space_sampling = True, return_depth=False, type_of_sampling="in-the-box"): + if type_of_sampling == "in-the-box": + ray_start, ray_end = self.get_ray_limits_box( + ray_origins, ray_directions, box_side_length=box_side_lenght + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = self.sample_stratified( + ray_origins, + ray_start, + ray_end, + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = self.sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + n_samples, + disparity_space_sampling, + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + + def local_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + Now each view aggregates its own points to its own plane, returning [B, V, C, H, W]. + + Args: + xy: [B, V, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, V, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, V, C, H, W] + """ + B, V, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] # [B, V, N] + y = xy[..., 1] # [B, V, N] + + x0 = torch.floor(x).long().clamp(0, W - 1) # [B, V, N] + x1 = (x0 + 1).clamp(0, W - 1) # [B, V, N] + y0 = torch.floor(y).long().clamp(0, H - 1) # [B, V, N] + y1 = (y0 + 1).clamp(0, H - 1) # [B, V, N] + + wa = (x1.float() - x) * (y1.float() - y) # [B, V, N] + wb = (x1.float() - x) * (y - y0.float()) # [B, V, N] + wc = (x - x0.float()) * (y1.float() - y) # [B, V, N] + wd = (x - x0.float()) * (y - y0.float()) # [B, V, N] + + def splat_weighted(x_idx, y_idx, weight, features): + # Prepare indices + idx_b = torch.arange(B, device=device).view(B, 1, 1).expand(B, V, N) # [B, V, N] + idx_v = torch.arange(V, device=device).view(1, V, 1).expand(B, V, N) # [B, V, N] + + # Calculate flat indices for each view's plane + flat_idx = idx_b * (V * H * W) + idx_v * (H * W) + y_idx * W + x_idx # [B, V, N] + + # Flatten all dimensions except channels + features_flat = features.reshape(-1, C) # [B*V*N, C] + weights_flat = weight.reshape(-1, 1) # [B*V*N, 1] + idx_flat = flat_idx.reshape(-1, 1).expand(-1, C) # [B*V*N, C] + + # Accumulate in a tensor that has space for all views + accum_feat = torch.zeros(B * V * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * V * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.reshape(-1, 1), weights_flat) + + # Reshape to separate batches and views + accum_feat = accum_feat.view(B, V, H, W, C).permute(0, 1, 4, 2, 3) # [B, V, C, H, W] + accum_weight = accum_weight.view(B, V, H, W).unsqueeze(2) # [B, V, 1, H, W] + + return accum_feat, accum_weight + + # Sum up the splatted contributions and weights for each corner + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, V, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, V, C, H, W] + + + + + def global_bilinear_splatting(self, xy, features, H, W): + """ + Differentiable splatting using bilinear interpolation and scatter_add. + + NB: this version aggregates all splatted points from all the views in a single plane. + + Args: + xy: [B, N, 2] coordinates in [0, W-1] and [0, H-1] + features: [B, N, C] feature vectors + H, W: Output grid size + + Returns: + grid: [B, C, H, W] + """ + B, N, C = features.shape + device = features.device + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + x = xy[..., 0] + y = xy[..., 1] + + x0 = torch.floor(x).long().clamp(0, W - 1) + x1 = (x0 + 1).clamp(0, W - 1) + y0 = torch.floor(y).long().clamp(0, H - 1) + y1 = (y0 + 1).clamp(0, H - 1) + + wa = (x1.float() - x) * (y1.float() - y) + wb = (x1.float() - x) * (y - y0.float()) + wc = (x - x0.float()) * (y1.float() - y) + wd = (x - x0.float()) * (y - y0.float()) + + def splat_weighted(x_idx, y_idx, weight, features): + idx_b = torch.arange(B, device=device).unsqueeze(1).expand(B, N) # [B, N] + flat_idx = idx_b * H * W + y_idx * W + x_idx # [B, N] + + # Flattened target + features_flat = features.view(-1, C) + + weights_flat = weight.view(-1, 1) + #weights_flat = torch.ones_like(weight.view(-1, 1)) + + + idx_flat = flat_idx.view(-1, 1).expand(-1, C) # [B*N, C] + + accum_feat = torch.zeros(B * H * W, C, device=device) + accum_feat.scatter_add_(0, idx_flat, features_flat * weights_flat) + + accum_weight = torch.zeros(B * H * W, 1, device=device) + accum_weight.scatter_add_(0, flat_idx.view(-1, 1), weights_flat) + + return accum_feat.view(B, H, W, C).permute(0, 3, 1, 2), \ + accum_weight.view(B, H, W).unsqueeze(1) # [B, 1, H, W] + + # Sum up the splatted contributions and weights + fa, wa_sum = splat_weighted(x0, y0, wa, features) + fb, wb_sum = splat_weighted(x0, y1, wb, features) + fc, wc_sum = splat_weighted(x1, y0, wc, features) + fd, wd_sum = splat_weighted(x1, y1, wd, features) + + feat_sum = fa + fb + fc + fd + weight_sum = wa_sum + wb_sum + wc_sum + wd_sum # [B, 1, H, W] + + # Avoid division by zero and avoid instability + eps = 1e-6 + mask = weight_sum > eps + feat_norm = torch.where(mask, feat_sum / (weight_sum + eps), torch.zeros_like(feat_sum)) + + return feat_norm # [B, C, H, W] + + def reshape_upsample(self, tokens): + N = tokens.shape[0] + H = W = self.plane_resolution + x = tokens.view(N, 3, H, W, -1) + x = torch.einsum('nihwd->indhw', x) # [3, N, D, H, W] + x = x.contiguous().view(3*N, -1, H, W) # [3*N, D, H, W] + x = self.upsampler(x) # [3*N, D', H', W'] + x = x.view(3, N, *x.shape[-3:]) # [3, N, D', H', W'] + x = torch.einsum('indhw->nidhw', x) # [N, 3, D', H', W'] + x = x.contiguous() + return x + + def sample_triplane(self, triplane, xy): + + B, C, H, W = triplane.shape + + xy = xy.clone() + + # Scale normalized coordinates to grid size + xy[..., 0] *= (W - 1) + xy[..., 1] *= (H - 1) + + # Converti xy da [0, W-1] / [0, H-1] a [-1, 1] + xy_norm = xy.clone() + xy_norm[..., 0] = (xy[..., 0] / (W - 1)) * 2 - 1 # x: [0, W-1] -> [-1, 1] + xy_norm[..., 1] = (xy[..., 1] / (H - 1)) * 2 - 1 # y: [0, H-1] -> [-1, 1] + + # grid_sample vuole [B, H_out, W_out, 2], ma noi vogliamo campionare N punti singoli. + # Li trattiamo come H_out=1, W_out=N + grid = xy_norm.unsqueeze(1) # [B, 1, N, 2] + + # grid_sample richiede che l'ultimo dim abbia l'ordine (x, y) + grid = grid # già in [x, y], quindi non serve invertire + + # Usa grid_sample per campionare + sampled = F.grid_sample(triplane, grid, mode='bilinear', align_corners=True) + + return sampled + + def generate_planes(self): + """ + Defines planes by the three vectors that form the "axes" of the + plane. Should work with arbitrary number of planes and planes of + arbitrary orientation. + + Bugfix reference: https://github.com/NVlabs/eg3d/issues/67 + """ + return torch.tensor([[[1, 0, 0], + [0, 1, 0], + [0, 0, 1]], + [[1, 0, 0], + [0, 0, 1], + [0, 1, 0]], + [[0, 0, 1], + [0, 1, 0], + [1, 0, 0]]], dtype=torch.float32) + + def project_onto_planes(self, plane_axes, coordinates): + """ + Does a projection of a 3D point onto a batch of 2D planes, + returning 2D plane coordinates. + + Takes plane axes of shape n_planes, 3, 3 + # Takes coordinates of shape N, M, 3 + # returns projections of shape N*n_planes, M, 2 + """ + N, M, C = coordinates.shape + n_planes, _, _ = plane_axes.shape + coordinates = coordinates.unsqueeze(1).expand(-1, n_planes, -1, -1).reshape(N*n_planes, M, 3) + inv_planes = torch.linalg.inv(plane_axes).unsqueeze(0).expand(N, -1, -1, -1).reshape(N*n_planes, 3, 3) + projections = torch.bmm(coordinates, inv_planes) + return projections[..., :2] + + + + def forward( + self, + unet_features, + t_emb, + cameras, + k_near_cameras, + pos_embed + ): + device = unet_features.device + + + # #TODO ELIMINA + # unet_features*=0 + # idx=0 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + # idx=4 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=10 + # unet_features[idx,:,0,2]=20 + # unet_features[idx,:,0,3]=30 + # unet_features[idx,:,1,0]=40 + # unet_features[idx,:,1,1]=50 + # unet_features[idx,:,1,2]=60 + # unet_features[idx,:,1,3]=70 + # unet_features[idx,:,2,0]=80 + # unet_features[idx,:,2,1]=90 + # unet_features[idx,:,2,2]=100 + # unet_features[idx,:,2,3]=110 + # unet_features[idx,:,3,0]=120 + # unet_features[idx,:,3,1]=130 + # unet_features[idx,:,3,2]=140 + # unet_features[idx,:,3,3]=150 + # idx=19 + # unet_features[idx,:,0,0]=0.1 + # unet_features[idx,:,0,1]=1 + # unet_features[idx,:,0,2]=2 + # unet_features[idx,:,0,3]=3 + # unet_features[idx,:,1,0]=4 + # unet_features[idx,:,1,1]=5 + # unet_features[idx,:,1,2]=6 + # unet_features[idx,:,1,3]=7 + # unet_features[idx,:,2,0]=8 + # unet_features[idx,:,2,1]=9 + # unet_features[idx,:,2,2]=10 + # unet_features[idx,:,2,3]=11 + # unet_features[idx,:,3,0]=12 + # unet_features[idx,:,3,1]=13 + # unet_features[idx,:,3,2]=14 + # unet_features[idx,:,3,3]=15 + + #____ + unet_features = self.resnet(unet_features, t_emb) + + #_________________ REPEAT TRIPLANE POS TOKENS FOR EACH BATCH _________________________ + B_and_num_views = unet_features.shape[0] + current_dtype = unet_features.dtype + if pos_embed.shape[0] == 1: + x = pos_embed.repeat(B_and_num_views//self.num_views, 1, 1).to(current_dtype) + else: + x = pos_embed + + #___________________________ LOAD POSE AND INTRINSIC _______________ + B, num_views = cameras.shape[0], cameras.shape[1] + + intrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + intrinsics = rearrange(intrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + + #________________________ GENERATE RAY SAMPLES ___________________________ + #for each pixel in the feature map, generates ray origin and direction + ray_origins, ray_directions, uv_grid = self.ray_sample(c2w, intrinsics, resolution=self.latent_dim) + + #give a identification of each ray useful to know from what camera and what direction come from + if self.use_positional_encoding: + plucker_ray_embedding = self.encode_plucker(ray_origins, ray_directions) + + #for each ray, generates N points along the ray inside a predefined cube + #(B_num_views, num_rays, 3) xyz coordinates of the points along each ray for each view + sample_coordinates, sample_directions, sample_depths = self.sample_points( + ray_origins, ray_directions, box_side_lenght=self.box_side_lenght, disparity_space_sampling=False, return_depth=True, n_samples=self.n_samples, + ) + + #___________________ ENCODE EACH SAMPLES ________________________________ + if self.use_positional_encoding: + #give a identification of each point (use ray position as prefix) + local_xyz_probes_position_embedding = self.harmonic_embedding(sample_coordinates) + plucker_expanded = plucker_ray_embedding.unsqueeze(2).expand(-1, -1, self.n_samples, -1) # shape: [160, 16, 8, 78] + local_xyz_probes_position_embedding = torch.cat([plucker_expanded, local_xyz_probes_position_embedding], dim=-1).to(current_dtype) + + #attach the relative feature sampled from unet map (equal for each sampled point along the ray) + #convert uv grid from [0,1] -> [-1, 1] + #uv_grid = uv_grid[..., [1, 0]] # scambia (y, x) → (x, y) + uv_grid = uv_grid * 2 - 1 + uv_grid = uv_grid.unsqueeze(2) + + # Campionamento + sampled_features = F.grid_sample( + unet_features, # (160, 1280, 4, 4) + uv_grid, # (160, 16, 1, 2) + mode='bilinear', + align_corners=True, + padding_mode="border" + ) # Output: (160, 1280, 16, 1) + + # Rimuoviamo la dimensione 1 + unet_sampled_features = sampled_features.squeeze(-1).to(current_dtype) # (160, 1280, 16) + unet_sampled_features = unet_sampled_features.permute(0, 2, 1) + unet_sampled_features2 = unet_sampled_features.unsqueeze(2) # (160, 16, 1, 1280) + unet_sampled_features2 = unet_sampled_features2.expand(-1, -1, self.n_samples, -1) # (160, 16, 8, 1280) + + if self.use_positional_encoding: + unet_sampled_features_with_position_embedding = torch.cat([local_xyz_probes_position_embedding, unet_sampled_features2], dim=-1) # (160, 16, 8, 1397) + else: + unet_sampled_features_with_position_embedding = unet_sampled_features2 + #unet_sampled_features_with_position_embedding = torch.cat([unet_sampled_features[:,:,:,:117], unet_sampled_features], dim=-1) # (160, 16, 8, 1397) + + + #___________________ PLANE PROJECTIONS _____________________________ + ''' + (B*Num_Views, Num_Rays, Num_3D_Points, 3) + For each sample coordinate (x,y,z) find its projection into the XY, YZ and XZ planes + ''' + #(B*Num_Views, Num_Rays, Num_3D_Points, 3) --> (B*Num_Views*Num_Rays, Num_3D_Points, 3) + B_and_num_views, Num_Rays, Num_3D_Points, _ = sample_coordinates.shape + coordinates = sample_coordinates.reshape(B_and_num_views * Num_Rays, Num_3D_Points, 3) + + #( (B*Num_Views*Num_Rays*3, Num_3D_Points, 2) dove il "3" indica che per ogni punto 3D abbaiamo in fila la sua proiezione sul piano 1,2 e 3 + projected_coordinates = self.project_onto_planes(self.plane_axes.to(coordinates.device), coordinates) + + projected_coordinates = projected_coordinates.view(B_and_num_views, Num_Rays, 3, Num_3D_Points, 2) + + # Proiezione sul piano XY (X,Y) + proj_XY = projected_coordinates[:,:,0] # prende [:, :, :, 0:2] = (X, Y) + + # Proiezione sul piano YZ (Y,Z) + proj_YZ = projected_coordinates[:,:,1] # prende [:, :, :, 1:3] = (Y, Z) + + # Proiezione sul piano XZ (X,Z) + proj_XZ = projected_coordinates[:,:,2] + + #save_plane_projections(sample_coordinates[0:4].detach().cpu()) #prime 4 camere + + + #__________________ FEATURE SPLATTING ________________________________ + ''' + For each sample projected into XY, YZ and XZ planes, aggregates features into pixels via inverse bilinear sampling + ''' + #normalize each projection to be into [0,1] and reshape to (B, Num_points, 2) + proj_XY_normalized = ((proj_XY + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_YZ_normalized = ((proj_YZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + proj_XZ_normalized = ((proj_XZ + self.box_side_lenght/2) / (2 * self.box_side_lenght/2)).clamp(0,1).reshape(B, -1, 2) + + if self.do_local_bilinear_splatting == False: + XY = self.global_bilinear_splatting(proj_XY_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + YZ = self.global_bilinear_splatting(proj_YZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + XZ = self.global_bilinear_splatting(proj_XZ_normalized, unet_sampled_features_with_position_embedding.reshape(B, -1, unet_sampled_features_with_position_embedding.shape[-1]), H=self.splat_plane_resolution, W=self.splat_plane_resolution).unsqueeze(1) + else: + #[B, num_views, C, D, D] + XY = self.local_bilinear_splatting(proj_XY_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + YZ = self.local_bilinear_splatting(proj_YZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + XZ = self.local_bilinear_splatting(proj_XZ_normalized.reshape(B, num_views, self.latent_dim**2*self.n_samples, 2), unet_sampled_features_with_position_embedding.reshape(B, num_views, self.latent_dim**2*self.n_samples, self.ray_embedding_dim+self.ray_sample_embedding_dim+self.latent_dim_embedding if self.use_positional_encoding else self.latent_dim_embedding), H=self.splat_plane_resolution, W=self.splat_plane_resolution).to(current_dtype) + + + + #downsample and tokenize + B, T, C, H, W = XY.shape + #[B, num_views, C, num_tokens] + XY_tokens = self.downsampler_XY(XY.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + YZ_tokens = self.downsampler_YZ(YZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + XZ_tokens = self.downsampler_XZ(XZ.view(B * T, C, H, W)).view(B, T, C, self.plane_resolution**2).permute(0, 1, 3, 2) + + + + XY_tokens_mean = XY_tokens.mean(dim=1) + YZ_tokens_mean = YZ_tokens.mean(dim=1) + XZ_tokens_mean = XZ_tokens.mean(dim=1) + init_tokens_mean = self.expand_init_tokens(torch.cat([XY_tokens_mean,YZ_tokens_mean,XZ_tokens_mean], dim=1)) + x = x + init_tokens_mean + + mod = t_emb[::self.num_views] + for layer in self.layers: + x = x + self.forward_layer(layer, x, mod, XY_tokens, YZ_tokens, XZ_tokens) + x = self.norm(x) + + if self.do_latent_rendering: + + #__________________ CONVERT TOKENS TO TRIPLANE _____________ + #[b, 3, 32, 64, 64]) + planes = self.reshape_upsample(x) + + #__________________ SAMPLE FEATURES FROM TRIPLANE___________ + features_XY = self.sample_triplane(planes[:,0,:,:,:], proj_XY_normalized) + features_YZ = self.sample_triplane(planes[:,1,:,:,:], proj_YZ_normalized) + features_XZ = self.sample_triplane(planes[:,2,:,:,:], proj_XZ_normalized) + + #join XY,YZ and XZ as unique feature for each sampled point + global_features = torch.cat((features_XY, features_YZ, features_XZ), dim=1).squeeze(2).permute(0,2,1) + + #__________________ DECODE SAMPLED FEATURES__________________ + decoded_sampled_features = self.decoder(global_features) + + #__________________AGGREGATE RAY SAMPLES____________________ + #[Num_Rays, Num_Samples, C]) + decoded_sampled_features = decoded_sampled_features.reshape(B*self.num_views*self.latent_dim**2, self.n_samples, self.latent_dim_embedding) + + + weight = self.weight_sample(decoded_sampled_features) + weight = F.softmax(weight, dim=1) + updated_feature_map = torch.sum(decoded_sampled_features * weight, dim=1) + # updated_feature_map = unet_sampled_features.reshape(B*self.num_views*self.latent_dim**2, 1, self.latent_dim_embedding) + # for layer in self.samples_aggregator_layers: + # updated_feature_map = layer(updated_feature_map, mod, decoded_sampled_features) + + + updated_feature_map = rearrange(updated_feature_map.squeeze(1), "(bf h w) c -> bf c h w", bf=B_and_num_views, h=self.latent_dim, w=self.latent_dim) + updated_feature_map = rearrange(updated_feature_map, "bf c h w -> (bf h w) c") + updated_feature_map = rearrange( + # hw, + updated_feature_map, + "(b f h w) c -> (b f) c h w", + h=self.latent_dim, + w=self.latent_dim, + f=self.num_views, + ) + + + return updated_feature_map.transpose(2,3), planes if self.latent_dim == 32 else x + + else: + return unet_features, x + + + + + + +import plotly.graph_objects as go +import plotly.colors as pc +import matplotlib.pyplot as plt +import torch +import plotly.graph_objects as go +import numpy as np +from matplotlib import cm +import matplotlib.patches as patches + + +def plot_scene(sample_coordinates: torch.Tensor, + ray_origins: torch.Tensor, + views_id, + cubo_lato: float = 1.0, + spazio_range: float = 1.6): + """ + Plotta raggi 3D per più viste con bordi di un cubo centrato in (0,0,0), + colorando ogni vista con un colore diverso e mostrando il centro di ciascuna camera. + + Args: + sample_coordinates: Tensor [V, R, P, 3], V viste, R raggi, P punti per raggio + ray_origins: Tensor [V, R, 3], origini dei raggi per ogni vista + num_viste: quante viste plottare (default: 16) + cubo_lato: lato del cubo centrato in (0,0,0) + spazio_range: range assi x/y/z (default: ±1.6) + """ + fig = go.Figure() + + # --- Colori distinti per vista --- + colors = np.linspace(0, 1, len(views_id)) + colormap = cm.get_cmap('viridis') + rgb_colors = [f'rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})' for r, g, b, _ in colormap(colors)] + + # --- Plotta raggi e centri camera --- + for i in views_id: + color = rgb_colors[i%len(views_id)] + + # Plot raggi della vista i + for j in range(sample_coordinates.shape[1]): + points = sample_coordinates[i, j] # [P, 3] + x, y, z = points[:, 0].numpy(), points[:, 1].numpy(), points[:, 2].numpy() + + fig.add_trace(go.Scatter3d( + x=x, y=y, z=z, + mode='lines+markers', + marker=dict(size=3, color=color), + line=dict(width=2, color=color), + name=f'Vista {i}' if j == 0 else None, + showlegend=(j == 0) + )) + + # Calcola centro della camera + center = ray_origins[i][0].numpy() + print("CENTER ",center) + fig.add_trace(go.Scatter3d( + x=[center[0]], y=[center[1]], z=[center[2]], + mode='markers+text', + marker=dict(size=6, color=color, symbol='x'), + text=[f'C{i}'], + textposition='top center', + name=f'Centro Vista {i}', + showlegend=False + )) + + # --- Disegna bordi del cubo --- + half = cubo_lato / 2 + cube_vertices = [ + [-half, -half, -half], [-half, -half, half], + [-half, half, -half], [-half, half, half], + [ half, -half, -half], [ half, -half, half], + [ half, half, -half], [ half, half, half], + ] + edges = [ + [0,1], [0,2], [0,4], [1,3], [1,5], + [2,3], [2,6], [3,7], [4,5], [4,6], + [5,7], [6,7], + ] + for e in edges: + p1, p2 = cube_vertices[e[0]], cube_vertices[e[1]] + fig.add_trace(go.Scatter3d( + x=[p1[0], p2[0]], + y=[p1[1], p2[1]], + z=[p1[2], p2[2]], + mode='lines', + line=dict(color='red', width=4), + showlegend=False + )) + + + # --- Layout --- + fig.update_layout( + title=f'Prime {views_id} viste con raggi + Cubo centrato in (0,0,0)', + scene=dict( + xaxis=dict(title='X', range=[-spazio_range, spazio_range]), + yaxis=dict(title='Y', range=[-spazio_range, spazio_range]), + zaxis=dict(title='Z', range=[-spazio_range, spazio_range]) + ) + ) + + fig.show() + + +def plot_avg_feature_map(x, batch_id, plane_id, reshape_upsample, where_to_save="/raid/homes/giulio.federico/LoomNet/src/da_eliminare/splat_0.png"): + + assert batch_id >=0 and batch_id <= x.shape[0], "batch id must be between [0, B] where B is the batch size of x" + assert plane_id >=0 and plane_id <=2, "plane id can be 0 (XY), 1 (YZ) or 2 (XZ)" + + with torch.no_grad(): + # Estrai e media lungo i canali + img_tensor = reshape_upsample(x)[batch_id][plane_id].detach().cpu().mean(dim=0) # shape: [128, 128] + + # Converti in numpy per matplotlib + img_np = img_tensor.numpy() + + # Visualizza e salva l'immagine + plt.figure(figsize=(6, 6)) + im = plt.imshow(img_np, cmap='viridis') # Puoi cambiare cmap: 'inferno', 'plasma', ecc. + plt.colorbar(im) + plt.title(f"Feature Map Media - Batch ID {batch_id}") + plt.savefig(where_to_save) + plt.show() diff --git a/loomnet/models/extras/geometry_loss/__pycache__/geometric_loss.cpython-311.pyc b/loomnet/models/extras/geometry_loss/__pycache__/geometric_loss.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51eb696bd1fc6ef3cf9bcc36a254edb3b3144bea Binary files /dev/null and b/loomnet/models/extras/geometry_loss/__pycache__/geometric_loss.cpython-311.pyc differ diff --git a/loomnet/models/extras/geometry_loss/__pycache__/vgg_net.cpython-311.pyc b/loomnet/models/extras/geometry_loss/__pycache__/vgg_net.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02b20e10724494297c3f888d206f3d4191108321 Binary files /dev/null and b/loomnet/models/extras/geometry_loss/__pycache__/vgg_net.cpython-311.pyc differ diff --git a/loomnet/models/extras/geometry_loss/geometric_loss.py b/loomnet/models/extras/geometry_loss/geometric_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4a57fc8bd2e248caccba1e917ce431ee75a593 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/geometric_loss.py @@ -0,0 +1,281 @@ +import torch.nn as nn +import torch +import torch.nn.functional as F +import numpy as np +from termcolor import cprint +from .vgg_net import VGG_NET +from .vggt.vggt.models.vggt import VGGT +from rembg import remove +import torchvision.transforms as T + +class VGGT_Geometric_Loss(nn.Module): + def __init__( + self, + use_16 = True, + target_layers = [], # [4, 11, 17, 23] #what intermediate representation to use from transformer layers to compute geometric loss + use_gradient_checkpoint = True, + fused_attention = True, + type_of_geometric_loss = "token_based_geometric_loss", + num_query_points = 1, + num_views_to_check = 1 + ): + super().__init__() + + self.target_layers = target_layers + self.type_of_geometric_loss = type_of_geometric_loss + self.num_query_points = num_query_points + self.num_views_to_check = num_views_to_check + + cprint("Initializes VGGT Geometric Loss", "green") + if type_of_geometric_loss == "token_based_geometric_loss": + return_type = "token_features" + elif type_of_geometric_loss == "register_token_based_geometric_loss": + return_type = "register_token_features" + else: + return_type = "none" + + + self.vggt_net = VGG_NET(target_layers=target_layers, use_gradient_checkpoint=use_gradient_checkpoint, fused_attention=fused_attention, return_type=return_type) + self.patch_size = self.vggt_net.aggregator.patch_size + + + self.L = len(target_layers) + + + + + ''' + - grt_images: images of shape (b, num_views, 3, D1, D2) in [0,1] + - pred_images: images of shape (b, num_views, 3, D1, D2) in [0,1] + ''' + + def forward(self, grt_images, pred_images, k_near_indices): + + if self.type_of_geometric_loss == "token_based_geometric_loss" or self.type_of_geometric_loss == "register_token_based_geometric_loss": + return self.forward1(grt_images, pred_images) + + elif self.type_of_geometric_loss == "point_matching_geometric_loss": + return self.forward2(pred_images, k_near_indices) + + + def forward1(self, grt_images, pred_images): + + #prepare both grt_images and pred_images to vggt --> (b, numviews, 3, 518, 518) + grt_images = self.prepare_for_vggt(grt_images).to(torch.float16) + pred_images = self.prepare_for_vggt(pred_images).to(torch.float16) + + B, num_views, C, H, W = grt_images.shape + + #list of global representation at "target_layers" + outs0, _, _ = self.vggt_net(grt_images) + outs1, _, _ = self.vggt_net(pred_images) + + feats0, feats1, diffs = {}, {}, {} + B, num_views, num_tokens, dim_token = outs0[0].shape + + if self.type_of_geometric_loss == "token_based_geometric_loss": + patch_h, patch_w = H // self.patch_size, W // self.patch_size + elif self.type_of_geometric_loss == "register_token_based_geometric_loss": + patch_h, patch_w = 2, 2 #NB: it doeasn't make sense, it's just to avoid changing the following code (i threat register tokens as 2x2 matrix) + + + for kk in range(self.L): + #(b, num_views, num_tokens, C) --> + outs0_kk = outs0[kk].view(B * num_views, -1, dim_token).permute(0, 2, 1).reshape((B*num_views, dim_token, patch_h, patch_w)).contiguous() + outs1_kk = outs1[kk].view(B * num_views, -1, dim_token).permute(0, 2, 1).reshape((B*num_views, dim_token, patch_h, patch_w)).contiguous() + feats0[kk], feats1[kk] = self.normalize_tensor(outs0_kk), self.normalize_tensor(outs1_kk) + diffs[kk] = (feats0[kk]-feats1[kk])**2 + + res = [self.spatial_average(diffs[kk].sum(dim=1,keepdim=True), keepdim=False) for kk in range(self.L)] + + val = 0 + # val[i] means: the total "distance" of behaviour that each view i has with its own ground truth + for l in range(self.L): + val += res[l] + + return val + + #NB: CHECKED ONLY FOR BATCH SIZE 1 + def forward2(self, pred_images, k_near_indices): + + #prepare pred_images to vggt --> (b, numviews, 3, 518, 518) + pred_images, masks = self.prepare_for_vggt(pred_images, compute_mask=True) + + b, N, c, h, w = pred_images.shape + + #re-organize pred_images with its neighbors + k_pred_images = torch.stack([ + pred_images[i][k_near_indices[i]] # [N, k, 3, H, W] + for i in range(b) + ]) + + b, N, k, c, h, w = k_pred_images.shape + + sampled_points = self.sample_points_from_mask_batch(masks, self.num_query_points) + #plot_points_on_mask(masks, sample_points_from_mask_batch(masks, 512), view_idx=1, batch_idx=0, save_path='/raid/homes/giulio.federico/LoomNet/src/da_eliminare/sampled_points.png') + + # seleziono randomicamente gli indici delle view di cui calcolare la consistenza + indices = torch.randperm(self.num_views_to_check) + + subset_pred_images = k_pred_images[:,indices].view(b*self.num_views_to_check, k, c, h, w) + subset_query_points = sampled_points[:, indices].view(b*self.num_views_to_check, self.num_query_points, 2) + + _, patch_start_idx, aggregated_tokens_list = self.vggt_net(subset_pred_images) + # Predict Point Matching + track_list, vis_score, conf_score = self.vggt_net.track_head(aggregated_tokens_list, subset_pred_images, patch_start_idx, query_points=subset_query_points) + + #dalle confidenze escludi il match con se stessa + conf_score = conf_score[:,1:,:] + + ''' + Dalle confidenze trova la massima (ossia se in almeno una immagine è stato trovato il match) + Questo serve a far si che se viene trovata in una immagine e non nelle altre, perchè magari + non esiste il match vero, non venga penalizzato + ''' + max_conf, _ = conf_score.max(dim=1) + + #per ogni batch + loss = (1 - max_conf) + + #(b, tot_points) + return loss.view(b, self.num_views_to_check*self.num_query_points) + + + + + + def prepare_for_vggt(self, images, compute_mask = False): + + B, num_views, c, width, height = images.shape + + images = images.view(B*num_views, c, width, height) + + new_width = 518 + + # Calculate height maintaining aspect ratio, divisible by 14 + new_height = round(height * (new_width / width) / 14) * 14 + + images = F.interpolate( + images, + size=(new_height, new_width), + mode='bilinear', + align_corners=False + ).clamp(0, 1) + + if compute_mask == True: + + # Soft mask for foreground + # Assume white background ~ (1,1,1) + threshold = 0.99 + bg_thresh = (images > threshold).float() # (B*num_views, 3, H, W) + bg_mask = bg_thresh.prod(dim=1, keepdim=True) # (B*num_views, 1, H, W) + fg_mask = 1.0 - bg_mask # 1 = foreground, 0 = background + + images_out = images.view(B, num_views, c, new_height, new_width) + masks_out = fg_mask.view(B, num_views, 1, new_height, new_width) + + return images_out, masks_out + + # to_pil = T.ToPILImage() + # to_tensor = T.ToTensor() + + # backgrounds = [] + + # for i in range(images.shape[0]): + + # img_pil = to_pil(images[i].detach().cpu()) + + # # Rimuovi sfondo + # bg_pil = remove(img_pil) + + # # Converti di nuovo in tensor + # bg_tensor = to_tensor(bg_pil) + + # backgrounds.append(bg_tensor[-1]) + + # # Ricostruisci batch, sposta device originale + # background_images = torch.stack(backgrounds).to(images.device).view(B, num_views, 1, new_height, new_width) + + # return images.view(B, num_views, c, new_height, new_width), background_images + + return images.view(B, num_views, c, new_height, new_width) + + + def normalize_tensor(self, in_feat,eps=1e-10): + norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1,keepdim=True)) + return in_feat/(norm_factor+eps) + + def spatial_average(self, in_tens, keepdim=True): + return in_tens.mean([2,3],keepdim=keepdim) + + def sample_points_from_mask_batch(self, mask, K): + """ + mask: (B, N, 1, H, W), binary foreground mask (0/1) + Returns: + points: (B, N, K, 2) normalized coordinates in [0,1] + """ + B, N, _, H, W = mask.shape + device = mask.device + + # Crea meshgrid normalized: shape (H*W, 2) + x = torch.linspace(0, 1, W, device=device) + y = torch.linspace(0, 1, H, device=device) + yy, xx = torch.meshgrid(y, x, indexing='ij') # (H, W) + coords = torch.stack([xx, yy], dim=-1).view(-1, 2) # (H*W, 2) + + # Flatten maschera: (B, N, H*W) + mask_flat = mask.view(B, N, -1) # (B, N, H*W) + + # Per ogni immagine e vista, ottieni gli indici foreground + # Qui usiamo topk per estrarre fino a K punti foreground (se meno, ripetiamo) + # Aggiungiamo un piccolo epsilon per evitare zero-somme + scores = mask_flat.float() + 1e-6 # (B, N, H*W) + + # Normalizza le probabilità + probs = scores / scores.sum(dim=2, keepdim=True) # (B, N, H*W) + + # Campiona K punti per ogni B,N con multinomial (probabilità discrete) + sampled_idx = torch.multinomial(probs.view(-1, H*W), K, replacement=True) # (B*N, K) + + sampled_idx = sampled_idx.view(B, N, K) # (B, N, K) + + # Indici da coordinare: coords è (H*W, 2) + # Usa gather con expand per B,N,K + coords_exp = coords.unsqueeze(0).unsqueeze(0).expand(B, N, H*W, 2) # (B, N, H*W, 2) + sampled_idx_exp = sampled_idx.unsqueeze(-1).expand(B, N, K, 2) # (B, N, K, 2) + + sampled_points = torch.gather(coords_exp, 2, sampled_idx_exp) # (B, N, K, 2) + + return sampled_points + + +#------------------ just to plot + +import matplotlib.pyplot as plt +import numpy as np + +def plot_points_on_mask(mask, points, view_idx=0, batch_idx=0, save_path='plot.png'): + """ + mask: (B, N, 1, H, W) + points: (B, N, K, 2) normalized coords in [0,1] + """ + B, N, _, H, W = mask.shape + K = points.shape[2] + + # Estrai la maschera e il set di punti per l'immagine/view scelti + m = mask[batch_idx, view_idx, 0].cpu().numpy() # (H, W) + pts = points[batch_idx, view_idx].cpu().numpy() # (K, 2) + + # Denormalizza i punti in pixel (colonna=x, riga=y) + pts_px = np.zeros_like(pts) + pts_px[:, 0] = pts[:, 0] * (W - 1) # x + pts_px[:, 1] = pts[:, 1] * (H - 1) # y + + # Plot + plt.figure(figsize=(6,6)) + plt.imshow(m, cmap='gray') + plt.scatter(pts_px[:, 0], pts_px[:, 1], c='r', s=30, marker='o') + plt.title(f'Batch {batch_idx}, View {view_idx} - Sampled Points') + plt.axis('off') + plt.savefig(save_path, bbox_inches='tight') + plt.close() \ No newline at end of file diff --git a/loomnet/models/extras/geometry_loss/vgg_net.py b/loomnet/models/extras/geometry_loss/vgg_net.py new file mode 100644 index 0000000000000000000000000000000000000000..589f068d0f41d56ba03535688ddfd08453baa832 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vgg_net.py @@ -0,0 +1,229 @@ +from .vggt.vggt.models.vggt import VGGT +import torch.nn as nn +import torch +from torch.utils.checkpoint import checkpoint + +class VGG_NET(nn.Module): + def __init__( + self, + target_layers = [4, 11, 17, 23], + use_16 = True, + use_gradient_checkpoint = False, + fused_attention = True, + return_type = "none" + ): + super().__init__() + + self.target_layers = target_layers + self.use_gradient_checkpoint = use_gradient_checkpoint + self.fused_attention = fused_attention + self.return_type = return_type + + vggt = VGGT.from_pretrained("facebook/VGGT-1B") + + for param in vggt.parameters(): + param.requires_grad = False + + vggt.eval() + + self.aggregator = vggt.aggregator + self.track_head = vggt.track_head + + + + + + def forward(self, images): + + B, S, C_in, H, W = images.shape + + images = (images - self.aggregator._resnet_mean) / self.aggregator._resnet_std + + # Reshape to [B*S, C, H, W] for patch embedding + images = images.view(B * S, C_in, H, W) + patch_tokens = self.aggregator.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.aggregator.camera_token, B, S) + register_token = slice_expand_and_flatten(self.aggregator.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.aggregator.rope is not None: + pos = self.aggregator.position_getter(B * S, H // self.aggregator.patch_size, W // self.aggregator.patch_size, device=images.device) + + if self.aggregator.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.aggregator.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 = [] + output_list_features = [] + + for depth_i in range(self.aggregator.aa_block_num): + for attn_type in self.aggregator.aa_order: + if attn_type == "frame": + tokens, frame_idx, attns, frame_intermediates = self._process_frame_attention( + tokens, B, S, P, C, frame_idx, pos=pos + ) + elif attn_type == "global": + tokens, global_idx, attns, global_intermediates = self._process_global_attention( + tokens, B, S, P, C, global_idx, pos=pos + ) + else: + raise ValueError(f"Unknown attention type: {attn_type}") + + if depth_i in self.target_layers: + if self.return_type == "token_features": + #add global representation of each frame without camera parameter token and registers tokens + glb_tokens = tokens.view(B, S, P, C ) + glb_tokens = glb_tokens[:,:,self.aggregator.patch_start_idx:,:] + output_list_features.append(glb_tokens) + elif self.return_type == "register_token_features": + #add only registers tokens + glb_tokens = tokens.view(B, S, P, C ) + register_tokens = glb_tokens[:,:,1:1+self.aggregator.num_register_tokens,:] + output_list_features.append(register_tokens) + if depth_i == max(self.target_layers): + break + + for i in range(len(frame_intermediates)): + # 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) + + + del concat_inter + del frame_intermediates + del global_intermediates + return output_list_features, self.aggregator.patch_start_idx, output_list + + 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). + """ + frame_idx_tensor = torch.tensor(frame_idx, dtype=torch.long, device=tokens.device) + + # 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.aggregator.aa_block_size): + if self.use_gradient_checkpoint: + # tokens = checkpoint( + # lambda t, idx, p: self.aggregator.frame_blocks[idx.item()](t, pos=p), # idx is converted to int using .item() + # tokens, frame_idx_tensor, pos + # ) + idx = frame_idx_tensor.item() + r = checkpoint( + lambda t, p: self.aggregator.frame_blocks[idx](t, pos=p, fused_attn = self.fused_attention), + tokens, pos + ) + + if isinstance(r, list): + tokens, attns = r + else: + tokens = r + else: + r = self.aggregator.frame_blocks[frame_idx](tokens, pos=pos, fused_attn = self.fused_attention) + if isinstance(r, list): + tokens, attns = r + else: + tokens = r + + frame_idx_tensor += 1 + intermediates.append(tokens.view(B, S, P, C)) + + + return tokens, frame_idx_tensor.item(), getattr(self, 'attns', None), 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). + """ + global_idx_tensor = torch.tensor(global_idx, dtype=torch.long, device=tokens.device) + + 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.aggregator.aa_block_size): + if self.use_gradient_checkpoint: + # tokens = checkpoint( + # lambda t, idx, p: self.aggregator.global_blocks[idx.item()](t, pos=p), # idx is converted to int using .item() + # tokens, global_idx_tensor, pos + # ) + idx = global_idx_tensor.item() + r = checkpoint( + lambda t, p: self.aggregator.global_blocks[idx](t, pos=p, fused_attn = self.fused_attention), + tokens, pos + ) + if isinstance(r, list): + tokens, attns = r + else: + tokens = r + else: + r = self.aggregator.global_blocks[global_idx](tokens, pos=pos, fused_attn = self.fused_attention) + if isinstance(r, list): + tokens, attns = r + else: + tokens = r + + global_idx_tensor += 1 + intermediates.append(tokens.view(B, S, P, C)) + + + return tokens, global_idx_tensor.item(), getattr(self, 'attns', None), intermediates + + +def slice_expand_and_flatten(token_tensor, B, S): + """ + Processes specialized tokens with shape (1, 2, X, C) for multi-frame processing: + 1) Uses the first position (index=0) for the first frame only + 2) Uses the second position (index=1) for all remaining frames (S-1 frames) + 3) Expands both to match batch size B + 4) Concatenates to form (B, S, X, C) where each sequence has 1 first-position token + followed by (S-1) second-position tokens + 5) Flattens to (B*S, X, C) for processing + + Returns: + torch.Tensor: Processed tokens with shape (B*S, X, C) + """ + + # Slice out the "query" tokens => shape (1, 1, ...) + query = token_tensor[:, 0:1, ...].expand(B, 1, *token_tensor.shape[2:]) + # Slice out the "other" tokens => shape (1, S-1, ...) + others = token_tensor[:, 1:, ...].expand(B, S - 1, *token_tensor.shape[2:]) + # Concatenate => shape (B, S, ...) + combined = torch.cat([query, others], dim=1) + + # Finally flatten => shape (B*S, ...) + combined = combined.view(B * S, *combined.shape[2:]) + return combined + diff --git a/loomnet/models/extras/geometry_loss/vggt/.gitattributes b/loomnet/models/extras/geometry_loss/vggt/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..887a2c18f01df0784f690be728f22c1f9d1fa5c4 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/.gitattributes @@ -0,0 +1,2 @@ +# SCM syntax highlighting & preventing 3-way merges +pixi.lock merge=binary linguist-language=YAML linguist-generated=true diff --git a/loomnet/models/extras/geometry_loss/vggt/.gitignore b/loomnet/models/extras/geometry_loss/vggt/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6c2db4377297140df430d609233f8474c3bdf09d --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/.gitignore @@ -0,0 +1,150 @@ +.hydra/ +output/ +ckpt/ +dependency/ +# Byte-compiled / optimized / DLL files +__pycache__/ +**/__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Profiling data +.prof + +# Folder specific to your needs +**/tmp/ +**/outputs/skyseg.onnx +skyseg.onnx + +# pixi environments +.pixi +*.egg-info diff --git a/loomnet/models/extras/geometry_loss/vggt/CODE_OF_CONDUCT.md b/loomnet/models/extras/geometry_loss/vggt/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..3232ed665566ec047ce55a929db1581dbda266a1 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/CODE_OF_CONDUCT.md @@ -0,0 +1,80 @@ +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to make participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic +address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when +an individual is representing the project or its community in public spaces. +Examples of representing a project or community include using an official +project e-mail address, posting via an official social media account, or acting +as an appointed representative at an online or offline event. Representation of +a project may be further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when there is a +reasonable belief that an individual's behavior may have a negative impact on +the project or its community. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at . All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/loomnet/models/extras/geometry_loss/vggt/CONTRIBUTING.md b/loomnet/models/extras/geometry_loss/vggt/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..72baaa2eb86da6050a43c1ea553c095932a5b939 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/CONTRIBUTING.md @@ -0,0 +1,31 @@ +# Contributing to vggt +We want to make contributing to this project as easy and transparent as +possible. + +## Pull Requests +We actively welcome your pull requests. + +1. Fork the repo and create your branch from `main`. +2. If you've added code that should be tested, add tests. +3. If you've changed APIs, update the documentation. +4. Ensure the test suite passes. +5. Make sure your code lints. +6. If you haven't already, complete the Contributor License Agreement ("CLA"). + +## Contributor License Agreement ("CLA") +In order to accept your pull request, we need you to submit a CLA. You only need +to do this once to work on any of Facebook's open source projects. + +Complete your CLA here: + +## Issues +We use GitHub issues to track public bugs. Please ensure your description is +clear and has sufficient instructions to be able to reproduce the issue. + +Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe +disclosure of security bugs. In those cases, please go through the process +outlined on that page and do not file a public issue. + +## License +By contributing to vggt, you agree that your contributions will be licensed +under the LICENSE file in the root directory of this source tree. \ No newline at end of file diff --git a/loomnet/models/extras/geometry_loss/vggt/LICENSE.txt b/loomnet/models/extras/geometry_loss/vggt/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e395ca3e2cdebf48a6375a3c1022d10caabba7db --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/LICENSE.txt @@ -0,0 +1,399 @@ +Attribution-NonCommercial 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + j. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + k. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + l. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/loomnet/models/extras/geometry_loss/vggt/README.md b/loomnet/models/extras/geometry_loss/vggt/README.md new file mode 100644 index 0000000000000000000000000000000000000000..114f5a9927299e7ebbf9abd74f2822beea19a09e --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/README.md @@ -0,0 +1,237 @@ +
+

VGGT: Visual Geometry Grounded Transformer

+ + + Paper PDF + +arXiv +Project Page + + + +**[Visual Geometry Group, University of Oxford](https://www.robots.ox.ac.uk/~vgg/)**; **[Meta AI](https://ai.facebook.com/research/)** + + +[Jianyuan Wang](https://jytime.github.io/), [Minghao Chen](https://silent-chen.github.io/), [Nikita Karaev](https://nikitakaraevv.github.io/), [Andrea Vedaldi](https://www.robots.ox.ac.uk/~vedaldi/), [Christian Rupprecht](https://chrirupp.github.io/), [David Novotny](https://d-novotny.github.io/) +
+ +```bibtex +@inproceedings{wang2025vggt, + title={VGGT: Visual Geometry Grounded Transformer}, + author={Wang, Jianyuan and Chen, Minghao and Karaev, Nikita and Vedaldi, Andrea and Rupprecht, Christian and Novotny, David}, + booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, + year={2025} +} +``` + +## Updates +- [Apr 13, 2025] Training code is being gradually cleaned and uploaded to the [training](https://github.com/facebookresearch/vggt/tree/training) branch. It will be merged into the main branch once finalized. + +## Overview + +Visual Geometry Grounded Transformer (VGGT, CVPR 2025) is a feed-forward neural network that directly infers all key 3D attributes of a scene, including extrinsic and intrinsic camera parameters, point maps, depth maps, and 3D point tracks, **from one, a few, or hundreds of its views, within seconds**. + + +## Quick Start + +First, clone this repository to your local machine, and install the dependencies (torch, torchvision, numpy, Pillow, and huggingface_hub). + +```bash +git clone git@github.com:facebookresearch/vggt.git +cd vggt +pip install -r requirements.txt +``` + +Alternatively, you can install VGGT as a package (click here for details). + + +Now, try the model with just a few lines of code: + +```python +import torch +from vggt.models.vggt import VGGT +from vggt.utils.load_fn import load_and_preprocess_images + +device = "cuda" if torch.cuda.is_available() else "cpu" +# bfloat16 is supported on Ampere GPUs (Compute Capability 8.0+) +dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] >= 8 else torch.float16 + +# Initialize the model and load the pretrained weights. +# This will automatically download the model weights the first time it's run, which may take a while. +model = VGGT.from_pretrained("facebook/VGGT-1B").to(device) + +# Load and preprocess example images (replace with your own image paths) +image_names = ["path/to/imageA.png", "path/to/imageB.png", "path/to/imageC.png"] +images = load_and_preprocess_images(image_names).to(device) + +with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=dtype): + # Predict attributes including cameras, depth maps, and point maps. + predictions = model(images) +``` + +The model weights will be automatically downloaded from Hugging Face. If you encounter issues such as slow loading, you can manually download them [here](https://huggingface.co/facebook/VGGT-1B/blob/main/model.pt) and load, or: + +```python +model = VGGT() +_URL = "https://huggingface.co/facebook/VGGT-1B/resolve/main/model.pt" +model.load_state_dict(torch.hub.load_state_dict_from_url(_URL)) +``` + +## Detailed Usage + +You can also optionally choose which attributes (branches) to predict, as shown below. This achieves the same result as the example above. This example uses a batch size of 1 (processing a single scene), but it naturally works for multiple scenes. + +```python +from vggt.utils.pose_enc import pose_encoding_to_extri_intri +from vggt.utils.geometry import unproject_depth_map_to_point_map + +with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=dtype): + images = images[None] # add batch dimension + aggregated_tokens_list, ps_idx = model.aggregator(images) + + # Predict Cameras + pose_enc = model.camera_head(aggregated_tokens_list)[-1] + # Extrinsic and intrinsic matrices, following OpenCV convention (camera from world) + extrinsic, intrinsic = pose_encoding_to_extri_intri(pose_enc, images.shape[-2:]) + + # Predict Depth Maps + depth_map, depth_conf = model.depth_head(aggregated_tokens_list, images, ps_idx) + + # Predict Point Maps + point_map, point_conf = model.point_head(aggregated_tokens_list, images, ps_idx) + + # Construct 3D Points from Depth Maps and Cameras + # which usually leads to more accurate 3D points than point map branch + point_map_by_unprojection = unproject_depth_map_to_point_map(depth_map.squeeze(0), + extrinsic.squeeze(0), + intrinsic.squeeze(0)) + + # Predict Tracks + # choose your own points to track, with shape (N, 2) for one scene + query_points = torch.FloatTensor([[100.0, 200.0], + [60.72, 259.94]]).to(device) + track_list, vis_score, conf_score = model.track_head(aggregated_tokens_list, images, ps_idx, query_points=query_points[None]) +``` + + +Furthermore, if certain pixels in the input frames are unwanted (e.g., reflective surfaces, sky, or water), you can simply mask them by setting the corresponding pixel values to 0 or 1. Precise segmentation masks aren't necessary - simple bounding box masks work effectively (check this [issue](https://github.com/facebookresearch/vggt/issues/47) for an example). + + +## Visualization + +We provide multiple ways to visualize your 3D reconstructions and tracking results. Before using these visualization tools, install the required dependencies: + +```bash +pip install -r requirements_demo.txt +``` + +### Interactive 3D Visualization + +**Please note:** VGGT typically reconstructs a scene in less than 1 second. However, visualizing 3D points may take tens of seconds due to third-party rendering, independent of VGGT's processing time. The visualization is slow especially when the number of images is large. + + +#### Gradio Web Interface + +Our Gradio-based interface allows you to upload images/videos, run reconstruction, and interactively explore the 3D scene in your browser. You can launch this in your local machine or try it on [Hugging Face](https://huggingface.co/spaces/facebook/vggt). + + +```bash +python demo_gradio.py +``` + +
+Click to preview the Gradio interactive interface + +![Gradio Web Interface Preview](https://jytime.github.io/data/vggt_hf_demo_screen.png) +
+ + +#### Viser 3D Viewer + +Run the following command to run reconstruction and visualize the point clouds in viser. Note this script requires a path to a folder containing images. It assumes only image files under the folder. You can set `--use_point_map` to use the point cloud from the point map branch, instead of the depth-based point cloud. + +```bash +python demo_viser.py --image_folder path/to/your/images/folder +``` + + +### Track Visualization + +To visualize point tracks across multiple images: + +```python +from vggt.utils.visual_track import visualize_tracks_on_images +track = track_list[-1] +visualize_tracks_on_images(images, track, (conf_score>0.2) & (vis_score>0.2), out_dir="track_visuals") +``` +This plots the tracks on the images and saves them to the specified output directory. + + +## Single-view Reconstruction + +Our model shows surprisingly good performance on single-view reconstruction, although it was never trained for this task. The model does not need to duplicate the single-view image to a pair, instead, it can directly infer the 3D structure from the tokens of the single view image. Feel free to try it with our demos above, which naturally works for single-view reconstruction. + + +We did not quantitatively test monocular depth estimation performance ourselves, but [@kabouzeid](https://github.com/kabouzeid) generously provided a comparison of VGGT to recent methods [here](https://github.com/facebookresearch/vggt/issues/36). VGGT shows competitive or better results compared to state-of-the-art monocular approaches such as DepthAnything v2 or MoGe, despite never being explicitly trained for single-view tasks. + + + +## Runtime and GPU Memory + +We benchmark the runtime and GPU memory usage of VGGT's aggregator on a single NVIDIA H100 GPU across various input sizes. + +| **Input Frames** | 1 | 2 | 4 | 8 | 10 | 20 | 50 | 100 | 200 | +|:----------------:|:-:|:-:|:-:|:-:|:--:|:--:|:--:|:---:|:---:| +| **Time (s)** | 0.04 | 0.05 | 0.07 | 0.11 | 0.14 | 0.31 | 1.04 | 3.12 | 8.75 | +| **Memory (GB)** | 1.88 | 2.07 | 2.45 | 3.23 | 3.63 | 5.58 | 11.41 | 21.15 | 40.63 | + +Note that these results were obtained using Flash Attention 3, which is faster than the default Flash Attention 2 implementation while maintaining almost the same memory usage. Feel free to compile Flash Attention 3 from source to get better performance. + + +## Research Progression + +Our work builds upon a series of previous research projects. If you're interested in understanding how our research evolved, check out our previous works: + + + + + + + + + + + + + + + + + + +
+ Deep SfM Revisited + ──┐
+ PoseDiffusion + ─────► + VGGSfM ──► + VGGT +
+ CoTracker + ──┘
+ + +## Acknowledgements + +Thanks to these great repositories: [PoseDiffusion](https://github.com/facebookresearch/PoseDiffusion), [VGGSfM](https://github.com/facebookresearch/vggsfm), [CoTracker](https://github.com/facebookresearch/co-tracker), [DINOv2](https://github.com/facebookresearch/dinov2), [Dust3r](https://github.com/naver/dust3r), [Moge](https://github.com/microsoft/moge), [PyTorch3D](https://github.com/facebookresearch/pytorch3d), [Sky Segmentation](https://github.com/xiongzhu666/Sky-Segmentation-and-Post-processing), [Depth Anything V2](https://github.com/DepthAnything/Depth-Anything-V2), [Metric3D](https://github.com/YvanYin/Metric3D) and many other inspiring works in the community. + +## Checklist + +- [ ] Release the training code +- [ ] Release VGGT-500M and VGGT-200M + + +## License +See the [LICENSE](./LICENSE.txt) file for details about the license under which this code is made available. diff --git a/loomnet/models/extras/geometry_loss/vggt/demo_gradio.py b/loomnet/models/extras/geometry_loss/vggt/demo_gradio.py new file mode 100644 index 0000000000000000000000000000000000000000..8dcef99142828bc38d82b0bfd2219de60f38f1d8 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/demo_gradio.py @@ -0,0 +1,685 @@ +# 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 os +import cv2 +import torch +import numpy as np +import gradio as gr +import sys +import shutil +from datetime import datetime +import glob +import gc +import time + +sys.path.append("vggt/") + +from visual_util import predictions_to_glb +from vggt.models.vggt import VGGT +from vggt.utils.load_fn import load_and_preprocess_images +from vggt.utils.pose_enc import pose_encoding_to_extri_intri +from vggt.utils.geometry import unproject_depth_map_to_point_map + +device = "cuda" if torch.cuda.is_available() else "cpu" + +print("Initializing and loading VGGT model...") +# model = VGGT.from_pretrained("facebook/VGGT-1B") # another way to load the model + +model = VGGT() +_URL = "https://huggingface.co/facebook/VGGT-1B/resolve/main/model.pt" +model.load_state_dict(torch.hub.load_state_dict_from_url(_URL)) + + +model.eval() +model = model.to(device) + + +# ------------------------------------------------------------------------- +# 1) Core model inference +# ------------------------------------------------------------------------- +def run_model(target_dir, model) -> dict: + """ + Run the VGGT model on images in the 'target_dir/images' folder and return predictions. + """ + print(f"Processing images from {target_dir}") + + # Device check + device = "cuda" if torch.cuda.is_available() else "cpu" + if not torch.cuda.is_available(): + raise ValueError("CUDA is not available. Check your environment.") + + # Move model to device + model = model.to(device) + model.eval() + + # Load and preprocess images + image_names = glob.glob(os.path.join(target_dir, "images", "*")) + image_names = sorted(image_names) + print(f"Found {len(image_names)} images") + if len(image_names) == 0: + raise ValueError("No images found. Check your upload.") + + images = load_and_preprocess_images(image_names).to(device) + print(f"Preprocessed images shape: {images.shape}") + + # Run inference + print("Running inference...") + dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] >= 8 else torch.float16 + + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=dtype): + predictions = model(images) + + # Convert pose encoding to extrinsic and intrinsic matrices + print("Converting pose encoding to extrinsic and intrinsic matrices...") + extrinsic, intrinsic = pose_encoding_to_extri_intri(predictions["pose_enc"], images.shape[-2:]) + predictions["extrinsic"] = extrinsic + predictions["intrinsic"] = intrinsic + + # Convert tensors to numpy + for key in predictions.keys(): + if isinstance(predictions[key], torch.Tensor): + predictions[key] = predictions[key].cpu().numpy().squeeze(0) # remove batch dimension + + # Generate world points from depth map + print("Computing world points from depth map...") + depth_map = predictions["depth"] # (S, H, W, 1) + world_points = unproject_depth_map_to_point_map(depth_map, predictions["extrinsic"], predictions["intrinsic"]) + predictions["world_points_from_depth"] = world_points + + # Clean up + torch.cuda.empty_cache() + return predictions + + +# ------------------------------------------------------------------------- +# 2) Handle uploaded video/images --> produce target_dir + images +# ------------------------------------------------------------------------- +def handle_uploads(input_video, input_images): + """ + Create a new 'target_dir' + 'images' subfolder, and place user-uploaded + images or extracted frames from video into it. Return (target_dir, image_paths). + """ + start_time = time.time() + gc.collect() + torch.cuda.empty_cache() + + # Create a unique folder name + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + target_dir = f"input_images_{timestamp}" + target_dir_images = os.path.join(target_dir, "images") + + # Clean up if somehow that folder already exists + if os.path.exists(target_dir): + shutil.rmtree(target_dir) + os.makedirs(target_dir) + os.makedirs(target_dir_images) + + image_paths = [] + + # --- Handle images --- + if input_images is not None: + for file_data in input_images: + if isinstance(file_data, dict) and "name" in file_data: + file_path = file_data["name"] + else: + file_path = file_data + dst_path = os.path.join(target_dir_images, os.path.basename(file_path)) + shutil.copy(file_path, dst_path) + image_paths.append(dst_path) + + # --- Handle video --- + if input_video is not None: + if isinstance(input_video, dict) and "name" in input_video: + video_path = input_video["name"] + else: + video_path = input_video + + vs = cv2.VideoCapture(video_path) + fps = vs.get(cv2.CAP_PROP_FPS) + frame_interval = int(fps * 1) # 1 frame/sec + + count = 0 + video_frame_num = 0 + while True: + gotit, frame = vs.read() + if not gotit: + break + count += 1 + if count % frame_interval == 0: + image_path = os.path.join(target_dir_images, f"{video_frame_num:06}.png") + cv2.imwrite(image_path, frame) + image_paths.append(image_path) + video_frame_num += 1 + + # Sort final images for gallery + image_paths = sorted(image_paths) + + end_time = time.time() + print(f"Files copied to {target_dir_images}; took {end_time - start_time:.3f} seconds") + return target_dir, image_paths + + +# ------------------------------------------------------------------------- +# 3) Update gallery on upload +# ------------------------------------------------------------------------- +def update_gallery_on_upload(input_video, input_images): + """ + Whenever user uploads or changes files, immediately handle them + and show in the gallery. Return (target_dir, image_paths). + If nothing is uploaded, returns "None" and empty list. + """ + if not input_video and not input_images: + return None, None, None, None + target_dir, image_paths = handle_uploads(input_video, input_images) + return None, target_dir, image_paths, "Upload complete. Click 'Reconstruct' to begin 3D processing." + + +# ------------------------------------------------------------------------- +# 4) Reconstruction: uses the target_dir plus any viz parameters +# ------------------------------------------------------------------------- +def gradio_demo( + target_dir, + conf_thres=3.0, + frame_filter="All", + mask_black_bg=False, + mask_white_bg=False, + show_cam=True, + mask_sky=False, + prediction_mode="Pointmap Regression", +): + """ + Perform reconstruction using the already-created target_dir/images. + """ + if not os.path.isdir(target_dir) or target_dir == "None": + return None, "No valid target directory found. Please upload first.", None, None + + start_time = time.time() + gc.collect() + torch.cuda.empty_cache() + + # Prepare frame_filter dropdown + target_dir_images = os.path.join(target_dir, "images") + all_files = sorted(os.listdir(target_dir_images)) if os.path.isdir(target_dir_images) else [] + all_files = [f"{i}: {filename}" for i, filename in enumerate(all_files)] + frame_filter_choices = ["All"] + all_files + + print("Running run_model...") + with torch.no_grad(): + predictions = run_model(target_dir, model) + + # Save predictions + prediction_save_path = os.path.join(target_dir, "predictions.npz") + np.savez(prediction_save_path, **predictions) + + # Handle None frame_filter + if frame_filter is None: + frame_filter = "All" + + # Build a GLB file name + glbfile = os.path.join( + target_dir, + f"glbscene_{conf_thres}_{frame_filter.replace('.', '_').replace(':', '').replace(' ', '_')}_maskb{mask_black_bg}_maskw{mask_white_bg}_cam{show_cam}_sky{mask_sky}_pred{prediction_mode.replace(' ', '_')}.glb", + ) + + # Convert predictions to GLB + glbscene = predictions_to_glb( + predictions, + conf_thres=conf_thres, + filter_by_frames=frame_filter, + mask_black_bg=mask_black_bg, + mask_white_bg=mask_white_bg, + show_cam=show_cam, + mask_sky=mask_sky, + target_dir=target_dir, + prediction_mode=prediction_mode, + ) + glbscene.export(file_obj=glbfile) + + # Cleanup + del predictions + gc.collect() + torch.cuda.empty_cache() + + end_time = time.time() + print(f"Total time: {end_time - start_time:.2f} seconds (including IO)") + log_msg = f"Reconstruction Success ({len(all_files)} frames). Waiting for visualization." + + return glbfile, log_msg, gr.Dropdown(choices=frame_filter_choices, value=frame_filter, interactive=True) + + +# ------------------------------------------------------------------------- +# 5) Helper functions for UI resets + re-visualization +# ------------------------------------------------------------------------- +def clear_fields(): + """ + Clears the 3D viewer, the stored target_dir, and empties the gallery. + """ + return None + + +def update_log(): + """ + Display a quick log message while waiting. + """ + return "Loading and Reconstructing..." + + +def update_visualization( + target_dir, conf_thres, frame_filter, mask_black_bg, mask_white_bg, show_cam, mask_sky, prediction_mode, is_example +): + """ + Reload saved predictions from npz, create (or reuse) the GLB for new parameters, + and return it for the 3D viewer. If is_example == "True", skip. + """ + + # If it's an example click, skip as requested + if is_example == "True": + return None, "No reconstruction available. Please click the Reconstruct button first." + + if not target_dir or target_dir == "None" or not os.path.isdir(target_dir): + return None, "No reconstruction available. Please click the Reconstruct button first." + + predictions_path = os.path.join(target_dir, "predictions.npz") + if not os.path.exists(predictions_path): + return None, f"No reconstruction available at {predictions_path}. Please run 'Reconstruct' first." + + loaded = np.load(predictions_path, allow_pickle=True) + predictions = {key: loaded[key] for key in loaded.keys()} + + glbfile = os.path.join( + target_dir, + f"glbscene_{conf_thres}_{frame_filter.replace('.', '_').replace(':', '').replace(' ', '_')}_maskb{mask_black_bg}_maskw{mask_white_bg}_cam{show_cam}_sky{mask_sky}_pred{prediction_mode.replace(' ', '_')}.glb", + ) + + if not os.path.exists(glbfile): + glbscene = predictions_to_glb( + predictions, + conf_thres=conf_thres, + filter_by_frames=frame_filter, + mask_black_bg=mask_black_bg, + mask_white_bg=mask_white_bg, + show_cam=show_cam, + mask_sky=mask_sky, + target_dir=target_dir, + prediction_mode=prediction_mode, + ) + glbscene.export(file_obj=glbfile) + + return glbfile, "Updating Visualization" + + +# ------------------------------------------------------------------------- +# Example images +# ------------------------------------------------------------------------- + +great_wall_video = "examples/videos/great_wall.mp4" +colosseum_video = "examples/videos/Colosseum.mp4" +room_video = "examples/videos/room.mp4" +kitchen_video = "examples/videos/kitchen.mp4" +fern_video = "examples/videos/fern.mp4" +single_cartoon_video = "examples/videos/single_cartoon.mp4" +single_oil_painting_video = "examples/videos/single_oil_painting.mp4" +pyramid_video = "examples/videos/pyramid.mp4" + + +# ------------------------------------------------------------------------- +# 6) Build Gradio UI +# ------------------------------------------------------------------------- +theme = gr.themes.Ocean() +theme.set( + checkbox_label_background_fill_selected="*button_primary_background_fill", + checkbox_label_text_color_selected="*button_primary_text_color", +) + +with gr.Blocks( + theme=theme, + css=""" + .custom-log * { + font-style: italic; + font-size: 22px !important; + background-image: linear-gradient(120deg, #0ea5e9 0%, #6ee7b7 60%, #34d399 100%); + -webkit-background-clip: text; + background-clip: text; + font-weight: bold !important; + color: transparent !important; + text-align: center !important; + } + + .example-log * { + font-style: italic; + font-size: 16px !important; + background-image: linear-gradient(120deg, #0ea5e9 0%, #6ee7b7 60%, #34d399 100%); + -webkit-background-clip: text; + background-clip: text; + color: transparent !important; + } + + #my_radio .wrap { + display: flex; + flex-wrap: nowrap; + justify-content: center; + align-items: center; + } + + #my_radio .wrap label { + display: flex; + width: 50%; + justify-content: center; + align-items: center; + margin: 0; + padding: 10px 0; + box-sizing: border-box; + } + """, +) as demo: + + # Instead of gr.State, we use a hidden Textbox: + is_example = gr.Textbox(label="is_example", visible=False, value="None") + num_images = gr.Textbox(label="num_images", visible=False, value="None") + + gr.HTML( + """ +

🏛️ VGGT: Visual Geometry Grounded Transformer

+

+ 🐙 GitHub Repository | + Project Page +

+ +
+

Upload a video or a set of images to create a 3D reconstruction of a scene or object. VGGT takes these images and generates a 3D point cloud, along with estimated camera poses.

+ +

Getting Started:

+
    +
  1. Upload Your Data: Use the "Upload Video" or "Upload Images" buttons on the left to provide your input. Videos will be automatically split into individual frames (one frame per second).
  2. +
  3. Preview: Your uploaded images will appear in the gallery on the left.
  4. +
  5. Reconstruct: Click the "Reconstruct" button to start the 3D reconstruction process.
  6. +
  7. Visualize: The 3D reconstruction will appear in the viewer on the right. You can rotate, pan, and zoom to explore the model, and download the GLB file. Note the visualization of 3D points may be slow for a large number of input images.
  8. +
  9. + Adjust Visualization (Optional): + After reconstruction, you can fine-tune the visualization using the options below +
    + (click to expand): +
      +
    • Confidence Threshold: Adjust the filtering of points based on confidence.
    • +
    • Show Points from Frame: Select specific frames to display in the point cloud.
    • +
    • Show Camera: Toggle the display of estimated camera positions.
    • +
    • Filter Sky / Filter Black Background: Remove sky or black-background points.
    • +
    • Select a Prediction Mode: Choose between "Depthmap and Camera Branch" or "Pointmap Branch."
    • +
    +
    +
  10. +
+

Please note: VGGT typically reconstructs a scene in less than 1 second. However, visualizing 3D points may take tens of seconds due to third-party rendering, which are independent of VGGT's processing time.

+
+ """ + ) + + target_dir_output = gr.Textbox(label="Target Dir", visible=False, value="None") + + with gr.Row(): + with gr.Column(scale=2): + input_video = gr.Video(label="Upload Video", interactive=True) + input_images = gr.File(file_count="multiple", label="Upload Images", interactive=True) + + image_gallery = gr.Gallery( + label="Preview", + columns=4, + height="300px", + show_download_button=True, + object_fit="contain", + preview=True, + ) + + with gr.Column(scale=4): + with gr.Column(): + gr.Markdown("**3D Reconstruction (Point Cloud and Camera Poses)**") + log_output = gr.Markdown( + "Please upload a video or images, then click Reconstruct.", elem_classes=["custom-log"] + ) + reconstruction_output = gr.Model3D(height=520, zoom_speed=0.5, pan_speed=0.5) + + with gr.Row(): + submit_btn = gr.Button("Reconstruct", scale=1, variant="primary") + clear_btn = gr.ClearButton( + [input_video, input_images, reconstruction_output, log_output, target_dir_output, image_gallery], + scale=1, + ) + + with gr.Row(): + prediction_mode = gr.Radio( + ["Depthmap and Camera Branch", "Pointmap Branch"], + label="Select a Prediction Mode", + value="Depthmap and Camera Branch", + scale=1, + elem_id="my_radio", + ) + + with gr.Row(): + conf_thres = gr.Slider(minimum=0, maximum=100, value=50, step=0.1, label="Confidence Threshold (%)") + frame_filter = gr.Dropdown(choices=["All"], value="All", label="Show Points from Frame") + with gr.Column(): + show_cam = gr.Checkbox(label="Show Camera", value=True) + mask_sky = gr.Checkbox(label="Filter Sky", value=False) + mask_black_bg = gr.Checkbox(label="Filter Black Background", value=False) + mask_white_bg = gr.Checkbox(label="Filter White Background", value=False) + + # ---------------------- Examples section ---------------------- + examples = [ + [colosseum_video, "22", None, 20.0, False, False, True, False, "Depthmap and Camera Branch", "True"], + [pyramid_video, "30", None, 35.0, False, False, True, False, "Depthmap and Camera Branch", "True"], + [single_cartoon_video, "1", None, 15.0, False, False, True, False, "Depthmap and Camera Branch", "True"], + [single_oil_painting_video, "1", None, 20.0, False, False, True, True, "Depthmap and Camera Branch", "True"], + [room_video, "8", None, 5.0, False, False, True, False, "Depthmap and Camera Branch", "True"], + [kitchen_video, "25", None, 50.0, False, False, True, False, "Depthmap and Camera Branch", "True"], + [fern_video, "20", None, 45.0, False, False, True, False, "Depthmap and Camera Branch", "True"], + ] + + def example_pipeline( + input_video, + num_images_str, + input_images, + conf_thres, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example_str, + ): + """ + 1) Copy example images to new target_dir + 2) Reconstruct + 3) Return model3D + logs + new_dir + updated dropdown + gallery + We do NOT return is_example. It's just an input. + """ + target_dir, image_paths = handle_uploads(input_video, input_images) + # Always use "All" for frame_filter in examples + frame_filter = "All" + glbfile, log_msg, dropdown = gradio_demo( + target_dir, conf_thres, frame_filter, mask_black_bg, mask_white_bg, show_cam, mask_sky, prediction_mode + ) + return glbfile, log_msg, target_dir, dropdown, image_paths + + gr.Markdown("Click any row to load an example.", elem_classes=["example-log"]) + + gr.Examples( + examples=examples, + inputs=[ + input_video, + num_images, + input_images, + conf_thres, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + outputs=[ + reconstruction_output, + log_output, + target_dir_output, + frame_filter, + image_gallery, + ], + fn=example_pipeline, + cache_examples=False, + examples_per_page=50, + ) + + # ------------------------------------------------------------------------- + # "Reconstruct" button logic: + # - Clear fields + # - Update log + # - gradio_demo(...) with the existing target_dir + # - Then set is_example = "False" + # ------------------------------------------------------------------------- + submit_btn.click(fn=clear_fields, inputs=[], outputs=[reconstruction_output]).then( + fn=update_log, inputs=[], outputs=[log_output] + ).then( + fn=gradio_demo, + inputs=[ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + ], + outputs=[reconstruction_output, log_output, frame_filter], + ).then( + fn=lambda: "False", inputs=[], outputs=[is_example] # set is_example to "False" + ) + + # ------------------------------------------------------------------------- + # Real-time Visualization Updates + # ------------------------------------------------------------------------- + conf_thres.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + frame_filter.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + mask_black_bg.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + mask_white_bg.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + show_cam.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + mask_sky.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + prediction_mode.change( + update_visualization, + [ + target_dir_output, + conf_thres, + frame_filter, + mask_black_bg, + mask_white_bg, + show_cam, + mask_sky, + prediction_mode, + is_example, + ], + [reconstruction_output, log_output], + ) + + # ------------------------------------------------------------------------- + # Auto-update gallery whenever user uploads or changes their files + # ------------------------------------------------------------------------- + input_video.change( + fn=update_gallery_on_upload, + inputs=[input_video, input_images], + outputs=[reconstruction_output, target_dir_output, image_gallery, log_output], + ) + input_images.change( + fn=update_gallery_on_upload, + inputs=[input_video, input_images], + outputs=[reconstruction_output, target_dir_output, image_gallery, log_output], + ) + + demo.queue(max_size=20).launch(show_error=True, share=True) diff --git a/loomnet/models/extras/geometry_loss/vggt/demo_viser.py b/loomnet/models/extras/geometry_loss/vggt/demo_viser.py new file mode 100644 index 0000000000000000000000000000000000000000..c52726b6d720933b9ad72b66cffd8896d6302e28 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/demo_viser.py @@ -0,0 +1,416 @@ +# 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 os +import glob +import time +import threading +import argparse +from typing import List, Optional + +import numpy as np +import torch +from tqdm.auto import tqdm +import viser +import viser.transforms as viser_tf +import cv2 + + +try: + import onnxruntime +except ImportError: + print("onnxruntime not found. Sky segmentation may not work.") + +from visual_util import segment_sky, download_file_from_url +from vggt.models.vggt import VGGT +from vggt.utils.load_fn import load_and_preprocess_images +from vggt.utils.geometry import closed_form_inverse_se3, unproject_depth_map_to_point_map +from vggt.utils.pose_enc import pose_encoding_to_extri_intri + + +def viser_wrapper( + pred_dict: dict, + port: int = 8080, + init_conf_threshold: float = 50.0, # represents percentage (e.g., 50 means filter lowest 50%) + use_point_map: bool = False, + background_mode: bool = False, + mask_sky: bool = False, + image_folder: str = None, +): + """ + Visualize predicted 3D points and camera poses with viser. + + Args: + pred_dict (dict): + { + "images": (S, 3, H, W) - Input images, + "world_points": (S, H, W, 3), + "world_points_conf": (S, H, W), + "depth": (S, H, W, 1), + "depth_conf": (S, H, W), + "extrinsic": (S, 3, 4), + "intrinsic": (S, 3, 3), + } + port (int): Port number for the viser server. + init_conf_threshold (float): Initial percentage of low-confidence points to filter out. + use_point_map (bool): Whether to visualize world_points or use depth-based points. + background_mode (bool): Whether to run the server in background thread. + mask_sky (bool): Whether to apply sky segmentation to filter out sky points. + image_folder (str): Path to the folder containing input images. + """ + print(f"Starting viser server on port {port}") + + server = viser.ViserServer(host="0.0.0.0", port=port) + server.gui.configure_theme(titlebar_content=None, control_layout="collapsible") + + # Unpack prediction dict + images = pred_dict["images"] # (S, 3, H, W) + world_points_map = pred_dict["world_points"] # (S, H, W, 3) + conf_map = pred_dict["world_points_conf"] # (S, H, W) + + depth_map = pred_dict["depth"] # (S, H, W, 1) + depth_conf = pred_dict["depth_conf"] # (S, H, W) + + extrinsics_cam = pred_dict["extrinsic"] # (S, 3, 4) + intrinsics_cam = pred_dict["intrinsic"] # (S, 3, 3) + + # Compute world points from depth if not using the precomputed point map + if not use_point_map: + world_points = unproject_depth_map_to_point_map(depth_map, extrinsics_cam, intrinsics_cam) + conf = depth_conf + else: + world_points = world_points_map + conf = conf_map + + # Apply sky segmentation if enabled + if mask_sky and image_folder is not None: + conf = apply_sky_segmentation(conf, image_folder) + + # Convert images from (S, 3, H, W) to (S, H, W, 3) + # Then flatten everything for the point cloud + colors = images.transpose(0, 2, 3, 1) # now (S, H, W, 3) + S, H, W, _ = world_points.shape + + # Flatten + points = world_points.reshape(-1, 3) + colors_flat = (colors.reshape(-1, 3) * 255).astype(np.uint8) + conf_flat = conf.reshape(-1) + + cam_to_world_mat = closed_form_inverse_se3(extrinsics_cam) # shape (S, 4, 4) typically + # For convenience, we store only (3,4) portion + cam_to_world = cam_to_world_mat[:, :3, :] + + # Compute scene center and recenter + scene_center = np.mean(points, axis=0) + points_centered = points - scene_center + cam_to_world[..., -1] -= scene_center + + # Store frame indices so we can filter by frame + frame_indices = np.repeat(np.arange(S), H * W) + + # Build the viser GUI + gui_show_frames = server.gui.add_checkbox( + "Show Cameras", + initial_value=True, + ) + + # Now the slider represents percentage of points to filter out + gui_points_conf = server.gui.add_slider( + "Confidence Percent", + min=0, + max=100, + step=0.1, + initial_value=init_conf_threshold, + ) + + gui_frame_selector = server.gui.add_dropdown( + "Show Points from Frames", + options=["All"] + [str(i) for i in range(S)], + initial_value="All", + ) + + # Create the main point cloud handle + # Compute the threshold value as the given percentile + init_threshold_val = np.percentile(conf_flat, init_conf_threshold) + init_conf_mask = (conf_flat >= init_threshold_val) & (conf_flat > 0.1) + point_cloud = server.scene.add_point_cloud( + name="viser_pcd", + points=points_centered[init_conf_mask], + colors=colors_flat[init_conf_mask], + point_size=0.001, + point_shape="circle", + ) + + # We will store references to frames & frustums so we can toggle visibility + frames: List[viser.FrameHandle] = [] + frustums: List[viser.CameraFrustumHandle] = [] + + def visualize_frames(extrinsics: np.ndarray, images_: np.ndarray) -> None: + """ + Add camera frames and frustums to the scene. + extrinsics: (S, 3, 4) + images_: (S, 3, H, W) + """ + # Clear any existing frames or frustums + for f in frames: + f.remove() + frames.clear() + for fr in frustums: + fr.remove() + frustums.clear() + + # Optionally attach a callback that sets the viewpoint to the chosen camera + def attach_callback(frustum: viser.CameraFrustumHandle, frame: viser.FrameHandle) -> None: + @frustum.on_click + def _(_) -> None: + for client in server.get_clients().values(): + client.camera.wxyz = frame.wxyz + client.camera.position = frame.position + + img_ids = range(S) + for img_id in tqdm(img_ids): + cam2world_3x4 = extrinsics[img_id] + T_world_camera = viser_tf.SE3.from_matrix(cam2world_3x4) + + # Add a small frame axis + frame_axis = server.scene.add_frame( + f"frame_{img_id}", + wxyz=T_world_camera.rotation().wxyz, + position=T_world_camera.translation(), + axes_length=0.05, + axes_radius=0.002, + origin_radius=0.002, + ) + frames.append(frame_axis) + + # Convert the image for the frustum + img = images_[img_id] # shape (3, H, W) + img = (img.transpose(1, 2, 0) * 255).astype(np.uint8) + h, w = img.shape[:2] + + # If you want correct FOV from intrinsics, do something like: + # fx = intrinsics_cam[img_id, 0, 0] + # fov = 2 * np.arctan2(h/2, fx) + # For demonstration, we pick a simple approximate FOV: + fy = 1.1 * h + fov = 2 * np.arctan2(h / 2, fy) + + # Add the frustum + frustum_cam = server.scene.add_camera_frustum( + f"frame_{img_id}/frustum", + fov=fov, + aspect=w / h, + scale=0.05, + image=img, + line_width=1.0, + ) + frustums.append(frustum_cam) + attach_callback(frustum_cam, frame_axis) + + def update_point_cloud() -> None: + """Update the point cloud based on current GUI selections.""" + # Here we compute the threshold value based on the current percentage + current_percentage = gui_points_conf.value + threshold_val = np.percentile(conf_flat, current_percentage) + + print(f"Threshold absolute value: {threshold_val}, percentage: {current_percentage}%") + + conf_mask = (conf_flat >= threshold_val) & (conf_flat > 1e-5) + + if gui_frame_selector.value == "All": + frame_mask = np.ones_like(conf_mask, dtype=bool) + else: + selected_idx = int(gui_frame_selector.value) + frame_mask = frame_indices == selected_idx + + combined_mask = conf_mask & frame_mask + point_cloud.points = points_centered[combined_mask] + point_cloud.colors = colors_flat[combined_mask] + + @gui_points_conf.on_update + def _(_) -> None: + update_point_cloud() + + @gui_frame_selector.on_update + def _(_) -> None: + update_point_cloud() + + @gui_show_frames.on_update + def _(_) -> None: + """Toggle visibility of camera frames and frustums.""" + for f in frames: + f.visible = gui_show_frames.value + for fr in frustums: + fr.visible = gui_show_frames.value + + # Add the camera frames to the scene + visualize_frames(cam_to_world, images) + + print("Starting viser server...") + # If background_mode is True, spawn a daemon thread so the main thread can continue. + if background_mode: + + def server_loop(): + while True: + time.sleep(0.001) + + thread = threading.Thread(target=server_loop, daemon=True) + thread.start() + else: + while True: + time.sleep(0.01) + + return server + + +# Helper functions for sky segmentation + + +def apply_sky_segmentation(conf: np.ndarray, image_folder: str) -> np.ndarray: + """ + Apply sky segmentation to confidence scores. + + Args: + conf (np.ndarray): Confidence scores with shape (S, H, W) + image_folder (str): Path to the folder containing input images + + Returns: + np.ndarray: Updated confidence scores with sky regions masked out + """ + S, H, W = conf.shape + sky_masks_dir = image_folder.rstrip("/") + "_sky_masks" + os.makedirs(sky_masks_dir, exist_ok=True) + + # Download skyseg.onnx if it doesn't exist + if not os.path.exists("skyseg.onnx"): + print("Downloading skyseg.onnx...") + download_file_from_url("https://huggingface.co/JianyuanWang/skyseg/resolve/main/skyseg.onnx", "skyseg.onnx") + + skyseg_session = onnxruntime.InferenceSession("skyseg.onnx") + image_files = sorted(glob.glob(os.path.join(image_folder, "*"))) + sky_mask_list = [] + + print("Generating sky masks...") + for i, image_path in enumerate(tqdm(image_files[:S])): # Limit to the number of images in the batch + image_name = os.path.basename(image_path) + mask_filepath = os.path.join(sky_masks_dir, image_name) + + if os.path.exists(mask_filepath): + sky_mask = cv2.imread(mask_filepath, cv2.IMREAD_GRAYSCALE) + else: + sky_mask = segment_sky(image_path, skyseg_session, mask_filepath) + + # Resize mask to match H×W if needed + if sky_mask.shape[0] != H or sky_mask.shape[1] != W: + sky_mask = cv2.resize(sky_mask, (W, H)) + + sky_mask_list.append(sky_mask) + + # Convert list to numpy array with shape S×H×W + sky_mask_array = np.array(sky_mask_list) + # Apply sky mask to confidence scores + sky_mask_binary = (sky_mask_array > 0.1).astype(np.float32) + conf = conf * sky_mask_binary + + print("Sky segmentation applied successfully") + return conf + + +parser = argparse.ArgumentParser(description="VGGT demo with viser for 3D visualization") +parser.add_argument( + "--image_folder", type=str, default="examples/kitchen/images/", help="Path to folder containing images" +) +parser.add_argument("--use_point_map", action="store_true", help="Use point map instead of depth-based points") +parser.add_argument("--background_mode", action="store_true", help="Run the viser server in background mode") +parser.add_argument("--port", type=int, default=8080, help="Port number for the viser server") +parser.add_argument( + "--conf_threshold", type=float, default=25.0, help="Initial percentage of low-confidence points to filter out" +) +parser.add_argument("--mask_sky", action="store_true", help="Apply sky segmentation to filter out sky points") + + +def main(): + """ + Main function for the VGGT demo with viser for 3D visualization. + + This function: + 1. Loads the VGGT model + 2. Processes input images from the specified folder + 3. Runs inference to generate 3D points and camera poses + 4. Optionally applies sky segmentation to filter out sky points + 5. Visualizes the results using viser + + Command-line arguments: + --image_folder: Path to folder containing input images + --use_point_map: Use point map instead of depth-based points + --background_mode: Run the viser server in background mode + --port: Port number for the viser server + --conf_threshold: Initial percentage of low-confidence points to filter out + --mask_sky: Apply sky segmentation to filter out sky points + """ + args = parser.parse_args() + device = "cuda" if torch.cuda.is_available() else "cpu" + print(f"Using device: {device}") + + print("Initializing and loading VGGT model...") + # model = VGGT.from_pretrained("facebook/VGGT-1B") + + model = VGGT() + _URL = "https://huggingface.co/facebook/VGGT-1B/resolve/main/model.pt" + model.load_state_dict(torch.hub.load_state_dict_from_url(_URL)) + + model.eval() + model = model.to(device) + + # Use the provided image folder path + print(f"Loading images from {args.image_folder}...") + image_names = glob.glob(os.path.join(args.image_folder, "*")) + print(f"Found {len(image_names)} images") + + images = load_and_preprocess_images(image_names).to(device) + print(f"Preprocessed images shape: {images.shape}") + + print("Running inference...") + dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] >= 8 else torch.float16 + + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=dtype): + predictions = model(images) + + print("Converting pose encoding to extrinsic and intrinsic matrices...") + extrinsic, intrinsic = pose_encoding_to_extri_intri(predictions["pose_enc"], images.shape[-2:]) + predictions["extrinsic"] = extrinsic + predictions["intrinsic"] = intrinsic + + print("Processing model outputs...") + for key in predictions.keys(): + if isinstance(predictions[key], torch.Tensor): + predictions[key] = predictions[key].cpu().numpy().squeeze(0) # remove batch dimension and convert to numpy + + if args.use_point_map: + print("Visualizing 3D points from point map") + else: + print("Visualizing 3D points by unprojecting depth map by cameras") + + if args.mask_sky: + print("Sky segmentation enabled - will filter out sky points") + + print("Starting viser visualization...") + + viser_server = viser_wrapper( + predictions, + port=args.port, + init_conf_threshold=args.conf_threshold, + use_point_map=args.use_point_map, + background_mode=args.background_mode, + mask_sky=args.mask_sky, + image_folder=args.image_folder, + ) + print("Visualization complete") + + +if __name__ == "__main__": + main() diff --git a/loomnet/models/extras/geometry_loss/vggt/docs/package.md b/loomnet/models/extras/geometry_loss/vggt/docs/package.md new file mode 100644 index 0000000000000000000000000000000000000000..356df89b613f9b48dd47d8b993bf792715237a6b --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/docs/package.md @@ -0,0 +1,45 @@ +# Alternative Installation Methods + +This document explains how to install VGGT as a package using different package managers. + +## Prerequisites + +Before installing VGGT as a package, you need to install PyTorch and torchvision. We don't list these as dependencies to avoid CUDA version mismatches. Install them first, with an example as: + +```bash +# install pytorch 2.3.1 with cuda 12.1 +pip install torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu121 +``` + +## Installation Options + +### Install with pip + +The simplest way to install VGGT is using pip: + +```bash +pip install -e . +``` + +### Install and run with pixi + +[Pixi](https://pixi.sh) is a package management tool for creating reproducible environments. + +1. First, [download and install pixi](https://pixi.sh/latest/get_started/) +2. Then run: + +```bash +pixi run -e python demo_gradio.py +``` + +### Install and run with uv + +[uv](https://docs.astral.sh/uv/) is a fast Python package installer and resolver. + +1. First, [install uv](https://docs.astral.sh/uv/getting-started/installation/) +2. Then run: + +```bash +uv run --extra demo demo_gradio.py +``` + diff --git a/loomnet/models/extras/geometry_loss/vggt/pyproject.toml b/loomnet/models/extras/geometry_loss/vggt/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..81d4f1de65b9218aaf9f2c8c6a3596c9cfd19d48 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/pyproject.toml @@ -0,0 +1,52 @@ +[project] +authors = [{name = "Jianyuan Wang", email = "jianyuan@robots.ox.ac.uk"}] +dependencies = [ + "numpy<2", + "Pillow", + "huggingface_hub", + "einops", + "safetensors", + "opencv-python", +] +name = "vggt" +requires-python = ">= 3.10" +version = "0.0.1" + +[project.optional-dependencies] +demo = [ + "gradio==5.17.1", + "viser==0.2.23", + "tqdm", + "hydra-core", + "omegaconf", + "opencv-python", + "scipy", + "onnxruntime", + "requests", + "trimesh", + "matplotlib", +] + +# Using setuptools as the build backend +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +# setuptools configuration +[tool.setuptools.packages.find] +where = ["."] +include = ["vggt*"] + +# Pixi configuration +[tool.pixi.workspace] +channels = ["conda-forge"] +platforms = ["linux-64"] + +[tool.pixi.pypi-dependencies] +vggt = { path = ".", editable = true } + +[tool.pixi.environments] +default = { solve-group = "default" } +demo = { features = ["demo"], solve-group = "default" } + +[tool.pixi.tasks] diff --git a/loomnet/models/extras/geometry_loss/vggt/requirements.txt b/loomnet/models/extras/geometry_loss/vggt/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..1cb61a2b7fd415bef4e77df43fc0ec5b53c63d7b --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/requirements.txt @@ -0,0 +1,7 @@ +torch==2.3.1 +torchvision==0.18.1 +numpy==1.26.1 +Pillow +huggingface_hub +einops +safetensors diff --git a/loomnet/models/extras/geometry_loss/vggt/requirements_demo.txt b/loomnet/models/extras/geometry_loss/vggt/requirements_demo.txt new file mode 100644 index 0000000000000000000000000000000000000000..efd6f5e9173ec19287ada50d14e73a073edebc08 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/requirements_demo.txt @@ -0,0 +1,11 @@ +gradio==5.17.1 +viser==0.2.23 +tqdm +hydra-core +omegaconf +opencv-python +scipy +onnxruntime +requests +trimesh +matplotlib diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/camera_head.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/camera_head.py new file mode 100644 index 0000000000000000000000000000000000000000..176d76fb5baeb3a42fa3675a1d1fb14010f2904d --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/camera_head.py @@ -0,0 +1,162 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from vggt.layers import Mlp +from vggt.layers.block import Block +from 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, 1, C]. + num_iterations (int): Number of refinement iterations. + + Returns: + list: List of activated camera encodings from each iteration. + """ + B, S, C = pose_tokens.shape # S is expected to be 1. + pred_pose_enc = None + pred_pose_enc_list = [] + + for _ in range(num_iterations): + # Use a learned empty pose for the first iteration. + if pred_pose_enc is None: + module_input = self.embed_pose(self.empty_pose_tokens.expand(B, S, -1)) + else: + # Detach the previous prediction to avoid backprop through time. + pred_pose_enc = pred_pose_enc.detach() + module_input = self.embed_pose(pred_pose_enc) + + # Generate modulation parameters and split them into shift, scale, and gate components. + shift_msa, scale_msa, gate_msa = self.poseLN_modulation(module_input).chunk(3, dim=-1) + + # Adaptive layer normalization and modulation. + pose_tokens_modulated = gate_msa * modulate(self.adaln_norm(pose_tokens), shift_msa, scale_msa) + pose_tokens_modulated = pose_tokens_modulated + pose_tokens + + pose_tokens_modulated = self.trunk(pose_tokens_modulated) + # Compute the delta update for the pose encoding. + pred_pose_enc_delta = self.pose_branch(self.trunk_norm(pose_tokens_modulated)) + + if pred_pose_enc is None: + pred_pose_enc = pred_pose_enc_delta + else: + pred_pose_enc = pred_pose_enc + pred_pose_enc_delta + + # Apply final activation functions for translation, quaternion, and field-of-view. + activated_pose = activate_pose( + pred_pose_enc, + trans_act=self.trans_act, + quat_act=self.quat_act, + fl_act=self.fl_act, + ) + pred_pose_enc_list.append(activated_pose) + + return pred_pose_enc_list + + +def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: + """ + Modulate the input tensor using scaling and shifting parameters. + """ + # modified from https://github.com/facebookresearch/DiT/blob/796c29e532f47bba17c5b9c5eb39b9354b8b7c64/models.py#L19 + return x * (1 + scale) + shift diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/dpt_head.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5cf6e1cee2eb7cb2ad9538d0d168f97a590382 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/dpt_head.py @@ -0,0 +1,497 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +# Inspired by https://github.com/DepthAnything/Depth-Anything-V2 + + +import os +from typing import List, Dict, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from .head_act import activate_head +from .utils import create_uv_grid, position_grid_to_embed + + +class DPTHead(nn.Module): + """ + DPT Head for dense prediction tasks. + + This implementation follows the architecture described in "Vision Transformers for Dense Prediction" + (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer + backbone and produces dense predictions by fusing multi-scale features. + + Args: + dim_in (int): Input dimension (channels). + patch_size (int, optional): Patch size. Default is 14. + output_dim (int, optional): Number of output channels. Default is 4. + activation (str, optional): Activation type. Default is "inv_log". + conf_activation (str, optional): Confidence activation type. Default is "expp1". + features (int, optional): Feature channels for intermediate representations. Default is 256. + out_channels (List[int], optional): Output channels for each intermediate layer. + intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT. + pos_embed (bool, optional): Whether to use positional embedding. Default is True. + feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False. + down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1. + """ + + def __init__( + self, + dim_in: int, + patch_size: int = 14, + output_dim: int = 4, + activation: str = "inv_log", + conf_activation: str = "expp1", + features: int = 256, + out_channels: List[int] = [256, 512, 1024, 1024], + intermediate_layer_idx: List[int] = [4, 11, 17, 23], + pos_embed: bool = True, + feature_only: bool = False, + down_ratio: int = 1, + ) -> None: + super(DPTHead, self).__init__() + self.patch_size = patch_size + self.activation = activation + self.conf_activation = conf_activation + self.pos_embed = pos_embed + self.feature_only = feature_only + self.down_ratio = down_ratio + self.intermediate_layer_idx = intermediate_layer_idx + + self.norm = nn.LayerNorm(dim_in) + + # Projection layers for each output channel from tokens. + self.projects = nn.ModuleList( + [ + nn.Conv2d( + in_channels=dim_in, + out_channels=oc, + kernel_size=1, + stride=1, + padding=0, + ) + for oc in out_channels + ] + ) + + # Resize layers for upsampling feature maps. + self.resize_layers = nn.ModuleList( + [ + nn.ConvTranspose2d( + in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0 + ), + nn.ConvTranspose2d( + in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0 + ), + nn.Identity(), + nn.Conv2d( + in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1 + ), + ] + ) + + self.scratch = _make_scratch( + out_channels, + features, + expand=False, + ) + + # Attach additional modules to scratch. + self.scratch.stem_transpose = None + self.scratch.refinenet1 = _make_fusion_block(features) + self.scratch.refinenet2 = _make_fusion_block(features) + self.scratch.refinenet3 = _make_fusion_block(features) + self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False) + + head_features_1 = features + head_features_2 = 32 + + if feature_only: + self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1) + else: + self.scratch.output_conv1 = nn.Conv2d( + head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 + ) + conv2_in_channels = head_features_1 // 2 + + self.scratch.output_conv2 = nn.Sequential( + nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), + ) + + def forward( + self, + aggregated_tokens_list: List[torch.Tensor], + images: torch.Tensor, + patch_start_idx: int, + frames_chunk_size: int = 8, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Forward pass through the DPT head, supports processing by chunking frames. + Args: + aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. + images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. + patch_start_idx (int): Starting index for patch tokens in the token sequence. + Used to separate patch tokens from other tokens (e.g., camera or register tokens). + frames_chunk_size (int, optional): Number of frames to process in each chunk. + If None or larger than S, all frames are processed at once. Default: 8. + + Returns: + Tensor or Tuple[Tensor, Tensor]: + - If feature_only=True: Feature maps with shape [B, S, C, H, W] + - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W] + """ + B, S, _, H, W = images.shape + + # If frames_chunk_size is not specified or greater than S, process all frames at once + if frames_chunk_size is None or frames_chunk_size >= S: + return self._forward_impl(aggregated_tokens_list, images, patch_start_idx) + + # Otherwise, process frames in chunks to manage memory usage + assert frames_chunk_size > 0 + + # Process frames in batches + all_preds = [] + all_conf = [] + + for frames_start_idx in range(0, S, frames_chunk_size): + frames_end_idx = min(frames_start_idx + frames_chunk_size, S) + + # Process batch of frames + if self.feature_only: + chunk_output = self._forward_impl( + aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_output) + else: + chunk_preds, chunk_conf = self._forward_impl( + aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_preds) + all_conf.append(chunk_conf) + + # Concatenate results along the sequence dimension + if self.feature_only: + return torch.cat(all_preds, dim=1) + else: + return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1) + + def _forward_impl( + self, + aggregated_tokens_list: List[torch.Tensor], + images: torch.Tensor, + patch_start_idx: int, + frames_start_idx: int = None, + frames_end_idx: int = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Implementation of the forward pass through the DPT head. + + This method processes a specific chunk of frames from the sequence. + + Args: + aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. + images (Tensor): Input images with shape [B, S, 3, H, W]. + patch_start_idx (int): Starting index for patch tokens. + frames_start_idx (int, optional): Starting index for frames to process. + frames_end_idx (int, optional): Ending index for frames to process. + + Returns: + Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence). + """ + if frames_start_idx is not None and frames_end_idx is not None: + images = images[:, frames_start_idx:frames_end_idx].contiguous() + + B, S, _, H, W = images.shape + + patch_h, patch_w = H // self.patch_size, W // self.patch_size + + out = [] + dpt_idx = 0 + + for layer_idx in self.intermediate_layer_idx: + x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:] + + # Select frames if processing a chunk + if frames_start_idx is not None and frames_end_idx is not None: + x = x[:, frames_start_idx:frames_end_idx] + + x = x.view(B * S, -1, x.shape[-1]) + + x = self.norm(x) + + x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) + + x = self.projects[dpt_idx](x) + if self.pos_embed: + x = self._apply_pos_embed(x, W, H) + x = self.resize_layers[dpt_idx](x) + + out.append(x) + dpt_idx += 1 + + # Fuse features from multiple layers. + out = self.scratch_forward(out) + # Interpolate fused output to match target image resolution. + out = custom_interpolate( + out, + (int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)), + mode="bilinear", + align_corners=True, + ) + + if self.pos_embed: + out = self._apply_pos_embed(out, W, H) + + if self.feature_only: + return out.view(B, S, *out.shape[1:]) + + out = self.scratch.output_conv2(out) + preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation) + + preds = preds.view(B, S, *preds.shape[1:]) + conf = conf.view(B, S, *conf.shape[1:]) + return preds, conf + + def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: + """ + Apply positional embedding to tensor x. + """ + patch_w = x.shape[-1] + patch_h = x.shape[-2] + pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device) + pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) + pos_embed = pos_embed * ratio + pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) + return x + pos_embed + + def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor: + """ + Forward pass through the fusion blocks. + + Args: + features (List[Tensor]): List of feature maps from different layers. + + Returns: + Tensor: Fused feature map. + """ + layer_1, layer_2, layer_3, layer_4 = features + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) + del layer_4_rn, layer_4 + + out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:]) + del layer_3_rn, layer_3 + + out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:]) + del layer_2_rn, layer_2 + + out = self.scratch.refinenet1(out, layer_1_rn) + del layer_1_rn, layer_1 + + out = self.scratch.output_conv1(out) + return out + + +################################################################################ +# Modules +################################################################################ + + +def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module: + return FeatureFusionBlock( + features, + nn.ReLU(inplace=True), + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=size, + has_residual=has_residual, + groups=groups, + ) + + +def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module: + scratch = nn.Module() + out_shape1 = out_shape + out_shape2 = out_shape + out_shape3 = out_shape + if len(in_shape) >= 4: + out_shape4 = out_shape + + if expand: + out_shape1 = out_shape + out_shape2 = out_shape * 2 + out_shape3 = out_shape * 4 + if len(in_shape) >= 4: + out_shape4 = out_shape * 8 + + scratch.layer1_rn = nn.Conv2d( + in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer2_rn = nn.Conv2d( + in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer3_rn = nn.Conv2d( + in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + if len(in_shape) >= 4: + scratch.layer4_rn = nn.Conv2d( + in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + return scratch + + +class ResidualConvUnit(nn.Module): + """Residual convolution module.""" + + def __init__(self, features, activation, bn, groups=1): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.bn = bn + self.groups = groups + self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) + self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) + + self.norm1 = None + self.norm2 = None + + self.activation = activation + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + + out = self.activation(x) + out = self.conv1(out) + if self.norm1 is not None: + out = self.norm1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.norm2 is not None: + out = self.norm2(out) + + return self.skip_add.add(out, x) + + +class FeatureFusionBlock(nn.Module): + """Feature fusion block.""" + + def __init__( + self, + features, + activation, + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=None, + has_residual=True, + groups=1, + ): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock, self).__init__() + + self.deconv = deconv + self.align_corners = align_corners + self.groups = groups + self.expand = expand + out_features = features + if self.expand == True: + out_features = features // 2 + + self.out_conv = nn.Conv2d( + features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=self.groups + ) + + if has_residual: + self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups) + + self.has_residual = has_residual + self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups) + + self.skip_add = nn.quantized.FloatFunctional() + self.size = size + + def forward(self, *xs, size=None): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if self.has_residual: + res = self.resConfUnit1(xs[1]) + output = self.skip_add.add(output, res) + + output = self.resConfUnit2(output) + + if (size is None) and (self.size is None): + modifier = {"scale_factor": 2} + elif size is None: + modifier = {"size": self.size} + else: + modifier = {"size": size} + + output = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners) + output = self.out_conv(output) + + return output + + +def custom_interpolate( + x: torch.Tensor, + size: Tuple[int, int] = None, + scale_factor: float = None, + mode: str = "bilinear", + align_corners: bool = True, +) -> torch.Tensor: + """ + Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate. + """ + if size is None: + size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor)) + + INT_MAX = 1610612736 + + input_elements = size[0] * size[1] * x.shape[0] * x.shape[1] + + if input_elements > INT_MAX: + chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0) + interpolated_chunks = [ + nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks + ] + x = torch.cat(interpolated_chunks, dim=0) + return x.contiguous() + else: + return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/head_act.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/head_act.py new file mode 100644 index 0000000000000000000000000000000000000000..2dedfcf1180a653dddc99623e60df625e5897489 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/head_act.py @@ -0,0 +1,125 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import torch +import torch.nn.functional as F + + +def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"): + """ + Activate pose parameters with specified activation functions. + + Args: + pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length] + trans_act: Activation type for translation component + quat_act: Activation type for quaternion component + fl_act: Activation type for focal length component + + Returns: + Activated pose parameters tensor + """ + T = pred_pose_enc[..., :3] + quat = pred_pose_enc[..., 3:7] + fl = pred_pose_enc[..., 7:] # or fov + + T = base_pose_act(T, trans_act) + quat = base_pose_act(quat, quat_act) + fl = base_pose_act(fl, fl_act) # or fov + + pred_pose_enc = torch.cat([T, quat, fl], dim=-1) + + return pred_pose_enc + + +def base_pose_act(pose_enc, act_type="linear"): + """ + Apply basic activation function to pose parameters. + + Args: + pose_enc: Tensor containing encoded pose parameters + act_type: Activation type ("linear", "inv_log", "exp", "relu") + + Returns: + Activated pose parameters + """ + if act_type == "linear": + return pose_enc + elif act_type == "inv_log": + return inverse_log_transform(pose_enc) + elif act_type == "exp": + return torch.exp(pose_enc) + elif act_type == "relu": + return F.relu(pose_enc) + else: + raise ValueError(f"Unknown act_type: {act_type}") + + +def activate_head(out, activation="norm_exp", conf_activation="expp1"): + """ + Process network output to extract 3D points and confidence values. + + Args: + out: Network output tensor (B, C, H, W) + activation: Activation type for 3D points + conf_activation: Activation type for confidence values + + Returns: + Tuple of (3D points tensor, confidence tensor) + """ + # Move channels from last dim to the 4th dimension => (B, H, W, C) + fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected + + # Split into xyz (first C-1 channels) and confidence (last channel) + xyz = fmap[:, :, :, :-1] + conf = fmap[:, :, :, -1] + + if activation == "norm_exp": + d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8) + xyz_normed = xyz / d + pts3d = xyz_normed * torch.expm1(d) + elif activation == "norm": + pts3d = xyz / xyz.norm(dim=-1, keepdim=True) + elif activation == "exp": + pts3d = torch.exp(xyz) + elif activation == "relu": + pts3d = F.relu(xyz) + elif activation == "inv_log": + pts3d = inverse_log_transform(xyz) + elif activation == "xy_inv_log": + xy, z = xyz.split([2, 1], dim=-1) + z = inverse_log_transform(z) + pts3d = torch.cat([xy * z, z], dim=-1) + elif activation == "sigmoid": + pts3d = torch.sigmoid(xyz) + elif activation == "linear": + pts3d = xyz + else: + raise ValueError(f"Unknown activation: {activation}") + + if conf_activation == "expp1": + conf_out = 1 + conf.exp() + elif conf_activation == "expp0": + conf_out = conf.exp() + elif conf_activation == "sigmoid": + conf_out = torch.sigmoid(conf) + else: + raise ValueError(f"Unknown conf_activation: {conf_activation}") + + return pts3d, conf_out + + +def inverse_log_transform(y): + """ + Apply inverse log transform: sign(y) * (exp(|y|) - 1) + + Args: + y: Input tensor + + Returns: + Transformed tensor + """ + return torch.sign(y) * (torch.expm1(torch.abs(y))) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_head.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec7199bd185060989c236997f93b93f4fc77825 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_head.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch.nn as nn +from .dpt_head import DPTHead +from .track_modules.base_track_predictor import BaseTrackerPredictor + + +class TrackHead(nn.Module): + """ + Track head that uses DPT head to process tokens and BaseTrackerPredictor for tracking. + The tracking is performed iteratively, refining predictions over multiple iterations. + """ + + def __init__( + self, + dim_in, + patch_size=14, + features=128, + iters=4, + predict_conf=True, + stride=2, + corr_levels=7, + corr_radius=4, + hidden_size=384, + ): + """ + Initialize the TrackHead module. + + Args: + dim_in (int): Input dimension of tokens from the backbone. + patch_size (int): Size of image patches used in the vision transformer. + features (int): Number of feature channels in the feature extractor output. + iters (int): Number of refinement iterations for tracking predictions. + predict_conf (bool): Whether to predict confidence scores for tracked points. + stride (int): Stride value for the tracker predictor. + corr_levels (int): Number of correlation pyramid levels + corr_radius (int): Radius for correlation computation, controlling the search area. + hidden_size (int): Size of hidden layers in the tracker network. + """ + super().__init__() + + self.patch_size = patch_size + + # Feature extractor based on DPT architecture + # Processes tokens into feature maps for tracking + self.feature_extractor = DPTHead( + dim_in=dim_in, + patch_size=patch_size, + features=features, + feature_only=True, # Only output features, no activation + down_ratio=2, # Reduces spatial dimensions by factor of 2 + pos_embed=False, + ) + + # Tracker module that predicts point trajectories + # Takes feature maps and predicts coordinates and visibility + self.tracker = BaseTrackerPredictor( + latent_dim=features, # Match the output_dim of feature extractor + predict_conf=predict_conf, + stride=stride, + corr_levels=corr_levels, + corr_radius=corr_radius, + hidden_size=hidden_size, + ) + + self.iters = iters + + def forward(self, aggregated_tokens_list, images, patch_start_idx, query_points=None, iters=None): + """ + Forward pass of the TrackHead. + + Args: + aggregated_tokens_list (list): List of aggregated tokens from the backbone. + images (torch.Tensor): Input images of shape (B, S, C, H, W) where: + B = batch size, S = sequence length. + patch_start_idx (int): Starting index for patch tokens. + query_points (torch.Tensor, optional): Initial query points to track. + If None, points are initialized by the tracker. + iters (int, optional): Number of refinement iterations. If None, uses self.iters. + + Returns: + tuple: + - coord_preds (torch.Tensor): Predicted coordinates for tracked points. + - vis_scores (torch.Tensor): Visibility scores for tracked points. + - conf_scores (torch.Tensor): Confidence scores for tracked points (if predict_conf=True). + """ + B, S, _, H, W = images.shape + + # Extract features from tokens + # feature_maps has shape (B, S, C, H//2, W//2) due to down_ratio=2 + feature_maps = self.feature_extractor(aggregated_tokens_list, images, patch_start_idx) + + # Use default iterations if not specified + if iters is None: + iters = self.iters + + # Perform tracking using the extracted features + coord_preds, vis_scores, conf_scores = self.tracker( + query_points=query_points, + fmaps=feature_maps, + iters=iters, + ) + + return coord_preds, vis_scores, conf_scores diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/__init__.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0952fcc3f57e34b3747962e9ebd6fc57aeea63fa --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/base_track_predictor.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/base_track_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce8ec4b66fff236e015d1bcaf85c8237a52be7a --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/base_track_predictor.py @@ -0,0 +1,209 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +from einops import rearrange, repeat + + +from .blocks import EfficientUpdateFormer, CorrBlock +from .utils import sample_features4d, get_2d_embedding, get_2d_sincos_pos_embed +from .modules import Mlp + + +class BaseTrackerPredictor(nn.Module): + def __init__( + self, + stride=1, + corr_levels=5, + corr_radius=4, + latent_dim=128, + hidden_size=384, + use_spaceatt=True, + depth=6, + max_scale=518, + predict_conf=True, + ): + super(BaseTrackerPredictor, self).__init__() + """ + The base template to create a track predictor + + Modified from https://github.com/facebookresearch/co-tracker/ + and https://github.com/facebookresearch/vggsfm + """ + + self.stride = stride + self.latent_dim = latent_dim + self.corr_levels = corr_levels + self.corr_radius = corr_radius + self.hidden_size = hidden_size + self.max_scale = max_scale + self.predict_conf = predict_conf + + self.flows_emb_dim = latent_dim // 2 + + self.corr_mlp = Mlp( + in_features=self.corr_levels * (self.corr_radius * 2 + 1) ** 2, + hidden_features=self.hidden_size, + out_features=self.latent_dim, + ) + + self.transformer_dim = self.latent_dim + self.latent_dim + self.latent_dim + 4 + + self.query_ref_token = nn.Parameter(torch.randn(1, 2, self.transformer_dim)) + + space_depth = depth if use_spaceatt else 0 + time_depth = depth + + self.updateformer = EfficientUpdateFormer( + space_depth=space_depth, + time_depth=time_depth, + input_dim=self.transformer_dim, + hidden_size=self.hidden_size, + output_dim=self.latent_dim + 2, + mlp_ratio=4.0, + add_space_attn=use_spaceatt, + ) + + self.fmap_norm = nn.LayerNorm(self.latent_dim) + self.ffeat_norm = nn.GroupNorm(1, self.latent_dim) + + # A linear layer to update track feats at each iteration + self.ffeat_updater = nn.Sequential(nn.Linear(self.latent_dim, self.latent_dim), nn.GELU()) + + self.vis_predictor = nn.Sequential(nn.Linear(self.latent_dim, 1)) + + if predict_conf: + self.conf_predictor = nn.Sequential(nn.Linear(self.latent_dim, 1)) + + def forward(self, query_points, fmaps=None, iters=6, return_feat=False, down_ratio=1, apply_sigmoid=True): + """ + query_points: B x N x 2, the number of batches, tracks, and xy + fmaps: B x S x C x HH x WW, the number of batches, frames, and feature dimension. + note HH and WW is the size of feature maps instead of original images + """ + B, N, D = query_points.shape + B, S, C, HH, WW = fmaps.shape + + assert D == 2, "Input points must be 2D coordinates" + + # apply a layernorm to fmaps here + fmaps = self.fmap_norm(fmaps.permute(0, 1, 3, 4, 2)) + fmaps = fmaps.permute(0, 1, 4, 2, 3) + + # Scale the input query_points because we may downsample the images + # by down_ratio or self.stride + # e.g., if a 3x1024x1024 image is processed to a 128x256x256 feature map + # its query_points should be query_points/4 + if down_ratio > 1: + query_points = query_points / float(down_ratio) + + query_points = query_points / float(self.stride) + + # Init with coords as the query points + # It means the search will start from the position of query points at the reference frames + coords = query_points.clone().reshape(B, 1, N, 2).repeat(1, S, 1, 1) + + # Sample/extract the features of the query points in the query frame + query_track_feat = sample_features4d(fmaps[:, 0], coords[:, 0]) + + # init track feats by query feats + track_feats = query_track_feat.unsqueeze(1).repeat(1, S, 1, 1) # B, S, N, C + # back up the init coords + coords_backup = coords.clone() + + fcorr_fn = CorrBlock(fmaps, num_levels=self.corr_levels, radius=self.corr_radius) + + coord_preds = [] + + # Iterative Refinement + for _ in range(iters): + # Detach the gradients from the last iteration + # (in my experience, not very important for performance) + coords = coords.detach() + + fcorrs = fcorr_fn.corr_sample(track_feats, coords) + + corr_dim = fcorrs.shape[3] + fcorrs_ = fcorrs.permute(0, 2, 1, 3).reshape(B * N, S, corr_dim) + fcorrs_ = self.corr_mlp(fcorrs_) + + # Movement of current coords relative to query points + flows = (coords - coords[:, 0:1]).permute(0, 2, 1, 3).reshape(B * N, S, 2) + + flows_emb = get_2d_embedding(flows, self.flows_emb_dim, cat_coords=False) + + # (In my trials, it is also okay to just add the flows_emb instead of concat) + flows_emb = torch.cat([flows_emb, flows / self.max_scale, flows / self.max_scale], dim=-1) + + track_feats_ = track_feats.permute(0, 2, 1, 3).reshape(B * N, S, self.latent_dim) + + # Concatenate them as the input for the transformers + transformer_input = torch.cat([flows_emb, fcorrs_, track_feats_], dim=2) + + # 2D positional embed + # TODO: this can be much simplified + pos_embed = get_2d_sincos_pos_embed(self.transformer_dim, grid_size=(HH, WW)).to(query_points.device) + sampled_pos_emb = sample_features4d(pos_embed.expand(B, -1, -1, -1), coords[:, 0]) + + sampled_pos_emb = rearrange(sampled_pos_emb, "b n c -> (b n) c").unsqueeze(1) + + x = transformer_input + sampled_pos_emb + + # Add the query ref token to the track feats + query_ref_token = torch.cat( + [self.query_ref_token[:, 0:1], self.query_ref_token[:, 1:2].expand(-1, S - 1, -1)], dim=1 + ) + x = x + query_ref_token.to(x.device).to(x.dtype) + + # B, N, S, C + x = rearrange(x, "(b n) s d -> b n s d", b=B) + + # Compute the delta coordinates and delta track features + delta, _ = self.updateformer(x) + + # BN, S, C + delta = rearrange(delta, " b n s d -> (b n) s d", b=B) + delta_coords_ = delta[:, :, :2] + delta_feats_ = delta[:, :, 2:] + + track_feats_ = track_feats_.reshape(B * N * S, self.latent_dim) + delta_feats_ = delta_feats_.reshape(B * N * S, self.latent_dim) + + # Update the track features + track_feats_ = self.ffeat_updater(self.ffeat_norm(delta_feats_)) + track_feats_ + + track_feats = track_feats_.reshape(B, N, S, self.latent_dim).permute(0, 2, 1, 3) # BxSxNxC + + # B x S x N x 2 + coords = coords + delta_coords_.reshape(B, N, S, 2).permute(0, 2, 1, 3) + + # Force coord0 as query + # because we assume the query points should not be changed + coords[:, 0] = coords_backup[:, 0] + + # The predicted tracks are in the original image scale + if down_ratio > 1: + coord_preds.append(coords * self.stride * down_ratio) + else: + coord_preds.append(coords * self.stride) + + # B, S, N + vis_e = self.vis_predictor(track_feats.reshape(B * S * N, self.latent_dim)).reshape(B, S, N) + if apply_sigmoid: + vis_e = torch.sigmoid(vis_e) + + if self.predict_conf: + conf_e = self.conf_predictor(track_feats.reshape(B * S * N, self.latent_dim)).reshape(B, S, N) + if apply_sigmoid: + conf_e = torch.sigmoid(conf_e) + else: + conf_e = None + + if return_feat: + return coord_preds, vis_e, track_feats, query_track_feat, conf_e + else: + return coord_preds, vis_e, conf_e diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/blocks.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..8e7763f4fd8f515662421db192594380dbb574e5 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/blocks.py @@ -0,0 +1,246 @@ +# 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 https://github.com/facebookresearch/co-tracker/ + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .utils import bilinear_sampler +from .modules import Mlp, AttnBlock, CrossAttnBlock, ResidualBlock + + +class EfficientUpdateFormer(nn.Module): + """ + Transformer model that updates track estimates. + """ + + def __init__( + self, + space_depth=6, + time_depth=6, + input_dim=320, + hidden_size=384, + num_heads=8, + output_dim=130, + mlp_ratio=4.0, + add_space_attn=True, + num_virtual_tracks=64, + ): + super().__init__() + + self.out_channels = 2 + self.num_heads = num_heads + self.hidden_size = hidden_size + self.add_space_attn = add_space_attn + + # Add input LayerNorm before linear projection + self.input_norm = nn.LayerNorm(input_dim) + self.input_transform = torch.nn.Linear(input_dim, hidden_size, bias=True) + + # Add output LayerNorm before final projection + self.output_norm = nn.LayerNorm(hidden_size) + self.flow_head = torch.nn.Linear(hidden_size, output_dim, bias=True) + self.num_virtual_tracks = num_virtual_tracks + + if self.add_space_attn: + self.virual_tracks = nn.Parameter(torch.randn(1, num_virtual_tracks, 1, hidden_size)) + else: + self.virual_tracks = None + + self.time_blocks = nn.ModuleList( + [ + AttnBlock( + hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + attn_class=nn.MultiheadAttention, + ) + for _ in range(time_depth) + ] + ) + + if add_space_attn: + self.space_virtual_blocks = nn.ModuleList( + [ + AttnBlock( + hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + attn_class=nn.MultiheadAttention, + ) + for _ in range(space_depth) + ] + ) + self.space_point2virtual_blocks = nn.ModuleList( + [CrossAttnBlock(hidden_size, hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(space_depth)] + ) + self.space_virtual2point_blocks = nn.ModuleList( + [CrossAttnBlock(hidden_size, hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(space_depth)] + ) + assert len(self.time_blocks) >= len(self.space_virtual2point_blocks) + self.initialize_weights() + + def initialize_weights(self): + 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) + torch.nn.init.trunc_normal_(self.flow_head.weight, std=0.001) + + self.apply(_basic_init) + + def forward(self, input_tensor, mask=None): + # Apply input LayerNorm + input_tensor = self.input_norm(input_tensor) + tokens = self.input_transform(input_tensor) + + init_tokens = tokens + + B, _, T, _ = tokens.shape + + if self.add_space_attn: + virtual_tokens = self.virual_tracks.repeat(B, 1, T, 1) + tokens = torch.cat([tokens, virtual_tokens], dim=1) + + _, N, _, _ = tokens.shape + + j = 0 + for i in range(len(self.time_blocks)): + time_tokens = tokens.contiguous().view(B * N, T, -1) # B N T C -> (B N) T C + + time_tokens = self.time_blocks[i](time_tokens) + + tokens = time_tokens.view(B, N, T, -1) # (B N) T C -> B N T C + if self.add_space_attn and (i % (len(self.time_blocks) // len(self.space_virtual_blocks)) == 0): + space_tokens = tokens.permute(0, 2, 1, 3).contiguous().view(B * T, N, -1) # B N T C -> (B T) N C + point_tokens = space_tokens[:, : N - self.num_virtual_tracks] + virtual_tokens = space_tokens[:, N - self.num_virtual_tracks :] + + virtual_tokens = self.space_virtual2point_blocks[j](virtual_tokens, point_tokens, mask=mask) + virtual_tokens = self.space_virtual_blocks[j](virtual_tokens) + point_tokens = self.space_point2virtual_blocks[j](point_tokens, virtual_tokens, mask=mask) + + space_tokens = torch.cat([point_tokens, virtual_tokens], dim=1) + tokens = space_tokens.view(B, T, N, -1).permute(0, 2, 1, 3) # (B T) N C -> B N T C + j += 1 + + if self.add_space_attn: + tokens = tokens[:, : N - self.num_virtual_tracks] + + tokens = tokens + init_tokens + + # Apply output LayerNorm before final projection + tokens = self.output_norm(tokens) + flow = self.flow_head(tokens) + + return flow, None + + +class CorrBlock: + def __init__(self, fmaps, num_levels=4, radius=4, multiple_track_feats=False, padding_mode="zeros"): + """ + Build a pyramid of feature maps from the input. + + fmaps: Tensor (B, S, C, H, W) + num_levels: number of pyramid levels (each downsampled by factor 2) + radius: search radius for sampling correlation + multiple_track_feats: if True, split the target features per pyramid level + padding_mode: passed to grid_sample / bilinear_sampler + """ + B, S, C, H, W = fmaps.shape + self.S, self.C, self.H, self.W = S, C, H, W + self.num_levels = num_levels + self.radius = radius + self.padding_mode = padding_mode + self.multiple_track_feats = multiple_track_feats + + # Build pyramid: each level is half the spatial resolution of the previous + self.fmaps_pyramid = [fmaps] # level 0 is full resolution + current_fmaps = fmaps + for i in range(num_levels - 1): + B, S, C, H, W = current_fmaps.shape + # Merge batch & sequence dimensions + current_fmaps = current_fmaps.reshape(B * S, C, H, W) + # Avg pool down by factor 2 + current_fmaps = F.avg_pool2d(current_fmaps, kernel_size=2, stride=2) + _, _, H_new, W_new = current_fmaps.shape + current_fmaps = current_fmaps.reshape(B, S, C, H_new, W_new) + self.fmaps_pyramid.append(current_fmaps) + + # Precompute a delta grid (of shape (2r+1, 2r+1, 2)) for sampling. + # This grid is added to the (scaled) coordinate centroids. + r = self.radius + dx = torch.linspace(-r, r, 2 * r + 1, device=fmaps.device, dtype=fmaps.dtype) + dy = torch.linspace(-r, r, 2 * r + 1, device=fmaps.device, dtype=fmaps.dtype) + # delta: for every (dy,dx) displacement (i.e. Δx, Δy) + self.delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), dim=-1) # shape: (2r+1, 2r+1, 2) + + def corr_sample(self, targets, coords): + """ + Instead of storing the entire correlation pyramid, we compute each level's correlation + volume, sample it immediately, then discard it. This saves GPU memory. + + Args: + targets: Tensor (B, S, N, C) — features for the current targets. + coords: Tensor (B, S, N, 2) — coordinates at full resolution. + + Returns: + Tensor (B, S, N, L) where L = num_levels * (2*radius+1)**2 (concatenated sampled correlations) + """ + B, S, N, C = targets.shape + + # If you have multiple track features, split them per level. + if self.multiple_track_feats: + targets_split = torch.split(targets, C // self.num_levels, dim=-1) + + out_pyramid = [] + for i, fmaps in enumerate(self.fmaps_pyramid): + # Get current spatial resolution H, W for this pyramid level. + B, S, C, H, W = fmaps.shape + # Reshape feature maps for correlation computation: + # fmap2s: (B, S, C, H*W) + fmap2s = fmaps.view(B, S, C, H * W) + # Choose appropriate target features. + fmap1 = targets_split[i] if self.multiple_track_feats else targets # shape: (B, S, N, C) + + # Compute correlation directly + corrs = compute_corr_level(fmap1, fmap2s, C) + corrs = corrs.view(B, S, N, H, W) + + # Prepare sampling grid: + # Scale down the coordinates for the current level. + centroid_lvl = coords.reshape(B * S * N, 1, 1, 2) / (2**i) + # Make sure our precomputed delta grid is on the same device/dtype. + delta_lvl = self.delta.to(coords.device).to(coords.dtype) + # Now the grid for grid_sample is: + # coords_lvl = centroid_lvl + delta_lvl (broadcasted over grid) + coords_lvl = centroid_lvl + delta_lvl.view(1, 2 * self.radius + 1, 2 * self.radius + 1, 2) + + # Sample from the correlation volume using bilinear interpolation. + # We reshape corrs to (B * S * N, 1, H, W) so grid_sample acts over each target. + corrs_sampled = bilinear_sampler( + corrs.reshape(B * S * N, 1, H, W), coords_lvl, padding_mode=self.padding_mode + ) + # The sampled output is (B * S * N, 1, 2r+1, 2r+1). Flatten the last two dims. + corrs_sampled = corrs_sampled.view(B, S, N, -1) # Now shape: (B, S, N, (2r+1)^2) + out_pyramid.append(corrs_sampled) + + # Concatenate all levels along the last dimension. + out = torch.cat(out_pyramid, dim=-1).contiguous() + return out + + +def compute_corr_level(fmap1, fmap2s, C): + # fmap1: (B, S, N, C) + # fmap2s: (B, S, C, H*W) + corrs = torch.matmul(fmap1, fmap2s) # (B, S, N, H*W) + corrs = corrs.view(fmap1.shape[0], fmap1.shape[1], fmap1.shape[2], -1) # (B, S, N, H*W) + return corrs / math.sqrt(C) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/modules.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..4b090ddc4a9db01c8dd3564f9053e1ca9cdde93a --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/modules.py @@ -0,0 +1,218 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +from typing import Callable +import collections +from torch import Tensor +from itertools import repeat + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): + return tuple(x) + return tuple(repeat(x, n)) + + return parse + + +def exists(val): + return val is not None + + +def default(val, d): + return val if exists(val) else d + + +to_2tuple = _ntuple(2) + + +class ResidualBlock(nn.Module): + """ + ResidualBlock: construct a block of two conv layers with residual connections + """ + + def __init__(self, in_planes, planes, norm_fn="group", stride=1, kernel_size=3): + super(ResidualBlock, self).__init__() + + self.conv1 = nn.Conv2d( + in_planes, + planes, + kernel_size=kernel_size, + padding=1, + stride=stride, + padding_mode="zeros", + ) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=kernel_size, + padding=1, + padding_mode="zeros", + ) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not stride == 1: + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(planes) + self.norm2 = nn.BatchNorm2d(planes) + if not stride == 1: + self.norm3 = nn.BatchNorm2d(planes) + + elif norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(planes) + self.norm2 = nn.InstanceNorm2d(planes) + if not stride == 1: + self.norm3 = nn.InstanceNorm2d(planes) + + elif norm_fn == "none": + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + if not stride == 1: + self.norm3 = nn.Sequential() + else: + raise NotImplementedError + + if stride == 1: + self.downsample = None + else: + self.downsample = nn.Sequential( + nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), + self.norm3, + ) + + def forward(self, x): + y = x + y = self.relu(self.norm1(self.conv1(y))) + y = self.relu(self.norm2(self.conv2(y))) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class Mlp(nn.Module): + """MLP as used in Vision Transformer, MLP-Mixer and related networks""" + + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + norm_layer=None, + bias=True, + drop=0.0, + use_conv=False, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + bias = to_2tuple(bias) + drop_probs = to_2tuple(drop) + linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear + + self.fc1 = linear_layer(in_features, hidden_features, bias=bias[0]) + self.act = act_layer() + self.drop1 = nn.Dropout(drop_probs[0]) + self.fc2 = linear_layer(hidden_features, out_features, bias=bias[1]) + self.drop2 = nn.Dropout(drop_probs[1]) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop1(x) + x = self.fc2(x) + x = self.drop2(x) + return x + + +class AttnBlock(nn.Module): + def __init__( + self, + hidden_size, + num_heads, + attn_class: Callable[..., nn.Module] = nn.MultiheadAttention, + mlp_ratio=4.0, + **block_kwargs + ): + """ + Self attention block + """ + super().__init__() + + self.norm1 = nn.LayerNorm(hidden_size) + self.norm2 = nn.LayerNorm(hidden_size) + + self.attn = attn_class(embed_dim=hidden_size, num_heads=num_heads, batch_first=True, **block_kwargs) + + mlp_hidden_dim = int(hidden_size * mlp_ratio) + + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, drop=0) + + def forward(self, x, mask=None): + # Prepare the mask for PyTorch's attention (it expects a different format) + # attn_mask = mask if mask is not None else None + # Normalize before attention + x = self.norm1(x) + + # PyTorch's MultiheadAttention returns attn_output, attn_output_weights + # attn_output, _ = self.attn(x, x, x, attn_mask=attn_mask) + + attn_output, _ = self.attn(x, x, x) + + # Add & Norm + x = x + attn_output + x = x + self.mlp(self.norm2(x)) + return x + + +class CrossAttnBlock(nn.Module): + def __init__(self, hidden_size, context_dim, num_heads=1, mlp_ratio=4.0, **block_kwargs): + """ + Cross attention block + """ + super().__init__() + + self.norm1 = nn.LayerNorm(hidden_size) + self.norm_context = nn.LayerNorm(hidden_size) + self.norm2 = nn.LayerNorm(hidden_size) + + self.cross_attn = nn.MultiheadAttention( + embed_dim=hidden_size, num_heads=num_heads, batch_first=True, **block_kwargs + ) + + mlp_hidden_dim = int(hidden_size * mlp_ratio) + + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, drop=0) + + def forward(self, x, context, mask=None): + # Normalize inputs + x = self.norm1(x) + context = self.norm_context(context) + + # Apply cross attention + # Note: nn.MultiheadAttention returns attn_output, attn_output_weights + attn_output, _ = self.cross_attn(x, context, context, attn_mask=mask) + + # Add & Norm + x = x + attn_output + x = x + self.mlp(self.norm2(x)) + return x diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/utils.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..51d01d39cdc10388a04dab5db7cf409b31bde766 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/track_modules/utils.py @@ -0,0 +1,226 @@ +# 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 https://github.com/facebookresearch/vggsfm +# and https://github.com/facebookresearch/co-tracker/tree/main + + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Union + + +def get_2d_sincos_pos_embed(embed_dim: int, grid_size: Union[int, Tuple[int, int]], return_grid=False) -> torch.Tensor: + """ + This function initializes a grid and generates a 2D positional embedding using sine and cosine functions. + It is a wrapper of get_2d_sincos_pos_embed_from_grid. + Args: + - embed_dim: The embedding dimension. + - grid_size: The grid size. + Returns: + - pos_embed: The generated 2D positional embedding. + """ + if isinstance(grid_size, tuple): + grid_size_h, grid_size_w = grid_size + else: + grid_size_h = grid_size_w = grid_size + grid_h = torch.arange(grid_size_h, dtype=torch.float) + grid_w = torch.arange(grid_size_w, dtype=torch.float) + grid = torch.meshgrid(grid_w, grid_h, indexing="xy") + grid = torch.stack(grid, dim=0) + grid = grid.reshape([2, 1, grid_size_h, grid_size_w]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if return_grid: + return ( + pos_embed.reshape(1, grid_size_h, grid_size_w, -1).permute(0, 3, 1, 2), + grid, + ) + return pos_embed.reshape(1, grid_size_h, grid_size_w, -1).permute(0, 3, 1, 2) + + +def get_2d_sincos_pos_embed_from_grid(embed_dim: int, grid: torch.Tensor) -> torch.Tensor: + """ + This function generates a 2D positional embedding from a given grid using sine and cosine functions. + + Args: + - embed_dim: The embedding dimension. + - grid: The grid to generate the embedding from. + + Returns: + - emb: The generated 2D positional embedding. + """ + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = torch.cat([emb_h, emb_w], dim=2) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim: int, pos: torch.Tensor) -> 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 + omega = torch.arange(embed_dim // 2, dtype=torch.double) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**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[None].float() + + +def get_2d_embedding(xy: torch.Tensor, C: int, cat_coords: bool = True) -> torch.Tensor: + """ + This function generates a 2D positional embedding from given coordinates using sine and cosine functions. + + Args: + - xy: The coordinates to generate the embedding from. + - C: The size of the embedding. + - cat_coords: A flag to indicate whether to concatenate the original coordinates to the embedding. + + Returns: + - pe: The generated 2D positional embedding. + """ + B, N, D = xy.shape + assert D == 2 + + x = xy[:, :, 0:1] + y = xy[:, :, 1:2] + div_term = (torch.arange(0, C, 2, device=xy.device, dtype=torch.float32) * (1000.0 / C)).reshape(1, 1, int(C / 2)) + + pe_x = torch.zeros(B, N, C, device=xy.device, dtype=torch.float32) + pe_y = torch.zeros(B, N, C, device=xy.device, dtype=torch.float32) + + pe_x[:, :, 0::2] = torch.sin(x * div_term) + pe_x[:, :, 1::2] = torch.cos(x * div_term) + + pe_y[:, :, 0::2] = torch.sin(y * div_term) + pe_y[:, :, 1::2] = torch.cos(y * div_term) + + pe = torch.cat([pe_x, pe_y], dim=2) # (B, N, C*3) + if cat_coords: + pe = torch.cat([xy, pe], dim=2) # (B, N, C*3+3) + return pe + + +def bilinear_sampler(input, coords, align_corners=True, padding_mode="border"): + r"""Sample a tensor using bilinear interpolation + + `bilinear_sampler(input, coords)` samples a tensor :attr:`input` at + coordinates :attr:`coords` using bilinear interpolation. It is the same + as `torch.nn.functional.grid_sample()` but with a different coordinate + convention. + + The input tensor is assumed to be of shape :math:`(B, C, H, W)`, where + :math:`B` is the batch size, :math:`C` is the number of channels, + :math:`H` is the height of the image, and :math:`W` is the width of the + image. The tensor :attr:`coords` of shape :math:`(B, H_o, W_o, 2)` is + interpreted as an array of 2D point coordinates :math:`(x_i,y_i)`. + + Alternatively, the input tensor can be of size :math:`(B, C, T, H, W)`, + in which case sample points are triplets :math:`(t_i,x_i,y_i)`. Note + that in this case the order of the components is slightly different + from `grid_sample()`, which would expect :math:`(x_i,y_i,t_i)`. + + If `align_corners` is `True`, the coordinate :math:`x` is assumed to be + in the range :math:`[0,W-1]`, with 0 corresponding to the center of the + left-most image pixel :math:`W-1` to the center of the right-most + pixel. + + If `align_corners` is `False`, the coordinate :math:`x` is assumed to + be in the range :math:`[0,W]`, with 0 corresponding to the left edge of + the left-most pixel :math:`W` to the right edge of the right-most + pixel. + + Similar conventions apply to the :math:`y` for the range + :math:`[0,H-1]` and :math:`[0,H]` and to :math:`t` for the range + :math:`[0,T-1]` and :math:`[0,T]`. + + Args: + input (Tensor): batch of input images. + coords (Tensor): batch of coordinates. + align_corners (bool, optional): Coordinate convention. Defaults to `True`. + padding_mode (str, optional): Padding mode. Defaults to `"border"`. + + Returns: + Tensor: sampled points. + """ + coords = coords.detach().clone() + ############################################################ + # IMPORTANT: + coords = coords.to(input.device).to(input.dtype) + ############################################################ + + sizes = input.shape[2:] + + assert len(sizes) in [2, 3] + + if len(sizes) == 3: + # t x y -> x y t to match dimensions T H W in grid_sample + coords = coords[..., [1, 2, 0]] + + if align_corners: + scale = torch.tensor( + [2 / max(size - 1, 1) for size in reversed(sizes)], device=coords.device, dtype=coords.dtype + ) + else: + scale = torch.tensor([2 / size for size in reversed(sizes)], device=coords.device, dtype=coords.dtype) + + coords.mul_(scale) # coords = coords * scale + coords.sub_(1) # coords = coords - 1 + + return F.grid_sample(input, coords, align_corners=align_corners, padding_mode=padding_mode) + + +def sample_features4d(input, coords): + r"""Sample spatial features + + `sample_features4d(input, coords)` samples the spatial features + :attr:`input` represented by a 4D tensor :math:`(B, C, H, W)`. + + The field is sampled at coordinates :attr:`coords` using bilinear + interpolation. :attr:`coords` is assumed to be of shape :math:`(B, R, + 2)`, where each sample has the format :math:`(x_i, y_i)`. This uses the + same convention as :func:`bilinear_sampler` with `align_corners=True`. + + The output tensor has one feature per point, and has shape :math:`(B, + R, C)`. + + Args: + input (Tensor): spatial features. + coords (Tensor): points. + + Returns: + Tensor: sampled features. + """ + + B, _, _, _ = input.shape + + # B R 2 -> B R 1 2 + coords = coords.unsqueeze(2) + + # B C R 1 + feats = bilinear_sampler(input, coords) + + return feats.permute(0, 2, 1, 3).view(B, -1, feats.shape[1] * feats.shape[3]) # B C R 1 -> B R C diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/heads/utils.py b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d7af1f68fa0ce0a48d11a708d53aa20aa8f78ba2 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/heads/utils.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + + +def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor: + """ + Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC) + + Args: + pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates + embed_dim: Output channel dimension for embeddings + + Returns: + Tensor of shape (H, W, embed_dim) with positional embeddings + """ + H, W, grid_dim = pos_grid.shape + assert grid_dim == 2 + pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2) + + # Process x and y coordinates separately + emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2] + emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2] + + # Combine and reshape + emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D] + + return emb.view(H, W, embed_dim) # [H, W, D] + + +def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor: + """ + This function generates a 1D positional embedding from a given grid using sine and cosine functions. + + Args: + - embed_dim: The embedding dimension. + - pos: The position to generate the embedding from. + + Returns: + - emb: The generated 1D positional embedding. + """ + assert embed_dim % 2 == 0 + omega = torch.arange(embed_dim // 2, dtype=torch.double, device=pos.device) + omega /= embed_dim / 2.0 + omega = 1.0 / omega_0**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = torch.sin(out) # (M, D/2) + emb_cos = torch.cos(out) # (M, D/2) + + emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) + return emb.float() + + +# Inspired by https://github.com/microsoft/moge + + +def create_uv_grid( + width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None +) -> torch.Tensor: + """ + Create a normalized UV grid of shape (width, height, 2). + + The grid spans horizontally and vertically according to an aspect ratio, + ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right + corner is at (x_span, y_span), normalized by the diagonal of the plane. + + Args: + width (int): Number of points horizontally. + height (int): Number of points vertically. + aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height. + dtype (torch.dtype, optional): Data type of the resulting tensor. + device (torch.device, optional): Device on which the tensor is created. + + Returns: + torch.Tensor: A (width, height, 2) tensor of UV coordinates. + """ + # Derive aspect ratio if not explicitly provided + if aspect_ratio is None: + aspect_ratio = float(width) / float(height) + + # Compute normalized spans for X and Y + diag_factor = (aspect_ratio**2 + 1.0) ** 0.5 + span_x = aspect_ratio / diag_factor + span_y = 1.0 / diag_factor + + # Establish the linspace boundaries + left_x = -span_x * (width - 1) / width + right_x = span_x * (width - 1) / width + top_y = -span_y * (height - 1) / height + bottom_y = span_y * (height - 1) / height + + # Generate 1D coordinates + x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device) + y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device) + + # Create 2D meshgrid (width x height) and stack into UV + uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy") + uv_grid = torch.stack((uu, vv), dim=-1) + + return uv_grid diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/__init__.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8120f4bc83066cb3f825ce32daa3b437f88486f1 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .mlp import Mlp +from .patch_embed import PatchEmbed +from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused +from .block import NestedTensorBlock +from .attention import MemEffAttention diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/attention.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..d91b78e8302738374b41a735a699b9f42575bce5 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/attention.py @@ -0,0 +1,100 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import logging +import os +import warnings + +from torch import Tensor +from torch import nn +import torch.nn.functional as F + +XFORMERS_AVAILABLE = False + + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + norm_layer: nn.Module = nn.LayerNorm, + qk_norm: bool = False, + 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.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, fused_attn=True) -> 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 fused_attn: + x = F.scaled_dot_product_attention( + q, + k, + v, + dropout_p=self.attn_drop.p if self.training else 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) + + if fused_attn: + return x + else: + return x, attn + + +class MemEffAttention(Attention): + def forward(self, x: Tensor, attn_bias=None, pos=None, fused_attn=True) -> Tensor: + assert pos is None + if not XFORMERS_AVAILABLE: + if attn_bias is not None: + raise AssertionError("xFormers is required for using nested tensors") + return super().forward(x) + + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + q, k, v = unbind(qkv, 2) + + x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) + x = x.reshape([B, N, C]) + + x = self.proj(x) + x = self.proj_drop(x) + return x diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/block.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/block.py new file mode 100644 index 0000000000000000000000000000000000000000..aa96b7dad810a7e3fb1103205aed114b094cedef --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/block.py @@ -0,0 +1,269 @@ +# 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 + +import logging +import os +from typing import Callable, List, Any, Tuple, Dict +import warnings + +import torch +from torch import nn, Tensor + +from .attention import Attention +from .drop_path import DropPath +from .layer_scale import LayerScale +from .mlp import Mlp + + +XFORMERS_AVAILABLE = False + + +class Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + 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, + 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, + rope=rope, + ) + + self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 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() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.sample_drop_ratio = drop_path + + def forward(self, x: Tensor, pos=None, fused_attn = True) -> Tensor: + def attn_residual_func(x: Tensor, pos=None) -> Tensor: + if fused_attn: + return self.ls1(self.attn(self.norm1(x), pos=pos, fused_attn=fused_attn)) + else: + x, attn = self.attn(self.norm1(x), pos=pos, fused_attn=fused_attn) + x = self.ls1(x) + return x, attn + + def ffn_residual_func(x: Tensor) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + if self.training and self.sample_drop_ratio > 0.1: + # the overhead is compensated only for a drop path rate larger than 0.1 + x = drop_add_residual_stochastic_depth( + x, + pos=pos, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + x = drop_add_residual_stochastic_depth( + x, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + elif self.training and self.sample_drop_ratio > 0.0: + x = x + self.drop_path1(attn_residual_func(x, pos=pos)) + x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 + else: + if fused_attn: + x = x + attn_residual_func(x, pos=pos) + x = x + ffn_residual_func(x) + return x + else: + x_after_attn, attn = attn_residual_func(x, pos=pos) + x = x + x_after_attn + x = x + ffn_residual_func(x) + return x, attn + return x + + +def drop_add_residual_stochastic_depth( + x: Tensor, + residual_func: Callable[[Tensor], Tensor], + sample_drop_ratio: float = 0.0, + pos=None, +) -> Tensor: + # 1) extract subset using permutation + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + x_subset = x[brange] + + # 2) apply residual_func to get residual + if pos is not None: + # if necessary, apply rope to the subset + pos = pos[brange] + residual = residual_func(x_subset, pos=pos) + else: + residual = residual_func(x_subset) + + x_flat = x.flatten(1) + residual = residual.flatten(1) + + residual_scale_factor = b / sample_subset_size + + # 3) add the residual + x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) + return x_plus_residual.view_as(x) + + +def get_branges_scales(x, sample_drop_ratio=0.0): + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + residual_scale_factor = b / sample_subset_size + return brange, residual_scale_factor + + +def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): + if scaling_vector is None: + x_flat = x.flatten(1) + residual = residual.flatten(1) + x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) + else: + x_plus_residual = scaled_index_add( + x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor + ) + return x_plus_residual + + +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 + + +def drop_add_residual_stochastic_depth_list( + x_list: List[Tensor], + residual_func: Callable[[Tensor, Any], Tensor], + sample_drop_ratio: float = 0.0, + scaling_vector=None, +) -> Tensor: + # 1) generate random set of indices for dropping samples in the batch + branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list] + branges = [s[0] for s in branges_scales] + residual_scale_factors = [s[1] for s in branges_scales] + + # 2) get attention bias and index+concat the tensors + attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges) + + # 3) apply residual_func to get residual, and split the result + residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore + + outputs = [] + for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors): + outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x)) + return outputs + + +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) + + if self.training and self.sample_drop_ratio > 0.0: + + def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.attn(self.norm1(x), attn_bias=attn_bias) + + def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.mlp(self.norm2(x)) + + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None, + ) + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None, + ) + return x_list + else: + + def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) + + def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + attn_bias, x = get_attn_bias_and_cat(x_list) + x = x + attn_residual_func(x, attn_bias=attn_bias) + x = x + ffn_residual_func(x) + return attn_bias.split(x) + + def forward(self, x_or_x_list): + if isinstance(x_or_x_list, Tensor): + return super().forward(x_or_x_list) + elif isinstance(x_or_x_list, list): + if not XFORMERS_AVAILABLE: + raise AssertionError("xFormers is required for using nested tensors") + return self.forward_nested(x_or_x_list) + else: + raise AssertionError diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/drop_path.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..1d640e0b969b8dcba96260243473700b4e5b24b5 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/drop_path.py @@ -0,0 +1,34 @@ +# 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/drop.py + + +from torch import nn + + +def drop_path(x, drop_prob: float = 0.0, training: bool = False): + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + output = x * random_tensor + return output + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/layer_scale.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..51df0d7ce61f2b41fa9e6369f52391dd7fe7d386 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/layer_scale.py @@ -0,0 +1,27 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 + +from typing import Union + +import torch +from torch import Tensor +from torch import nn + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/mlp.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..bbf9432aae9258612caeae910a7bde17999e328e --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/mlp.py @@ -0,0 +1,40 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py + + +from typing import Callable, Optional + +from torch import Tensor, nn + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/patch_embed.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..8b7c0804784a42cf80c0297d110dcc68cc85b339 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/patch_embed.py @@ -0,0 +1,88 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +from typing import Callable, Optional, Tuple, Union + +from torch import Tensor +import torch.nn as nn + + +def make_2tuple(x): + if isinstance(x, tuple): + assert len(x) == 2 + return x + + assert isinstance(x, int) + return (x, x) + + +class PatchEmbed(nn.Module): + """ + 2D image to patch embedding: (B,C,H,W) -> (B,N,D) + + Args: + img_size: Image size. + patch_size: Patch token size. + in_chans: Number of input image channels. + embed_dim: Number of linear projection output channels. + norm_layer: Normalization layer. + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int]] = 16, + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Optional[Callable] = None, + flatten_embedding: bool = True, + ) -> None: + super().__init__() + + image_HW = make_2tuple(img_size) + patch_HW = make_2tuple(patch_size) + patch_grid_size = ( + image_HW[0] // patch_HW[0], + image_HW[1] // patch_HW[1], + ) + + self.img_size = image_HW + self.patch_size = patch_HW + self.patches_resolution = patch_grid_size + self.num_patches = patch_grid_size[0] * patch_grid_size[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.flatten_embedding = flatten_embedding + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + _, _, H, W = x.shape + patch_H, patch_W = self.patch_size + + assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}" + assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}" + + x = self.proj(x) # B C H W + H, W = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) # B HW C + x = self.norm(x) + if not self.flatten_embedding: + x = x.reshape(-1, H, W, self.embed_dim) # B H W C + return x + + def flops(self) -> float: + Ho, Wo = self.patches_resolution + flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/rope.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..4d5d33304e55dbd05687bd86752a47a80e5f82df --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/rope.py @@ -0,0 +1,188 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + + +# Implementation of 2D Rotary Position Embeddings (RoPE). + +# This module provides a clean implementation of 2D Rotary Position Embeddings, +# which extends the original RoPE concept to handle 2D spatial positions. + +# Inspired by: +# https://github.com/meta-llama/codellama/blob/main/llama/model.py +# https://github.com/naver-ai/rope-vit + + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Dict, Tuple + + +class PositionGetter: + """Generates and caches 2D spatial positions for patches in a grid. + + This class efficiently manages the generation of spatial coordinates for patches + in a 2D grid, caching results to avoid redundant computations. + + Attributes: + position_cache: Dictionary storing precomputed position tensors for different + grid dimensions. + """ + + def __init__(self): + """Initializes the position generator with an empty cache.""" + self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {} + + def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor: + """Generates spatial positions for a batch of patches. + + Args: + batch_size: Number of samples in the batch. + height: Height of the grid in patches. + width: Width of the grid in patches. + device: Target device for the position tensor. + + Returns: + Tensor of shape (batch_size, height*width, 2) containing y,x coordinates + for each position in the grid, repeated for each batch item. + """ + if (height, width) not in self.position_cache: + y_coords = torch.arange(height, device=device) + x_coords = torch.arange(width, device=device) + positions = torch.cartesian_prod(y_coords, x_coords) + self.position_cache[height, width] = positions + + cached_positions = self.position_cache[height, width] + return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone() + + +class RotaryPositionEmbedding2D(nn.Module): + """2D Rotary Position Embedding implementation. + + This module applies rotary position embeddings to input tokens based on their + 2D spatial positions. It handles the position-dependent rotation of features + separately for vertical and horizontal dimensions. + + Args: + frequency: Base frequency for the position embeddings. Default: 100.0 + scaling_factor: Scaling factor for frequency computation. Default: 1.0 + + Attributes: + base_frequency: Base frequency for computing position embeddings. + scaling_factor: Factor to scale the computed frequencies. + frequency_cache: Cache for storing precomputed frequency components. + """ + + def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0): + """Initializes the 2D RoPE module.""" + super().__init__() + self.base_frequency = frequency + self.scaling_factor = scaling_factor + self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {} + + def _compute_frequency_components( + self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes frequency components for rotary embeddings. + + Args: + dim: Feature dimension (must be even). + seq_len: Maximum sequence length. + device: Target device for computations. + dtype: Data type for the computed tensors. + + Returns: + Tuple of (cosine, sine) tensors for frequency components. + """ + cache_key = (dim, seq_len, device, dtype) + if cache_key not in self.frequency_cache: + # Compute frequency bands + exponents = torch.arange(0, dim, 2, device=device).float() / dim + inv_freq = 1.0 / (self.base_frequency**exponents) + + # Generate position-dependent frequencies + positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + angles = torch.einsum("i,j->ij", positions, inv_freq) + + # Compute and cache frequency components + angles = angles.to(dtype) + angles = torch.cat((angles, angles), dim=-1) + cos_components = angles.cos().to(dtype) + sin_components = angles.sin().to(dtype) + self.frequency_cache[cache_key] = (cos_components, sin_components) + + return self.frequency_cache[cache_key] + + @staticmethod + def _rotate_features(x: torch.Tensor) -> torch.Tensor: + """Performs feature rotation by splitting and recombining feature dimensions. + + Args: + x: Input tensor to rotate. + + Returns: + Rotated feature tensor. + """ + feature_dim = x.shape[-1] + x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :] + return torch.cat((-x2, x1), dim=-1) + + def _apply_1d_rope( + self, tokens: torch.Tensor, positions: torch.Tensor, cos_comp: torch.Tensor, sin_comp: torch.Tensor + ) -> torch.Tensor: + """Applies 1D rotary position embeddings along one dimension. + + Args: + tokens: Input token features. + positions: Position indices. + cos_comp: Cosine components for rotation. + sin_comp: Sine components for rotation. + + Returns: + Tokens with applied rotary position embeddings. + """ + # Embed positions with frequency components + cos = F.embedding(positions, cos_comp)[:, None, :, :] + sin = F.embedding(positions, sin_comp)[:, None, :, :] + + # Apply rotation + return (tokens * cos) + (self._rotate_features(tokens) * sin) + + def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + """Applies 2D rotary position embeddings to input tokens. + + Args: + tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim). + The feature dimension (dim) must be divisible by 4. + positions: Position tensor of shape (batch_size, n_tokens, 2) containing + the y and x coordinates for each token. + + Returns: + Tensor of same shape as input with applied 2D rotary position embeddings. + + Raises: + AssertionError: If input dimensions are invalid or positions are malformed. + """ + # Validate inputs + assert tokens.size(-1) % 2 == 0, "Feature dimension must be even" + assert positions.ndim == 3 and positions.shape[-1] == 2, "Positions must have shape (batch_size, n_tokens, 2)" + + # Compute feature dimension for each spatial direction + feature_dim = tokens.size(-1) // 2 + + # Get frequency components + max_position = int(positions.max()) + 1 + cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype) + + # Split features for vertical and horizontal processing + vertical_features, horizontal_features = tokens.chunk(2, dim=-1) + + # Apply RoPE separately for each dimension + vertical_features = self._apply_1d_rope(vertical_features, positions[..., 0], cos_comp, sin_comp) + horizontal_features = self._apply_1d_rope(horizontal_features, positions[..., 1], cos_comp, sin_comp) + + # Combine processed features + return torch.cat((vertical_features, horizontal_features), dim=-1) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/swiglu_ffn.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/swiglu_ffn.py new file mode 100644 index 0000000000000000000000000000000000000000..54fe8e90b7bedf6fbdbf09c6215844e3cc63f857 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/swiglu_ffn.py @@ -0,0 +1,72 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +import os +from typing import Callable, Optional +import warnings + +from torch import Tensor, nn +import torch.nn.functional as F + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None +# try: +# if XFORMERS_ENABLED: +# from xformers.ops import SwiGLU + +# XFORMERS_AVAILABLE = True +# warnings.warn("xFormers is available (SwiGLU)") +# else: +# warnings.warn("xFormers is disabled (SwiGLU)") +# raise ImportError +# except ImportError: +SwiGLU = SwiGLUFFN +XFORMERS_AVAILABLE = False + +# warnings.warn("xFormers is not available (SwiGLU)") + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/layers/vision_transformer.py b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..120cbe6c26650d212e50aefc497669abdc937467 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/layers/vision_transformer.py @@ -0,0 +1,407 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +from functools import partial +import math +import logging +from typing import Sequence, Tuple, Union, Callable + +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint +from torch.nn.init import trunc_normal_ +from . import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block + +logger = logging.getLogger("dinov2") + + +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, + drop_path_rate=0.0, + drop_path_uniform=False, + 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 + drop_path_rate (float): stochastic depth rate + drop_path_uniform (bool): apply uniform drop rate across blocks + 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) + + # tricky but makes it work + self.use_checkpoint = False + # + + 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 drop_path_uniform is True: + dpr = [drop_path_rate] * depth + else: + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + if ffn_layer == "mlp": + logger.info("using MLP layer as FFN") + ffn_layer = Mlp + elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": + logger.info("using SwiGLU layer as FFN") + ffn_layer = SwiGLUFFNFused + elif ffn_layer == "identity": + logger.info("using Identity layer as FFN") + + 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, + drop_path=dpr[i], + 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: + if self.use_checkpoint: + x = checkpoint(blk, x, use_reentrant=self.use_reentrant) + else: + 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: + if self.use_checkpoint: + x = checkpoint(blk, x, use_reentrant=self.use_reentrant) + else: + 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, is_training=True, **kwargs): + ret = self.forward_features(*args, **kwargs) + if is_training: + return ret + else: + return self.head(ret["x_norm_clstoken"]) + + +def init_weights_vit_timm(module: nn.Module, name: str = ""): + """ViT weight initialization, original timm impl (for reproducibility)""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + + +def vit_small(patch_size=16, num_register_tokens=0, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_base(patch_size=16, num_register_tokens=0, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_large(patch_size=16, num_register_tokens=0, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs): + """ + Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 + """ + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1536, + depth=40, + num_heads=24, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/models/aggregator.py b/loomnet/models/extras/geometry_loss/vggt/vggt/models/aggregator.py new file mode 100644 index 0000000000000000000000000000000000000000..d6517fb96ae672fb5389818dbc9d1cbd507733bd --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/models/aggregator.py @@ -0,0 +1,333 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Optional, Tuple, Union, List, Dict, Any + +from vggt.layers import PatchEmbed +from vggt.layers.block import Block +from vggt.layers.rope import RotaryPositionEmbedding2D, PositionGetter +from 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 + ): + 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.num_register_tokens = num_register_tokens + + 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 + + # 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[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], int): + The list of outputs from the attention blocks, + 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)): + # 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) + + del concat_inter + del frame_intermediates + del global_intermediates + return output_list, self.patch_start_idx + + def _process_frame_attention(self, tokens, B, S, P, C, frame_idx, pos=None): + """ + Process frame attention blocks. We keep tokens in shape (B*S, P, C). + """ + # If needed, reshape tokens or positions: + if tokens.shape != (B * S, P, C): + tokens = tokens.view(B, S, P, C).view(B * S, P, C) + + if pos is not None and pos.shape != (B * S, P, 2): + pos = pos.view(B, S, P, 2).view(B * S, P, 2) + + intermediates = [] + + # by default, self.aa_block_size=1, which processes one block at a time + for _ in range(self.aa_block_size): + tokens = self.frame_blocks[frame_idx](tokens, pos=pos) + frame_idx += 1 + intermediates.append(tokens.view(B, S, P, C)) + + return tokens, frame_idx, intermediates + + def _process_global_attention(self, tokens, B, S, P, C, global_idx, pos=None): + """ + Process global attention blocks. We keep tokens in shape (B, S*P, C). + """ + if tokens.shape != (B, S * P, C): + tokens = tokens.view(B, S, P, C).view(B, S * P, C) + + if pos is not None and pos.shape != (B, S * P, 2): + pos = pos.view(B, S, P, 2).view(B, S * P, 2) + + intermediates = [] + + # by default, self.aa_block_size=1, which processes one block at a time + for _ in range(self.aa_block_size): + tokens = self.global_blocks[global_idx](tokens, pos=pos) + global_idx += 1 + intermediates.append(tokens.view(B, S, P, C)) + + return tokens, global_idx, intermediates + + +def slice_expand_and_flatten(token_tensor, B, S): + """ + Processes specialized tokens with shape (1, 2, X, C) for multi-frame processing: + 1) Uses the first position (index=0) for the first frame only + 2) Uses the second position (index=1) for all remaining frames (S-1 frames) + 3) Expands both to match batch size B + 4) Concatenates to form (B, S, X, C) where each sequence has 1 first-position token + followed by (S-1) second-position tokens + 5) Flattens to (B*S, X, C) for processing + + Returns: + torch.Tensor: Processed tokens with shape (B*S, X, C) + """ + + # Slice out the "query" tokens => shape (1, 1, ...) + query = token_tensor[:, 0:1, ...].expand(B, 1, *token_tensor.shape[2:]) + # Slice out the "other" tokens => shape (1, S-1, ...) + others = token_tensor[:, 1:, ...].expand(B, S - 1, *token_tensor.shape[2:]) + # Concatenate => shape (B, S, ...) + combined = torch.cat([query, others], dim=1) + + # Finally flatten => shape (B*S, ...) + combined = combined.view(B * S, *combined.shape[2:]) + return combined diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/models/vggt.py b/loomnet/models/extras/geometry_loss/vggt/vggt/models/vggt.py new file mode 100644 index 0000000000000000000000000000000000000000..ad48093b2b4969f840a5828c16297b2a30eb27e9 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/models/vggt.py @@ -0,0 +1,95 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +import torch +import torch.nn as nn +from huggingface_hub import PyTorchModelHubMixin # used for model hub + +from vggt.models.aggregator import Aggregator +from vggt.heads.camera_head import CameraHead +from vggt.heads.dpt_head import DPTHead +from vggt.heads.track_head import TrackHead + + +class VGGT(nn.Module, PyTorchModelHubMixin): + def __init__(self, img_size=518, patch_size=14, embed_dim=1024): + 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) + self.point_head = DPTHead(dim_in=2 * embed_dim, output_dim=4, activation="inv_log", conf_activation="expp1") + self.depth_head = DPTHead(dim_in=2 * embed_dim, output_dim=2, activation="exp", conf_activation="expp1") + self.track_head = TrackHead(dim_in=2 * embed_dim, patch_size=patch_size) + + def forward( + self, + images: torch.Tensor, + query_points: torch.Tensor = None, + ): + """ + Forward pass of the VGGT model. + + Args: + images (torch.Tensor): Input images with shape [S, 3, H, W] or [B, S, 3, H, W], in range [0, 1]. + B: batch size, S: sequence length, 3: RGB channels, H: height, W: width + query_points (torch.Tensor, optional): Query points for tracking, in pixel coordinates. + Shape: [N, 2] or [B, N, 2], where N is the number of query points. + Default: None + + Returns: + dict: A dictionary containing the following predictions: + - pose_enc (torch.Tensor): Camera pose encoding with shape [B, S, 9] (from the last iteration) + - depth (torch.Tensor): Predicted depth maps with shape [B, S, H, W, 1] + - depth_conf (torch.Tensor): Confidence scores for depth predictions with shape [B, S, H, W] + - world_points (torch.Tensor): 3D world coordinates for each pixel with shape [B, S, H, W, 3] + - world_points_conf (torch.Tensor): Confidence scores for world points with shape [B, S, H, W] + - images (torch.Tensor): Original input images, preserved for visualization + + If query_points is provided, also includes: + - track (torch.Tensor): Point tracks with shape [B, S, N, 2] (from the last iteration), in pixel coordinates + - vis (torch.Tensor): Visibility scores for tracked points with shape [B, S, N] + - conf (torch.Tensor): Confidence scores for tracked points with shape [B, S, N] + """ + + # If without batch dimension, add it + if len(images.shape) == 4: + images = images.unsqueeze(0) + if query_points is not None and len(query_points.shape) == 2: + query_points = query_points.unsqueeze(0) + + aggregated_tokens_list, patch_start_idx = self.aggregator(images) + + predictions = {} + + with torch.cuda.amp.autocast(enabled=False): + if self.camera_head is not None: + pose_enc_list = self.camera_head(aggregated_tokens_list) + predictions["pose_enc"] = pose_enc_list[-1] # pose encoding of the last iteration + + if self.depth_head is not None: + depth, depth_conf = self.depth_head( + aggregated_tokens_list, images=images, patch_start_idx=patch_start_idx + ) + predictions["depth"] = depth + predictions["depth_conf"] = depth_conf + + if self.point_head is not None: + pts3d, pts3d_conf = self.point_head( + aggregated_tokens_list, images=images, patch_start_idx=patch_start_idx + ) + predictions["world_points"] = pts3d + predictions["world_points_conf"] = pts3d_conf + + if self.track_head is not None and query_points is not None: + track_list, vis, conf = self.track_head( + aggregated_tokens_list, images=images, patch_start_idx=patch_start_idx, query_points=query_points + ) + predictions["track"] = track_list[-1] # track of the last iteration + predictions["vis"] = vis + predictions["conf"] = conf + + predictions["images"] = images + + return predictions diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/utils/geometry.py b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..8ebd25dbc6cac6b0095956524c4f0628410dd5cb --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/geometry.py @@ -0,0 +1,166 @@ +# 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 os +import torch +import numpy as np + + +def unproject_depth_map_to_point_map( + depth_map: np.ndarray, extrinsics_cam: np.ndarray, intrinsics_cam: np.ndarray +) -> np.ndarray: + """ + Unproject a batch of depth maps to 3D world coordinates. + + Args: + depth_map (np.ndarray): Batch of depth maps of shape (S, H, W, 1) or (S, H, W) + extrinsics_cam (np.ndarray): Batch of camera extrinsic matrices of shape (S, 3, 4) + intrinsics_cam (np.ndarray): Batch of camera intrinsic matrices of shape (S, 3, 3) + + Returns: + np.ndarray: Batch of 3D world coordinates of shape (S, H, W, 3) + """ + if isinstance(depth_map, torch.Tensor): + depth_map = depth_map.cpu().numpy() + if isinstance(extrinsics_cam, torch.Tensor): + extrinsics_cam = extrinsics_cam.cpu().numpy() + if isinstance(intrinsics_cam, torch.Tensor): + intrinsics_cam = intrinsics_cam.cpu().numpy() + + world_points_list = [] + for frame_idx in range(depth_map.shape[0]): + cur_world_points, _, _ = depth_to_world_coords_points( + depth_map[frame_idx].squeeze(-1), extrinsics_cam[frame_idx], intrinsics_cam[frame_idx] + ) + world_points_list.append(cur_world_points) + world_points_array = np.stack(world_points_list, axis=0) + + return world_points_array + + +def depth_to_world_coords_points( + depth_map: np.ndarray, + extrinsic: np.ndarray, + intrinsic: np.ndarray, + eps=1e-8, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Convert a depth map to world coordinates. + + Args: + depth_map (np.ndarray): Depth map of shape (H, W). + intrinsic (np.ndarray): Camera intrinsic matrix of shape (3, 3). + extrinsic (np.ndarray): Camera extrinsic matrix of shape (3, 4). OpenCV camera coordinate convention, cam from world. + + Returns: + tuple[np.ndarray, np.ndarray]: World coordinates (H, W, 3) and valid depth mask (H, W). + """ + if depth_map is None: + return None, None, None + + # Valid depth mask + point_mask = depth_map > eps + + # Convert depth map to camera coordinates + cam_coords_points = depth_to_cam_coords_points(depth_map, intrinsic) + + # Multiply with the inverse of extrinsic matrix to transform to world coordinates + # extrinsic_inv is 4x4 (note closed_form_inverse_OpenCV is batched, the output is (N, 4, 4)) + cam_to_world_extrinsic = closed_form_inverse_se3(extrinsic[None])[0] + + R_cam_to_world = cam_to_world_extrinsic[:3, :3] + t_cam_to_world = cam_to_world_extrinsic[:3, 3] + + # Apply the rotation and translation to the camera coordinates + world_coords_points = np.dot(cam_coords_points, R_cam_to_world.T) + t_cam_to_world # HxWx3, 3x3 -> HxWx3 + # world_coords_points = np.einsum("ij,hwj->hwi", R_cam_to_world, cam_coords_points) + t_cam_to_world + + return world_coords_points, cam_coords_points, point_mask + + +def depth_to_cam_coords_points(depth_map: np.ndarray, intrinsic: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """ + Convert a depth map to camera coordinates. + + Args: + depth_map (np.ndarray): Depth map of shape (H, W). + intrinsic (np.ndarray): Camera intrinsic matrix of shape (3, 3). + + Returns: + tuple[np.ndarray, np.ndarray]: Camera coordinates (H, W, 3) + """ + H, W = depth_map.shape + assert intrinsic.shape == (3, 3), "Intrinsic matrix must be 3x3" + assert intrinsic[0, 1] == 0 and intrinsic[1, 0] == 0, "Intrinsic matrix must have zero skew" + + # Intrinsic parameters + fu, fv = intrinsic[0, 0], intrinsic[1, 1] + cu, cv = intrinsic[0, 2], intrinsic[1, 2] + + # Generate grid of pixel coordinates + u, v = np.meshgrid(np.arange(W), np.arange(H)) + + # Unproject to camera coordinates + x_cam = (u - cu) * depth_map / fu + y_cam = (v - cv) * depth_map / fv + z_cam = depth_map + + # Stack to form camera coordinates + cam_coords = np.stack((x_cam, y_cam, z_cam), axis=-1).astype(np.float32) + + return cam_coords + + +def closed_form_inverse_se3(se3, R=None, T=None): + """ + Compute the inverse of each 4x4 (or 3x4) SE3 matrix in a batch. + + If `R` and `T` are provided, they must correspond to the rotation and translation + components of `se3`. Otherwise, they will be extracted from `se3`. + + Args: + se3: Nx4x4 or Nx3x4 array or tensor of SE3 matrices. + R (optional): Nx3x3 array or tensor of rotation matrices. + T (optional): Nx3x1 array or tensor of translation vectors. + + Returns: + Inverted SE3 matrices with the same type and device as `se3`. + + Shapes: + se3: (N, 4, 4) + R: (N, 3, 3) + T: (N, 3, 1) + """ + # Check if se3 is a numpy array or a torch tensor + is_numpy = isinstance(se3, np.ndarray) + + # Validate shapes + if se3.shape[-2:] != (4, 4) and se3.shape[-2:] != (3, 4): + raise ValueError(f"se3 must be of shape (N,4,4), got {se3.shape}.") + + # Extract R and T if not provided + if R is None: + R = se3[:, :3, :3] # (N,3,3) + if T is None: + T = se3[:, :3, 3:] # (N,3,1) + + # Transpose R + if is_numpy: + # Compute the transpose of the rotation for NumPy + R_transposed = np.transpose(R, (0, 2, 1)) + # -R^T t for NumPy + top_right = -np.matmul(R_transposed, T) + inverted_matrix = np.tile(np.eye(4), (len(R), 1, 1)) + else: + R_transposed = R.transpose(1, 2) # (N,3,3) + top_right = -torch.bmm(R_transposed, T) # (N,3,1) + inverted_matrix = torch.eye(4, 4)[None].repeat(len(R), 1, 1) + inverted_matrix = inverted_matrix.to(R.dtype).to(R.device) + + inverted_matrix[:, :3, :3] = R_transposed + inverted_matrix[:, :3, 3:] = top_right + + return inverted_matrix diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/utils/load_fn.py b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/load_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..d786e98a950f880342da9a13664be4fa32eb0bfa --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/load_fn.py @@ -0,0 +1,146 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from PIL import Image +from torchvision import transforms as TF + + +def load_and_preprocess_images(image_path_list, mode="crop"): + """ + A quick start function to load and preprocess images for model input. + This assumes the images should have the same shape for easier batching, but our model can also work well with different shapes. + + Args: + image_path_list (list): List of paths to image files + mode (str, optional): Preprocessing mode, either "crop" or "pad". + - "crop" (default): Sets width to 518px and center crops height if needed. + - "pad": Preserves all pixels by making the largest dimension 518px + and padding the smaller dimension to reach a square shape. + + Returns: + torch.Tensor: Batched tensor of preprocessed images with shape (N, 3, H, W) + + Raises: + ValueError: If the input list is empty or if mode is invalid + + Notes: + - Images with different dimensions will be padded with white (value=1.0) + - A warning is printed when images have different shapes + - When mode="crop": The function ensures width=518px while maintaining aspect ratio + and height is center-cropped if larger than 518px + - When mode="pad": The function ensures the largest dimension is 518px while maintaining aspect ratio + and the smaller dimension is padded to reach a square shape (518x518) + - Dimensions are adjusted to be divisible by 14 for compatibility with model requirements + """ + # Check for empty list + if len(image_path_list) == 0: + raise ValueError("At least 1 image is required") + + # Validate mode + if mode not in ["crop", "pad"]: + raise ValueError("Mode must be either 'crop' or 'pad'") + + images = [] + shapes = set() + to_tensor = TF.ToTensor() + target_size = 518 + + # First process all images and collect their shapes + for image_path in image_path_list: + + # Open image + img = Image.open(image_path) + + # If there's an alpha channel, blend onto white background: + if img.mode == "RGBA": + # Create white background + background = Image.new("RGBA", img.size, (255, 255, 255, 255)) + # Alpha composite onto the white background + img = Image.alpha_composite(background, img) + + # Now convert to "RGB" (this step assigns white for transparent areas) + img = img.convert("RGB") + + width, height = img.size + + if mode == "pad": + # Make the largest dimension 518px while maintaining aspect ratio + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 # Make divisible by 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 # Make divisible by 14 + else: # mode == "crop" + # Original behavior: set width to 518px + new_width = target_size + # Calculate height maintaining aspect ratio, divisible by 14 + new_height = round(height * (new_width / width) / 14) * 14 + + # Resize with new dimensions (width, height) + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + img = to_tensor(img) # Convert to tensor (0, 1) + + # Center crop height if it's larger than 518 (only in crop mode) + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img = img[:, start_y : start_y + target_size, :] + + # For pad mode, pad to make a square of target_size x target_size + if mode == "pad": + h_padding = target_size - img.shape[1] + w_padding = target_size - img.shape[2] + + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + + # Pad with white (value=1.0) + img = torch.nn.functional.pad( + img, (pad_left, pad_right, pad_top, pad_bottom), mode="constant", value=1.0 + ) + + shapes.add((img.shape[1], img.shape[2])) + images.append(img) + + # Check if we have different shapes + # In theory our model can also work well with different shapes + if len(shapes) > 1: + print(f"Warning: Found images with different shapes: {shapes}") + # Find maximum dimensions + max_height = max(shape[0] for shape in shapes) + max_width = max(shape[1] for shape in shapes) + + # Pad images if necessary + padded_images = [] + for img in images: + h_padding = max_height - img.shape[1] + w_padding = max_width - img.shape[2] + + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + + img = torch.nn.functional.pad( + img, (pad_left, pad_right, pad_top, pad_bottom), mode="constant", value=1.0 + ) + padded_images.append(img) + images = padded_images + + images = torch.stack(images) # concatenate images + + # Ensure correct shape when single image + if len(image_path_list) == 1: + # Verify shape is (1, C, H, W) + if images.dim() == 3: + images = images.unsqueeze(0) + + return images diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/utils/pose_enc.py b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/pose_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..2f98b0878cb13451b8cdb80074349cbf2644c5fa --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/pose_enc.py @@ -0,0 +1,130 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from .rotation import quat_to_mat, mat_to_quat + + +def extri_intri_to_pose_encoding( + extrinsics, + intrinsics, + image_size_hw=None, # e.g., (256, 512) + pose_encoding_type="absT_quaR_FoV", +): + """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, # e.g., (256, 512) + pose_encoding_type="absT_quaR_FoV", + build_intrinsics=True, +): + """Convert a pose encoding back to camera extrinsics and intrinsics. + + This function performs the inverse operation of extri_intri_to_pose_encoding, + reconstructing the full camera parameters from the compact encoding. + + Args: + pose_encoding (torch.Tensor): Encoded camera pose parameters with shape BxSx9, + where B is batch size and S is sequence length. + For "absT_quaR_FoV" type, the 9 dimensions are: + - [:3] = absolute translation vector T (3D) + - [3:7] = rotation as quaternion quat (4D) + - [7:] = field of view (2D) + image_size_hw (tuple): Tuple of (height, width) of the image in pixels. + Required for reconstructing intrinsics from field of view values. + For example: (256, 512). + pose_encoding_type (str): Type of pose encoding used. Currently only + supports "absT_quaR_FoV" (absolute translation, quaternion rotation, field of view). + build_intrinsics (bool): Whether to reconstruct the intrinsics matrix. + If False, only extrinsics are returned and intrinsics will be None. + + Returns: + tuple: (extrinsics, intrinsics) + - extrinsics (torch.Tensor): Camera extrinsic parameters with shape BxSx3x4. + In OpenCV coordinate system (x-right, y-down, z-forward), representing camera from world + transformation. The format is [R|t] where R is a 3x3 rotation matrix and t is + a 3x1 translation vector. + - intrinsics (torch.Tensor or None): Camera intrinsic parameters with shape BxSx3x3, + or None if build_intrinsics is False. Defined in pixels, with format: + [[fx, 0, cx], + [0, fy, cy], + [0, 0, 1]] + where fx, fy are focal lengths and (cx, cy) is the principal point, + assumed to be at the center of the image (W/2, H/2). + """ + + intrinsics = None + + if pose_encoding_type == "absT_quaR_FoV": + T = pose_encoding[..., :3] + quat = pose_encoding[..., 3:7] + fov_h = pose_encoding[..., 7] + fov_w = pose_encoding[..., 8] + + R = quat_to_mat(quat) + extrinsics = torch.cat([R, T[..., None]], dim=-1) + + if build_intrinsics: + H, W = image_size_hw + fy = (H / 2.0) / torch.tan(fov_h / 2.0) + fx = (W / 2.0) / torch.tan(fov_w / 2.0) + intrinsics = torch.zeros(pose_encoding.shape[:2] + (3, 3), device=pose_encoding.device) + intrinsics[..., 0, 0] = fx + intrinsics[..., 1, 1] = fy + intrinsics[..., 0, 2] = W / 2 + intrinsics[..., 1, 2] = H / 2 + intrinsics[..., 2, 2] = 1.0 # Set the homogeneous coordinate to 1 + else: + raise NotImplementedError + + return extrinsics, intrinsics diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/utils/rotation.py b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..657583e6915437c824c192d51939990b589a14fa --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/rotation.py @@ -0,0 +1,138 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Modified from PyTorch3D, https://github.com/facebookresearch/pytorch3d + +import torch +import numpy as np +import torch.nn.functional as F + + +def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor: + """ + Quaternion Order: XYZW or say ijkr, scalar-last + + Convert rotations given as quaternions to rotation matrices. + Args: + quaternions: quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + i, j, k, r = torch.unbind(quaternions, -1) + # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`. + two_s = 2.0 / (quaternions * quaternions).sum(-1) + + o = torch.stack( + ( + 1 - two_s * (j * j + k * k), + two_s * (i * j - k * r), + two_s * (i * k + j * r), + two_s * (i * j + k * r), + 1 - two_s * (i * i + k * k), + two_s * (j * k - i * r), + two_s * (i * k - j * r), + two_s * (j * k + i * r), + 1 - two_s * (i * i + j * j), + ), + -1, + ) + return o.reshape(quaternions.shape[:-1] + (3, 3)) + + +def mat_to_quat(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to quaternions. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + quaternions with real part last, as tensor of shape (..., 4). + Quaternion Order: XYZW or say ijkr, scalar-last + """ + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + + batch_dim = matrix.shape[:-2] + m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.reshape(batch_dim + (9,)), dim=-1) + + q_abs = _sqrt_positive_part( + torch.stack( + [ + 1.0 + m00 + m11 + m22, + 1.0 + m00 - m11 - m22, + 1.0 - m00 + m11 - m22, + 1.0 - m00 - m11 + m22, + ], + dim=-1, + ) + ) + + # we produce the desired quaternion multiplied by each of r, i, j, k + quat_by_rijk = torch.stack( + [ + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), + ], + dim=-2, + ) + + # We floor here at 0.1 but the exact level is not important; if q_abs is small, + # the candidate won't be picked. + flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) + quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) + + # if not for numerical problems, quat_candidates[i] should be same (up to a sign), + # forall i; we pick the best-conditioned one (with the largest denominator) + out = quat_candidates[F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape(batch_dim + (4,)) + + # Convert from rijk to ijkr + out = out[..., [1, 2, 3, 0]] + + out = standardize_quaternion(out) + + return out + + +def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: + """ + Returns torch.sqrt(torch.max(0, x)) + but with a zero subgradient where x is 0. + """ + ret = torch.zeros_like(x) + positive_mask = x > 0 + if torch.is_grad_enabled(): + ret[positive_mask] = torch.sqrt(x[positive_mask]) + else: + ret = torch.where(positive_mask, torch.sqrt(x), ret) + return ret + + +def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt/utils/visual_track.py b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/visual_track.py new file mode 100644 index 0000000000000000000000000000000000000000..796c114ccba00b5f7850e04b9444a6cd5c44b154 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt/utils/visual_track.py @@ -0,0 +1,239 @@ +# 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 cv2 +import torch +import numpy as np +import os + + +def color_from_xy(x, y, W, H, cmap_name="hsv"): + """ + Map (x, y) -> color in (R, G, B). + 1) Normalize x,y to [0,1]. + 2) Combine them into a single scalar c in [0,1]. + 3) Use matplotlib's colormap to convert c -> (R,G,B). + + You can customize step 2, e.g., c = (x + y)/2, or some function of (x, y). + """ + import matplotlib.cm + import matplotlib.colors + + x_norm = x / max(W - 1, 1) + y_norm = y / max(H - 1, 1) + # Simple combination: + c = (x_norm + y_norm) / 2.0 + + cmap = matplotlib.cm.get_cmap(cmap_name) + # cmap(c) -> (r,g,b,a) in [0,1] + rgba = cmap(c) + r, g, b = rgba[0], rgba[1], rgba[2] + return (r, g, b) # in [0,1], RGB order + + +def get_track_colors_by_position(tracks_b, vis_mask_b=None, image_width=None, image_height=None, cmap_name="hsv"): + """ + Given all tracks in one sample (b), compute a (N,3) array of RGB color values + in [0,255]. The color is determined by the (x,y) position in the first + visible frame for each track. + + Args: + tracks_b: Tensor of shape (S, N, 2). (x,y) for each track in each frame. + vis_mask_b: (S, N) boolean mask; if None, assume all are visible. + image_width, image_height: used for normalizing (x, y). + cmap_name: for matplotlib (e.g., 'hsv', 'rainbow', 'jet'). + + Returns: + track_colors: np.ndarray of shape (N, 3), each row is (R,G,B) in [0,255]. + """ + S, N, _ = tracks_b.shape + track_colors = np.zeros((N, 3), dtype=np.uint8) + + if vis_mask_b is None: + # treat all as visible + vis_mask_b = torch.ones(S, N, dtype=torch.bool, device=tracks_b.device) + + for i in range(N): + # Find first visible frame for track i + visible_frames = torch.where(vis_mask_b[:, i])[0] + if len(visible_frames) == 0: + # track is never visible; just assign black or something + track_colors[i] = (0, 0, 0) + continue + + first_s = int(visible_frames[0].item()) + # use that frame's (x,y) + x, y = tracks_b[first_s, i].tolist() + + # map (x,y) -> (R,G,B) in [0,1] + r, g, b = color_from_xy(x, y, W=image_width, H=image_height, cmap_name=cmap_name) + # scale to [0,255] + r, g, b = int(r * 255), int(g * 255), int(b * 255) + track_colors[i] = (r, g, b) + + return track_colors + + +def visualize_tracks_on_images( + images, + tracks, + track_vis_mask=None, + out_dir="track_visuals_concat_by_xy", + image_format="CHW", # "CHW" or "HWC" + normalize_mode="[0,1]", + cmap_name="hsv", # e.g. "hsv", "rainbow", "jet" + frames_per_row=4, # New parameter for grid layout + save_grid=True, # Flag to control whether to save the grid image +): + """ + Visualizes frames in a grid layout with specified frames per row. + Each track's color is determined by its (x,y) position + in the first visible frame (or frame 0 if always visible). + Finally convert the BGR result to RGB before saving. + Also saves each individual frame as a separate PNG file. + + Args: + images: torch.Tensor (S, 3, H, W) if CHW or (S, H, W, 3) if HWC. + tracks: torch.Tensor (S, N, 2), last dim = (x, y). + track_vis_mask: torch.Tensor (S, N) or None. + out_dir: folder to save visualizations. + image_format: "CHW" or "HWC". + normalize_mode: "[0,1]", "[-1,1]", or None for direct raw -> 0..255 + cmap_name: a matplotlib colormap name for color_from_xy. + frames_per_row: number of frames to display in each row of the grid. + save_grid: whether to save all frames in one grid image. + + Returns: + None (saves images in out_dir). + """ + + if len(tracks.shape) == 4: + tracks = tracks.squeeze(0) + images = images.squeeze(0) + if track_vis_mask is not None: + track_vis_mask = track_vis_mask.squeeze(0) + + import matplotlib + + matplotlib.use("Agg") # for non-interactive (optional) + + os.makedirs(out_dir, exist_ok=True) + + S = images.shape[0] + _, N, _ = tracks.shape # (S, N, 2) + + # Move to CPU + images = images.cpu().clone() + tracks = tracks.cpu().clone() + if track_vis_mask is not None: + track_vis_mask = track_vis_mask.cpu().clone() + + # Infer H, W from images shape + if image_format == "CHW": + # e.g. images[s].shape = (3, H, W) + H, W = images.shape[2], images.shape[3] + else: + # e.g. images[s].shape = (H, W, 3) + H, W = images.shape[1], images.shape[2] + + # Pre-compute the color for each track i based on first visible position + track_colors_rgb = get_track_colors_by_position( + tracks, # shape (S, N, 2) + vis_mask_b=track_vis_mask if track_vis_mask is not None else None, + image_width=W, + image_height=H, + cmap_name=cmap_name, + ) + + # We'll accumulate each frame's drawn image in a list + frame_images = [] + + for s in range(S): + # shape => either (3, H, W) or (H, W, 3) + img = images[s] + + # Convert to (H, W, 3) + if image_format == "CHW": + img = img.permute(1, 2, 0) # (H, W, 3) + # else "HWC", do nothing + + img = img.numpy().astype(np.float32) + + # Scale to [0,255] if needed + if normalize_mode == "[0,1]": + img = np.clip(img, 0, 1) * 255.0 + elif normalize_mode == "[-1,1]": + img = (img + 1.0) * 0.5 * 255.0 + img = np.clip(img, 0, 255.0) + # else no normalization + + # Convert to uint8 + img = img.astype(np.uint8) + + # For drawing in OpenCV, convert to BGR + img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + + # Draw each visible track + cur_tracks = tracks[s] # shape (N, 2) + if track_vis_mask is not None: + valid_indices = torch.where(track_vis_mask[s])[0] + else: + valid_indices = range(N) + + cur_tracks_np = cur_tracks.numpy() + for i in valid_indices: + x, y = cur_tracks_np[i] + pt = (int(round(x)), int(round(y))) + + # track_colors_rgb[i] is (R,G,B). For OpenCV circle, we need BGR + R, G, B = track_colors_rgb[i] + color_bgr = (int(B), int(G), int(R)) + cv2.circle(img_bgr, pt, radius=3, color=color_bgr, thickness=-1) + + # Convert back to RGB for consistent final saving: + img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) + + # Save individual frame + frame_path = os.path.join(out_dir, f"frame_{s:04d}.png") + # Convert to BGR for OpenCV imwrite + frame_bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR) + cv2.imwrite(frame_path, frame_bgr) + + frame_images.append(img_rgb) + + # Only create and save the grid image if save_grid is True + if save_grid: + # Calculate grid dimensions + num_rows = (S + frames_per_row - 1) // frames_per_row # Ceiling division + + # Create a grid of images + grid_img = None + for row in range(num_rows): + start_idx = row * frames_per_row + end_idx = min(start_idx + frames_per_row, S) + + # Concatenate this row horizontally + row_img = np.concatenate(frame_images[start_idx:end_idx], axis=1) + + # If this row has fewer than frames_per_row images, pad with black + if end_idx - start_idx < frames_per_row: + padding_width = (frames_per_row - (end_idx - start_idx)) * W + padding = np.zeros((H, padding_width, 3), dtype=np.uint8) + row_img = np.concatenate([row_img, padding], axis=1) + + # Add this row to the grid + if grid_img is None: + grid_img = row_img + else: + grid_img = np.concatenate([grid_img, row_img], axis=0) + + out_path = os.path.join(out_dir, "tracks_grid.png") + # Convert back to BGR for OpenCV imwrite + grid_img_bgr = cv2.cvtColor(grid_img, cv2.COLOR_RGB2BGR) + cv2.imwrite(out_path, grid_img_bgr) + print(f"[INFO] Saved color-by-XY track visualization grid -> {out_path}") + + print(f"[INFO] Saved {S} individual frames to {out_dir}/frame_*.png") diff --git a/loomnet/models/extras/geometry_loss/vggt/vggt_to_colmap.py b/loomnet/models/extras/geometry_loss/vggt/vggt_to_colmap.py new file mode 100644 index 0000000000000000000000000000000000000000..c28838035d732904260f5a1f4f97a59cdf793d85 --- /dev/null +++ b/loomnet/models/extras/geometry_loss/vggt/vggt_to_colmap.py @@ -0,0 +1,595 @@ +import os +import argparse +import numpy as np +import torch +import glob +import struct +from scipy.spatial.transform import Rotation +import sys +from PIL import Image +import cv2 +import requests +import tempfile + +sys.path.append("vggt/") + +from vggt.models.vggt import VGGT +from vggt.utils.load_fn import load_and_preprocess_images +from vggt.utils.pose_enc import pose_encoding_to_extri_intri +from vggt.utils.geometry import unproject_depth_map_to_point_map + +def load_model(device=None): + """Load and initialize the VGGT model.""" + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + print(f"Using device: {device}") + + model = VGGT.from_pretrained("facebook/VGGT-1B") + + # model = VGGT() + # _URL = "https://huggingface.co/facebook/VGGT-1B/resolve/main/model.pt" + # model.load_state_dict(torch.hub.load_state_dict_from_url(_URL)) + + model.eval() + model = model.to(device) + return model, device + +def process_images(image_dir, model, device): + """Process images with VGGT and return predictions.""" + image_names = glob.glob(os.path.join(image_dir, "*")) + image_names = sorted([f for f in image_names if f.lower().endswith(('.png', '.jpg', '.jpeg'))]) + print(f"Found {len(image_names)} images") + + if len(image_names) == 0: + raise ValueError(f"No images found in {image_dir}") + + original_images = [] + for img_path in image_names: + img = Image.open(img_path).convert('RGB') + original_images.append(np.array(img)) + + images = load_and_preprocess_images(image_names).to(device) + print(f"Preprocessed images shape: {images.shape}") + + print("Running inference...") + dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] >= 8 else torch.float16 + + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=dtype): + predictions = model(images) + + print("Converting pose encoding to camera parameters...") + extrinsic, intrinsic = pose_encoding_to_extri_intri(predictions["pose_enc"], images.shape[-2:]) + predictions["extrinsic"] = extrinsic + predictions["intrinsic"] = intrinsic + + for key in predictions.keys(): + if isinstance(predictions[key], torch.Tensor): + predictions[key] = predictions[key].cpu().numpy().squeeze(0) # remove batch dimension + + print("Computing 3D points from depth maps...") + depth_map = predictions["depth"] # (S, H, W, 1) + world_points = unproject_depth_map_to_point_map(depth_map, predictions["extrinsic"], predictions["intrinsic"]) + predictions["world_points_from_depth"] = world_points + + predictions["original_images"] = original_images + + S, H, W = world_points.shape[:3] + normalized_images = np.zeros((S, H, W, 3), dtype=np.float32) + + for i, img in enumerate(original_images): + resized_img = cv2.resize(img, (W, H)) + normalized_images[i] = resized_img / 255.0 + + predictions["images"] = normalized_images + + return predictions, image_names + +def extrinsic_to_colmap_format(extrinsics): + """Convert extrinsic matrices to COLMAP format (quaternion + translation).""" + num_cameras = extrinsics.shape[0] + quaternions = [] + translations = [] + + for i in range(num_cameras): + # VGGT's extrinsic is camera-to-world (R|t) format + R = extrinsics[i, :3, :3] + t = extrinsics[i, :3, 3] + + # Convert rotation matrix to quaternion + # COLMAP quaternion format is [qw, qx, qy, qz] + rot = Rotation.from_matrix(R) + quat = rot.as_quat() # scipy returns [x, y, z, w] + quat = np.array([quat[3], quat[0], quat[1], quat[2]]) # Convert to [w, x, y, z] + + quaternions.append(quat) + translations.append(t) + + return np.array(quaternions), np.array(translations) + +def download_file_from_url(url, filename): + """Downloads a file from a URL, handling redirects.""" + try: + response = requests.get(url, allow_redirects=False) + response.raise_for_status() + + if response.status_code == 302: + redirect_url = response.headers["Location"] + response = requests.get(redirect_url, stream=True) + response.raise_for_status() + else: + response = requests.get(url, stream=True) + response.raise_for_status() + + with open(filename, "wb") as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + print(f"Downloaded {filename} successfully.") + return True + + except requests.exceptions.RequestException as e: + print(f"Error downloading file: {e}") + return False + +def segment_sky(image_path, onnx_session, mask_filename=None): + """ + Segments sky from an image using an ONNX model. + """ + image = cv2.imread(image_path) + + result_map = run_skyseg(onnx_session, [320, 320], image) + result_map_original = cv2.resize(result_map, (image.shape[1], image.shape[0])) + + # Fix: Invert the mask so that 255 = non-sky, 0 = sky + # The model outputs low values for sky, high values for non-sky + output_mask = np.zeros_like(result_map_original) + output_mask[result_map_original < 32] = 255 # Use threshold of 32 + + if mask_filename is not None: + os.makedirs(os.path.dirname(mask_filename), exist_ok=True) + cv2.imwrite(mask_filename, output_mask) + + return output_mask + +def run_skyseg(onnx_session, input_size, image): + """ + Runs sky segmentation inference using ONNX model. + """ + import copy + + temp_image = copy.deepcopy(image) + resize_image = cv2.resize(temp_image, dsize=(input_size[0], input_size[1])) + x = cv2.cvtColor(resize_image, cv2.COLOR_BGR2RGB) + x = np.array(x, dtype=np.float32) + mean = [0.485, 0.456, 0.406] + std = [0.229, 0.224, 0.225] + x = (x / 255 - mean) / std + x = x.transpose(2, 0, 1) + x = x.reshape(-1, 3, input_size[0], input_size[1]).astype("float32") + + input_name = onnx_session.get_inputs()[0].name + output_name = onnx_session.get_outputs()[0].name + onnx_result = onnx_session.run([output_name], {input_name: x}) + + onnx_result = np.array(onnx_result).squeeze() + min_value = np.min(onnx_result) + max_value = np.max(onnx_result) + onnx_result = (onnx_result - min_value) / (max_value - min_value) + onnx_result *= 255 + onnx_result = onnx_result.astype("uint8") + + return onnx_result + +def filter_and_prepare_points(predictions, conf_threshold, mask_sky=False, mask_black_bg=False, + mask_white_bg=False, stride=1, prediction_mode="Depthmap and Camera Branch"): + """ + Filter points based on confidence and prepare for COLMAP format. + Implementation matches the conventions in the original VGGT code. + """ + + if "Pointmap" in prediction_mode: + print("Using Pointmap Branch") + if "world_points" in predictions: + pred_world_points = predictions["world_points"] + pred_world_points_conf = predictions.get("world_points_conf", np.ones_like(pred_world_points[..., 0])) + else: + print("Warning: world_points not found in predictions, falling back to depth-based points") + pred_world_points = predictions["world_points_from_depth"] + pred_world_points_conf = predictions.get("depth_conf", np.ones_like(pred_world_points[..., 0])) + else: + print("Using Depthmap and Camera Branch") + pred_world_points = predictions["world_points_from_depth"] + pred_world_points_conf = predictions.get("depth_conf", np.ones_like(pred_world_points[..., 0])) + + colors_rgb = predictions["images"] + + S, H, W = pred_world_points.shape[:3] + if colors_rgb.shape[:3] != (S, H, W): + print(f"Reshaping colors_rgb from {colors_rgb.shape} to match {(S, H, W, 3)}") + reshaped_colors = np.zeros((S, H, W, 3), dtype=np.float32) + for i in range(S): + if i < len(colors_rgb): + reshaped_colors[i] = cv2.resize(colors_rgb[i], (W, H)) + colors_rgb = reshaped_colors + + colors_rgb = (colors_rgb * 255).astype(np.uint8) + + if mask_sky: + print("Applying sky segmentation mask") + try: + import onnxruntime + + with tempfile.TemporaryDirectory() as temp_dir: + print(f"Created temporary directory for sky segmentation: {temp_dir}") + temp_images_dir = os.path.join(temp_dir, "images") + sky_masks_dir = os.path.join(temp_dir, "sky_masks") + os.makedirs(temp_images_dir, exist_ok=True) + os.makedirs(sky_masks_dir, exist_ok=True) + + image_list = [] + for i, img in enumerate(colors_rgb): + img_path = os.path.join(temp_images_dir, f"image_{i:04d}.png") + image_list.append(img_path) + cv2.imwrite(img_path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) + + + skyseg_path = os.path.join(temp_dir, "skyseg.onnx") + if not os.path.exists("skyseg.onnx"): + print("Downloading skyseg.onnx...") + download_success = download_file_from_url( + "https://huggingface.co/JianyuanWang/skyseg/resolve/main/skyseg.onnx", + skyseg_path + ) + if not download_success: + print("Failed to download skyseg model, skipping sky filtering") + mask_sky = False + else: + + import shutil + shutil.copy("skyseg.onnx", skyseg_path) + + if mask_sky: + skyseg_session = onnxruntime.InferenceSession(skyseg_path) + sky_mask_list = [] + + for img_path in image_list: + mask_path = os.path.join(sky_masks_dir, os.path.basename(img_path)) + sky_mask = segment_sky(img_path, skyseg_session, mask_path) + + if sky_mask.shape[0] != H or sky_mask.shape[1] != W: + sky_mask = cv2.resize(sky_mask, (W, H)) + + sky_mask_list.append(sky_mask) + + sky_mask_array = np.array(sky_mask_list) + + sky_mask_binary = (sky_mask_array > 0.1).astype(np.float32) + pred_world_points_conf = pred_world_points_conf * sky_mask_binary + print(f"Applied sky mask, shape: {sky_mask_binary.shape}") + + except (ImportError, Exception) as e: + print(f"Error in sky segmentation: {e}") + mask_sky = False + + vertices_3d = pred_world_points.reshape(-1, 3) + conf = pred_world_points_conf.reshape(-1) + colors_rgb_flat = colors_rgb.reshape(-1, 3) + + + + if len(conf) != len(colors_rgb_flat): + print(f"WARNING: Shape mismatch between confidence ({len(conf)}) and colors ({len(colors_rgb_flat)})") + min_size = min(len(conf), len(colors_rgb_flat)) + conf = conf[:min_size] + vertices_3d = vertices_3d[:min_size] + colors_rgb_flat = colors_rgb_flat[:min_size] + + if conf_threshold == 0.0: + conf_thres_value = 0.0 + else: + conf_thres_value = np.percentile(conf, conf_threshold) + + print(f"Using confidence threshold: {conf_threshold}% (value: {conf_thres_value:.4f})") + conf_mask = (conf >= conf_thres_value) & (conf > 1e-5) + + if mask_black_bg: + print("Filtering black background") + black_bg_mask = colors_rgb_flat.sum(axis=1) >= 16 + conf_mask = conf_mask & black_bg_mask + + if mask_white_bg: + print("Filtering white background") + white_bg_mask = ~((colors_rgb_flat[:, 0] > 240) & (colors_rgb_flat[:, 1] > 240) & (colors_rgb_flat[:, 2] > 240)) + conf_mask = conf_mask & white_bg_mask + + filtered_vertices = vertices_3d[conf_mask] + filtered_colors = colors_rgb_flat[conf_mask] + + if len(filtered_vertices) == 0: + print("Warning: No points remaining after filtering. Using default point.") + filtered_vertices = np.array([[0, 0, 0]]) + filtered_colors = np.array([[200, 200, 200]]) + + print(f"Filtered to {len(filtered_vertices)} points") + + points3D = [] + point_indices = {} + image_points2D = [[] for _ in range(len(pred_world_points))] + + print(f"Preparing points for COLMAP format with stride {stride}...") + + total_points = 0 + for img_idx in range(S): + for y in range(0, H, stride): + for x in range(0, W, stride): + flat_idx = img_idx * H * W + y * W + x + + if flat_idx >= len(conf): + continue + + if conf[flat_idx] < conf_thres_value or conf[flat_idx] <= 1e-5: + continue + + if mask_black_bg and colors_rgb_flat[flat_idx].sum() < 16: + continue + + if mask_white_bg and all(colors_rgb_flat[flat_idx] > 240): + continue + + point3D = vertices_3d[flat_idx] + rgb = colors_rgb_flat[flat_idx] + + if not np.all(np.isfinite(point3D)): + continue + + point_hash = hash_point(point3D, scale=100) + + if point_hash not in point_indices: + point_idx = len(points3D) + point_indices[point_hash] = point_idx + + point_entry = { + "id": point_idx, + "xyz": point3D, + "rgb": rgb, + "error": 1.0, + "track": [(img_idx, len(image_points2D[img_idx]))] + } + points3D.append(point_entry) + total_points += 1 + else: + point_idx = point_indices[point_hash] + points3D[point_idx]["track"].append((img_idx, len(image_points2D[img_idx]))) + + image_points2D[img_idx].append((x, y, point_indices[point_hash])) + + print(f"Prepared {len(points3D)} 3D points with {sum(len(pts) for pts in image_points2D)} observations for COLMAP") + return points3D, image_points2D + +def hash_point(point, scale=100): + """Create a hash for a 3D point by quantizing coordinates.""" + quantized = tuple(np.round(point * scale).astype(int)) + return hash(quantized) + +def write_colmap_cameras_txt(file_path, intrinsics, image_width, image_height): + """Write camera intrinsics to COLMAP cameras.txt format.""" + with open(file_path, 'w') as f: + f.write("# Camera list with one line of data per camera:\n") + f.write("# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\n") + f.write(f"# Number of cameras: {len(intrinsics)}\n") + + for i, intrinsic in enumerate(intrinsics): + camera_id = i + 1 # COLMAP uses 1-indexed camera IDs + model = "PINHOLE" + + fx = intrinsic[0, 0] + fy = intrinsic[1, 1] + cx = intrinsic[0, 2] + cy = intrinsic[1, 2] + + f.write(f"{camera_id} {model} {image_width} {image_height} {fx} {fy} {cx} {cy}\n") + +def write_colmap_images_txt(file_path, quaternions, translations, image_points2D, image_names): + """Write camera poses and keypoints to COLMAP images.txt format.""" + with open(file_path, 'w') as f: + f.write("# Image list with two lines of data per image:\n") + f.write("# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\n") + f.write("# POINTS2D[] as (X, Y, POINT3D_ID)\n") + + num_points = sum(len(points) for points in image_points2D) + avg_points = num_points / len(image_points2D) if image_points2D else 0 + f.write(f"# Number of images: {len(quaternions)}, mean observations per image: {avg_points:.1f}\n") + + for i in range(len(quaternions)): + image_id = i + 1 + camera_id = i + 1 + + qw, qx, qy, qz = quaternions[i] + tx, ty, tz = translations[i] + + f.write(f"{image_id} {qw} {qx} {qy} {qz} {tx} {ty} {tz} {camera_id} {os.path.basename(image_names[i])}\n") + + points_line = " ".join([f"{x} {y} {point3d_id+1}" for x, y, point3d_id in image_points2D[i]]) + f.write(f"{points_line}\n") + +def write_colmap_points3D_txt(file_path, points3D): + """Write 3D points and tracks to COLMAP points3D.txt format.""" + with open(file_path, 'w') as f: + f.write("# 3D point list with one line of data per point:\n") + f.write("# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n") + + avg_track_length = sum(len(point["track"]) for point in points3D) / len(points3D) if points3D else 0 + f.write(f"# Number of points: {len(points3D)}, mean track length: {avg_track_length:.4f}\n") + + for point in points3D: + point_id = point["id"] + 1 + x, y, z = point["xyz"] + r, g, b = point["rgb"] + error = point["error"] + + track = " ".join([f"{img_id+1} {point2d_idx}" for img_id, point2d_idx in point["track"]]) + + f.write(f"{point_id} {x} {y} {z} {int(r)} {int(g)} {int(b)} {error} {track}\n") + +def write_colmap_cameras_bin(file_path, intrinsics, image_width, image_height): + """Write camera intrinsics to COLMAP cameras.bin format.""" + with open(file_path, 'wb') as fid: + # Write number of cameras (uint64) + fid.write(struct.pack(' trimesh.Scene: + """ + Converts VGGT predictions to a 3D scene represented as a GLB file. + + Args: + predictions (dict): Dictionary containing model predictions with keys: + - world_points: 3D point coordinates (S, H, W, 3) + - world_points_conf: Confidence scores (S, H, W) + - images: Input images (S, H, W, 3) + - extrinsic: Camera extrinsic matrices (S, 3, 4) + conf_thres (float): Percentage of low-confidence points to filter out (default: 50.0) + filter_by_frames (str): Frame filter specification (default: "all") + mask_black_bg (bool): Mask out black background pixels (default: False) + mask_white_bg (bool): Mask out white background pixels (default: False) + show_cam (bool): Include camera visualization (default: True) + mask_sky (bool): Apply sky segmentation mask (default: False) + target_dir (str): Output directory for intermediate files (default: None) + prediction_mode (str): Prediction mode selector (default: "Predicted Pointmap") + + Returns: + trimesh.Scene: Processed 3D scene containing point cloud and cameras + + Raises: + ValueError: If input predictions structure is invalid + """ + if not isinstance(predictions, dict): + raise ValueError("predictions must be a dictionary") + + if conf_thres is None: + conf_thres = 10.0 + + print("Building GLB scene") + selected_frame_idx = None + if filter_by_frames != "all" and filter_by_frames != "All": + try: + # Extract the index part before the colon + selected_frame_idx = int(filter_by_frames.split(":")[0]) + except (ValueError, IndexError): + pass + + if "Pointmap" in prediction_mode: + print("Using Pointmap Branch") + if "world_points" in predictions: + pred_world_points = predictions["world_points"] # No batch dimension to remove + pred_world_points_conf = predictions.get("world_points_conf", np.ones_like(pred_world_points[..., 0])) + else: + print("Warning: world_points not found in predictions, falling back to depth-based points") + pred_world_points = predictions["world_points_from_depth"] + pred_world_points_conf = predictions.get("depth_conf", np.ones_like(pred_world_points[..., 0])) + else: + print("Using Depthmap and Camera Branch") + pred_world_points = predictions["world_points_from_depth"] + pred_world_points_conf = predictions.get("depth_conf", np.ones_like(pred_world_points[..., 0])) + + # Get images from predictions + images = predictions["images"] + # Use extrinsic matrices instead of pred_extrinsic_list + camera_matrices = predictions["extrinsic"] + + if mask_sky: + if target_dir is not None: + import onnxruntime + + skyseg_session = None + target_dir_images = target_dir + "/images" + image_list = sorted(os.listdir(target_dir_images)) + sky_mask_list = [] + + # Get the shape of pred_world_points_conf to match + S, H, W = ( + pred_world_points_conf.shape + if hasattr(pred_world_points_conf, "shape") + else (len(images), images.shape[1], images.shape[2]) + ) + + # Download skyseg.onnx if it doesn't exist + if not os.path.exists("skyseg.onnx"): + print("Downloading skyseg.onnx...") + download_file_from_url( + "https://huggingface.co/JianyuanWang/skyseg/resolve/main/skyseg.onnx", "skyseg.onnx" + ) + + for i, image_name in enumerate(image_list): + image_filepath = os.path.join(target_dir_images, image_name) + mask_filepath = os.path.join(target_dir, "sky_masks", image_name) + + # Check if mask already exists + if os.path.exists(mask_filepath): + # Load existing mask + sky_mask = cv2.imread(mask_filepath, cv2.IMREAD_GRAYSCALE) + else: + # Generate new mask + if skyseg_session is None: + skyseg_session = onnxruntime.InferenceSession("skyseg.onnx") + sky_mask = segment_sky(image_filepath, skyseg_session, mask_filepath) + + # Resize mask to match H×W if needed + if sky_mask.shape[0] != H or sky_mask.shape[1] != W: + sky_mask = cv2.resize(sky_mask, (W, H)) + + sky_mask_list.append(sky_mask) + + # Convert list to numpy array with shape S×H×W + sky_mask_array = np.array(sky_mask_list) + + # Apply sky mask to confidence scores + sky_mask_binary = (sky_mask_array > 0.1).astype(np.float32) + pred_world_points_conf = pred_world_points_conf * sky_mask_binary + + if selected_frame_idx is not None: + pred_world_points = pred_world_points[selected_frame_idx][None] + pred_world_points_conf = pred_world_points_conf[selected_frame_idx][None] + images = images[selected_frame_idx][None] + camera_matrices = camera_matrices[selected_frame_idx][None] + + vertices_3d = pred_world_points.reshape(-1, 3) + # Handle different image formats - check if images need transposing + if images.ndim == 4 and images.shape[1] == 3: # NCHW format + colors_rgb = np.transpose(images, (0, 2, 3, 1)) + else: # Assume already in NHWC format + colors_rgb = images + colors_rgb = (colors_rgb.reshape(-1, 3) * 255).astype(np.uint8) + + conf = pred_world_points_conf.reshape(-1) + # Convert percentage threshold to actual confidence value + if conf_thres == 0.0: + conf_threshold = 0.0 + else: + conf_threshold = np.percentile(conf, conf_thres) + + conf_mask = (conf >= conf_threshold) & (conf > 1e-5) + + if mask_black_bg: + black_bg_mask = colors_rgb.sum(axis=1) >= 16 + conf_mask = conf_mask & black_bg_mask + + if mask_white_bg: + # Filter out white background pixels (RGB values close to white) + # Consider pixels white if all RGB values are above 240 + white_bg_mask = ~((colors_rgb[:, 0] > 240) & (colors_rgb[:, 1] > 240) & (colors_rgb[:, 2] > 240)) + conf_mask = conf_mask & white_bg_mask + + vertices_3d = vertices_3d[conf_mask] + colors_rgb = colors_rgb[conf_mask] + + if vertices_3d is None or np.asarray(vertices_3d).size == 0: + vertices_3d = np.array([[1, 0, 0]]) + colors_rgb = np.array([[255, 255, 255]]) + scene_scale = 1 + else: + # Calculate the 5th and 95th percentiles along each axis + lower_percentile = np.percentile(vertices_3d, 5, axis=0) + upper_percentile = np.percentile(vertices_3d, 95, axis=0) + + # Calculate the diagonal length of the percentile bounding box + scene_scale = np.linalg.norm(upper_percentile - lower_percentile) + + colormap = matplotlib.colormaps.get_cmap("gist_rainbow") + + # Initialize a 3D scene + scene_3d = trimesh.Scene() + + # Add point cloud data to the scene + point_cloud_data = trimesh.PointCloud(vertices=vertices_3d, colors=colors_rgb) + + scene_3d.add_geometry(point_cloud_data) + + # Prepare 4x4 matrices for camera extrinsics + num_cameras = len(camera_matrices) + extrinsics_matrices = np.zeros((num_cameras, 4, 4)) + extrinsics_matrices[:, :3, :4] = camera_matrices + extrinsics_matrices[:, 3, 3] = 1 + + if show_cam: + # Add camera models to the scene + for i in range(num_cameras): + world_to_camera = extrinsics_matrices[i] + camera_to_world = np.linalg.inv(world_to_camera) + rgba_color = colormap(i / num_cameras) + current_color = tuple(int(255 * x) for x in rgba_color[:3]) + + integrate_camera_into_scene(scene_3d, camera_to_world, current_color, scene_scale) + + # Align scene to the observation of the first camera + scene_3d = apply_scene_alignment(scene_3d, extrinsics_matrices) + + print("GLB Scene built") + return scene_3d + + +def integrate_camera_into_scene( + scene: trimesh.Scene, + transform: np.ndarray, + face_colors: tuple, + scene_scale: float, +): + """ + Integrates a fake camera mesh into the 3D scene. + + Args: + scene (trimesh.Scene): The 3D scene to add the camera model. + transform (np.ndarray): Transformation matrix for camera positioning. + face_colors (tuple): Color of the camera face. + scene_scale (float): Scale of the scene. + """ + + cam_width = scene_scale * 0.05 + cam_height = scene_scale * 0.1 + + # Create cone shape for camera + rot_45_degree = np.eye(4) + rot_45_degree[:3, :3] = Rotation.from_euler("z", 45, degrees=True).as_matrix() + rot_45_degree[2, 3] = -cam_height + + opengl_transform = get_opengl_conversion_matrix() + # Combine transformations + complete_transform = transform @ opengl_transform @ rot_45_degree + camera_cone_shape = trimesh.creation.cone(cam_width, cam_height, sections=4) + + # Generate mesh for the camera + slight_rotation = np.eye(4) + slight_rotation[:3, :3] = Rotation.from_euler("z", 2, degrees=True).as_matrix() + + vertices_combined = np.concatenate( + [ + camera_cone_shape.vertices, + 0.95 * camera_cone_shape.vertices, + transform_points(slight_rotation, camera_cone_shape.vertices), + ] + ) + vertices_transformed = transform_points(complete_transform, vertices_combined) + + mesh_faces = compute_camera_faces(camera_cone_shape) + + # Add the camera mesh to the scene + camera_mesh = trimesh.Trimesh(vertices=vertices_transformed, faces=mesh_faces) + camera_mesh.visual.face_colors[:, :3] = face_colors + scene.add_geometry(camera_mesh) + + +def apply_scene_alignment(scene_3d: trimesh.Scene, extrinsics_matrices: np.ndarray) -> trimesh.Scene: + """ + Aligns the 3D scene based on the extrinsics of the first camera. + + Args: + scene_3d (trimesh.Scene): The 3D scene to be aligned. + extrinsics_matrices (np.ndarray): Camera extrinsic matrices. + + Returns: + trimesh.Scene: Aligned 3D scene. + """ + # Set transformations for scene alignment + opengl_conversion_matrix = get_opengl_conversion_matrix() + + # Rotation matrix for alignment (180 degrees around the y-axis) + align_rotation = np.eye(4) + align_rotation[:3, :3] = Rotation.from_euler("y", 180, degrees=True).as_matrix() + + # Apply transformation + initial_transformation = np.linalg.inv(extrinsics_matrices[0]) @ opengl_conversion_matrix @ align_rotation + scene_3d.apply_transform(initial_transformation) + return scene_3d + + +def get_opengl_conversion_matrix() -> np.ndarray: + """ + Constructs and returns the OpenGL conversion matrix. + + Returns: + numpy.ndarray: A 4x4 OpenGL conversion matrix. + """ + # Create an identity matrix + matrix = np.identity(4) + + # Flip the y and z axes + matrix[1, 1] = -1 + matrix[2, 2] = -1 + + return matrix + + +def transform_points(transformation: np.ndarray, points: np.ndarray, dim: int = None) -> np.ndarray: + """ + Applies a 4x4 transformation to a set of points. + + Args: + transformation (np.ndarray): Transformation matrix. + points (np.ndarray): Points to be transformed. + dim (int, optional): Dimension for reshaping the result. + + Returns: + np.ndarray: Transformed points. + """ + points = np.asarray(points) + initial_shape = points.shape[:-1] + dim = dim or points.shape[-1] + + # Apply transformation + transformation = transformation.swapaxes(-1, -2) # Transpose the transformation matrix + points = points @ transformation[..., :-1, :] + transformation[..., -1:, :] + + # Reshape the result + result = points[..., :dim].reshape(*initial_shape, dim) + return result + + +def compute_camera_faces(cone_shape: trimesh.Trimesh) -> np.ndarray: + """ + Computes the faces for the camera mesh. + + Args: + cone_shape (trimesh.Trimesh): The shape of the camera cone. + + Returns: + np.ndarray: Array of faces for the camera mesh. + """ + # Create pseudo cameras + faces_list = [] + num_vertices_cone = len(cone_shape.vertices) + + for face in cone_shape.faces: + if 0 in face: + continue + v1, v2, v3 = face + v1_offset, v2_offset, v3_offset = face + num_vertices_cone + v1_offset_2, v2_offset_2, v3_offset_2 = face + 2 * num_vertices_cone + + faces_list.extend( + [ + (v1, v2, v2_offset), + (v1, v1_offset, v3), + (v3_offset, v2, v3), + (v1, v2, v2_offset_2), + (v1, v1_offset_2, v3), + (v3_offset_2, v2, v3), + ] + ) + + faces_list += [(v3, v2, v1) for v1, v2, v3 in faces_list] + return np.array(faces_list) + + +def segment_sky(image_path, onnx_session, mask_filename=None): + """ + Segments sky from an image using an ONNX model. + Thanks for the great model provided by https://github.com/xiongzhu666/Sky-Segmentation-and-Post-processing + + Args: + image_path: Path to input image + onnx_session: ONNX runtime session with loaded model + mask_filename: Path to save the output mask + + Returns: + np.ndarray: Binary mask where 255 indicates non-sky regions + """ + + assert mask_filename is not None + image = cv2.imread(image_path) + + result_map = run_skyseg(onnx_session, [320, 320], image) + # resize the result_map to the original image size + result_map_original = cv2.resize(result_map, (image.shape[1], image.shape[0])) + + # Fix: Invert the mask so that 255 = non-sky, 0 = sky + # The model outputs low values for sky, high values for non-sky + output_mask = np.zeros_like(result_map_original) + output_mask[result_map_original < 32] = 255 # Use threshold of 32 + + os.makedirs(os.path.dirname(mask_filename), exist_ok=True) + cv2.imwrite(mask_filename, output_mask) + return output_mask + + +def run_skyseg(onnx_session, input_size, image): + """ + Runs sky segmentation inference using ONNX model. + + Args: + onnx_session: ONNX runtime session + input_size: Target size for model input (width, height) + image: Input image in BGR format + + Returns: + np.ndarray: Segmentation mask + """ + + # Pre process:Resize, BGR->RGB, Transpose, PyTorch standardization, float32 cast + temp_image = copy.deepcopy(image) + resize_image = cv2.resize(temp_image, dsize=(input_size[0], input_size[1])) + x = cv2.cvtColor(resize_image, cv2.COLOR_BGR2RGB) + x = np.array(x, dtype=np.float32) + mean = [0.485, 0.456, 0.406] + std = [0.229, 0.224, 0.225] + x = (x / 255 - mean) / std + x = x.transpose(2, 0, 1) + x = x.reshape(-1, 3, input_size[0], input_size[1]).astype("float32") + + # Inference + input_name = onnx_session.get_inputs()[0].name + output_name = onnx_session.get_outputs()[0].name + onnx_result = onnx_session.run([output_name], {input_name: x}) + + # Post process + onnx_result = np.array(onnx_result).squeeze() + min_value = np.min(onnx_result) + max_value = np.max(onnx_result) + onnx_result = (onnx_result - min_value) / (max_value - min_value) + onnx_result *= 255 + onnx_result = onnx_result.astype("uint8") + + return onnx_result + + +def download_file_from_url(url, filename): + """Downloads a file from a Hugging Face model repo, handling redirects.""" + try: + # Get the redirect URL + response = requests.get(url, allow_redirects=False) + response.raise_for_status() # Raise HTTPError for bad requests (4xx or 5xx) + + if response.status_code == 302: # Expecting a redirect + redirect_url = response.headers["Location"] + response = requests.get(redirect_url, stream=True) + response.raise_for_status() + else: + print(f"Unexpected status code: {response.status_code}") + return + + with open(filename, "wb") as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + print(f"Downloaded {filename} successfully.") + + except requests.exceptions.RequestException as e: + print(f"Error downloading file: {e}") diff --git a/loomnet/models/mv_model_1_to_infinity.py b/loomnet/models/mv_model_1_to_infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..0397f0cb2c24fc15b767bcc4f8d4f2e9fa634f95 --- /dev/null +++ b/loomnet/models/mv_model_1_to_infinity.py @@ -0,0 +1,292 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union + +import torch +import torch.nn as nn +from diffusers import UNet2DConditionModel +from einops import rearrange + +from loomnet.utils.project import HarmonicEmbedding, process_cameras + + +@dataclass +class RenderConfig: + ray_start: float = 0.5 + ray_end: float = 2.8 + resolution: int = 32 + n_samples: int = 8 + disparity_space_sampling: bool = False + box_warp: float = 1.0 + + +class MVModel(nn.Module): + def __init__( + self, + cp_block_model: nn.Module, + unet: Optional[UNet2DConditionModel] = None, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: str = "fp16_ema", + train_unet: bool = False, + insert_stages: List[int] = ["mid", "up"], + insert_up_layers: List[int] = [0, 1, 2, 3], + use_residual: bool = False, + plane_resolution: int = 32, + plane_channel_dim: int = 512 + ): + super().__init__() + + self.trainable_parameters = [] + + # prepare unet + self.unet = unet + if unet is None: + self.unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", variant=variant + ) + + if train_unet: + self.trainable_parameters += [(self.unet.parameters(), 0.01)] + else: + self.unet.requires_grad_(False) + + self.insert_stages = insert_stages + self.insert_up_layers = insert_up_layers + self.use_residual = use_residual + + # camera embedding + self.harmonic_embedding = HarmonicEmbedding() + embed_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + self.cp_blocks_encoder = nn.ModuleList() + self.cp_blocks_mid = nn.ModuleList() + self.cp_blocks_decoder = nn.ModuleList() + + if "down" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [32, 16, 8, 4] + + for i in range(len(self.unet.down_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_encoder.append( + cp_block_model( + dim=self.unet.down_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + if "mid" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolution = 4 + + self.cp_blocks_mid.append( + cp_block_model( + self.unet.mid_block.resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolution + ) + ) + if "up" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [4,8,16,32] + + for i in range(len(self.unet.up_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_decoder.append( + cp_block_model( + self.unet.up_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + + + ''' + TRIPLANE TOKENS + ''' + self.pos_embed = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + + + + self.trainable_parameters += [ + ( + list(self.cp_blocks_mid.parameters()) + + list(self.cp_blocks_decoder.parameters()) + + list(self.cp_blocks_encoder.parameters()), + 1.0, + ), + ( + [self.pos_embed], + 1.0 + ) + ] + + def set_use_memory_efficient_attention_xformers( + self, valid: bool, attention_op=None + ) -> None: + def fn_recursive_set_mem_eff(module: torch.nn.Module): + if hasattr(module, "set_use_memory_efficient_attention_xformers"): + module.set_use_memory_efficient_attention_xformers(valid, attention_op) + + for child in module.children(): + fn_recursive_set_mem_eff(child) + + for module in self.children(): + if isinstance(module, torch.nn.Module): + fn_recursive_set_mem_eff(module) + + def forward(self, latents, timestep, prompt_embd, meta): + cameras = meta["cameras"] + k_near_indices = meta["k_near_indices"] + b, m, c, h, w = latents.shape + + # [0, 1] -> [-1, 1] + # bs*m, 4, 64, 64 + hidden_states = rearrange(latents, "b m c h w -> (b m) c h w") + prompt_embd = rearrange(prompt_embd, "b m l c -> (b m) l c") + + # 1. process timesteps + timestep = timestep.reshape(-1) + t_emb = self.unet.time_proj(timestep) # (bs, 320) + emb = self.unet.time_embedding(t_emb) # (bs, 1280) + + hidden_states = self.unet.conv_in(hidden_states) # bs*m, 320, 64, 64 + + list_pixel_distances, list_feature_similarity = [], [] + + pos_embed = self.pos_embed + + # unet + # a. downsample + current_downblock_id = 0 + down_block_res_samples = (hidden_states,) + for i, downsample_block in enumerate(self.unet.down_blocks): + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + for resnet, attn in zip( + downsample_block.resnets, downsample_block.attentions + ): + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + down_block_res_samples += (hidden_states,) + else: + for resnet in downsample_block.resnets: + hidden_states = resnet(hidden_states, emb) + down_block_res_samples += (hidden_states,) + + if len(self.cp_blocks_encoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed = self.cp_blocks_encoder[current_downblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + current_downblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if downsample_block.downsamplers is not None: + for downsample in downsample_block.downsamplers: + hidden_states = downsample(hidden_states) + down_block_res_samples += (hidden_states,) + + # b. mid + hidden_states = self.unet.mid_block.resnets[0](hidden_states, emb) + + if len(self.cp_blocks_mid) > 0: + + global_latent_views, pos_embed = self.cp_blocks_mid[0]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + + for attn, resnet in zip( + self.unet.mid_block.attentions, self.unet.mid_block.resnets[1:] + ): + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + hidden_states = resnet(hidden_states, emb) + + h, w = hidden_states.shape[-2:] + + # c. upsample + current_upblock_id = 0 + for i, upsample_block in enumerate(self.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + for resnet, attn in zip( + upsample_block.resnets, upsample_block.attentions + ): + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + else: + for resnet in upsample_block.resnets: + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + + if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed = self.cp_blocks_decoder[current_upblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + current_upblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if upsample_block.upsamplers is not None: + for upsample in upsample_block.upsamplers: + hidden_states = upsample(hidden_states) + + + # 4.post-process + sample = self.unet.conv_norm_out(hidden_states) + sample = self.unet.conv_act(sample) + sample = self.unet.conv_out(sample) + sample = rearrange(sample, "(b m) c h w -> b m c h w", m=m) + return sample, pos_embed diff --git a/loomnet/models/mv_model_triplane.py b/loomnet/models/mv_model_triplane.py new file mode 100644 index 0000000000000000000000000000000000000000..a772aa76c1e50d1b059e70d7179340cb3af58a32 --- /dev/null +++ b/loomnet/models/mv_model_triplane.py @@ -0,0 +1,370 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union +from loomnet.models.blocks.resnet import ResBlock +import torch +import torch.nn as nn +from diffusers import UNet2DConditionModel +from einops import rearrange + +from loomnet.utils.project import HarmonicEmbedding, process_cameras + + +@dataclass +class RenderConfig: + ray_start: float = 0.5 + ray_end: float = 2.8 + resolution: int = 32 + n_samples: int = 8 + disparity_space_sampling: bool = False + box_warp: float = 1.0 + + +class MVModel(nn.Module): + def __init__( + self, + cp_block_model: nn.Module, + unet: Optional[UNet2DConditionModel] = None, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: str = "fp16_ema", + train_unet: bool = False, + insert_stages: List[int] = ["mid", "up"], + insert_up_layers: List[int] = [0, 1, 2, 3], + use_residual: bool = False, + plane_resolution: int = 32, + plane_channel_dim: int = 512 + ): + super().__init__() + + self.trainable_parameters = [] + + # prepare unet + self.unet = unet + if unet is None: + self.unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", variant=variant + ) + + if train_unet: + self.trainable_parameters += [(self.unet.parameters(), 0.01)] + else: + self.unet.requires_grad_(False) + + self.insert_stages = insert_stages + self.insert_up_layers = insert_up_layers + self.use_residual = use_residual + + # camera embedding + self.harmonic_embedding = HarmonicEmbedding() + embed_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + self.cp_blocks_encoder = nn.ModuleList() + self.cp_blocks_mid = nn.ModuleList() + self.cp_blocks_decoder = nn.ModuleList() + + if "down" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [32, 16, 8, 4] + + for i in range(len(self.unet.down_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_encoder.append( + cp_block_model( + dim=self.unet.down_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + if "mid" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolution = 4 + plane_resolution = 32 + plane_channel_dim = 1280 + n_samples_per_ray = 32 + + self.cp_blocks_mid.append( + cp_block_model( + self.unet.mid_block.resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolution, + plane_resolution = plane_resolution, + plane_channel_dim = plane_channel_dim, + plane_channel_dim_after_upsample = plane_channel_dim, + n_samples_per_ray = n_samples_per_ray + ) + ) + if "up" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [4,8,16,32] + plane_resolutions = [8, 16, 32, 64] + plane_channel_dims = [1280, 1280, 640, 256] + n_samples_per_ray_per_level = [16, 24, 48, 64] + + for i in range(len(self.unet.up_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_decoder.append( + cp_block_model( + self.unet.up_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i], + plane_resolution = plane_resolutions[i], + plane_channel_dim = plane_channel_dims[i], + plane_channel_dim_after_upsample = plane_channel_dims[i]//2, + n_samples_per_ray = n_samples_per_ray_per_level[i], + is_last_communication_block = True if i == max(insert_up_layers) else False + ) + ) + + + ''' + TRIPLANE TOKENS + ''' + plane_resolution = 32 + plane_channel_dim = 1280 + self.pos_embed_middle = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + self.pos_embed_up_0 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + plane_resolution = 16 + plane_channel_dim = 1280 + self.pos_embed_up_1 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + plane_resolution = 32 + plane_channel_dim = 640 + self.pos_embed_up_2 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + plane_resolution = 64 + plane_channel_dim = 256 + self.pos_embed_up_3 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + + #adapters + self.resnet_middle = ResBlock(1280, 1280, use_scale_shift_norm=True) + self.resnet_up_0 = ResBlock(1280, 1280, use_scale_shift_norm=True) + self.resnet_up_1 = ResBlock(1280, 1280, use_scale_shift_norm=True) + self.resnet_up_2 = ResBlock(640, 1280, use_scale_shift_norm=True) + self.resnet_up_3 = ResBlock(320, 1280, use_scale_shift_norm=True) + self.resnet_ups = [self.resnet_up_0,self.resnet_up_1,self.resnet_up_2,self.resnet_up_3] + + + self.trainable_parameters += [ + ( + list(self.cp_blocks_mid.parameters()) + + list(self.cp_blocks_decoder.parameters()) + + list(self.cp_blocks_encoder.parameters()), + 1.0, + ), + ( + [self.pos_embed_middle, self.pos_embed_up_0, self.pos_embed_up_1, self.pos_embed_up_2, self.pos_embed_up_3], + 1.0 + ), + ( + list(self.resnet_middle.parameters()) + + list(self.resnet_up_0.parameters()) + + list(self.resnet_up_1.parameters()) + + list(self.resnet_up_2.parameters()) + + list(self.resnet_up_3.parameters()), + 1.0 + ) + ] + + + def set_use_memory_efficient_attention_xformers( + self, valid: bool, attention_op=None + ) -> None: + def fn_recursive_set_mem_eff(module: torch.nn.Module): + if hasattr(module, "set_use_memory_efficient_attention_xformers"): + module.set_use_memory_efficient_attention_xformers(valid, attention_op) + + for child in module.children(): + fn_recursive_set_mem_eff(child) + + for module in self.children(): + if isinstance(module, torch.nn.Module): + fn_recursive_set_mem_eff(module) + + def forward(self, latents, timestep, prompt_embd, meta): + cameras = meta["cameras"] + k_near_indices = meta["k_near_indices"] + b, m, c, h, w = latents.shape + + # [0, 1] -> [-1, 1] + # bs*m, 4, 64, 64 + hidden_states = rearrange(latents, "b m c h w -> (b m) c h w") + prompt_embd = rearrange(prompt_embd, "b m l c -> (b m) l c") + + # 1. process timesteps + timestep = timestep.reshape(-1) + t_emb = self.unet.time_proj(timestep) # (bs, 320) + emb = self.unet.time_embedding(t_emb) # (bs, 1280) + + hidden_states = self.unet.conv_in(hidden_states) # bs*m, 320, 64, 64 + + feature_pairs = [] + pos_embeds = [] + + # unet + # a. downsample + current_downblock_id = 0 + down_block_res_samples = (hidden_states,) + for i, downsample_block in enumerate(self.unet.down_blocks): + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + for resnet, attn in zip( + downsample_block.resnets, downsample_block.attentions + ): + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + down_block_res_samples += (hidden_states,) + else: + for resnet in downsample_block.resnets: + hidden_states = resnet(hidden_states, emb) + down_block_res_samples += (hidden_states,) + + if len(self.cp_blocks_encoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed = self.cp_blocks_encoder[current_downblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed #TODO USARE POS_EMBED_ENCODER + ) + + current_downblock_id += 1 + + feature_pairs.append((global_latent_views, hidden_states.detach())) + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if downsample_block.downsamplers is not None: + for downsample in downsample_block.downsamplers: + hidden_states = downsample(hidden_states) + down_block_res_samples += (hidden_states,) + + # b. mid + hidden_states = self.unet.mid_block.resnets[0](hidden_states, emb) + + if len(self.cp_blocks_mid) > 0: + + hidden_states = self.resnet_middle(hidden_states, emb) + + global_latent_views, pos_embed = self.cp_blocks_mid[0]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = self.pos_embed_middle + ) + + feature_pairs.append((global_latent_views, hidden_states.detach())) + + pos_embeds.append(pos_embed) + + hidden_states = ( + hidden_states #+ global_latent_views + if self.use_residual + else global_latent_views + ) + + + for attn, resnet in zip( + self.unet.mid_block.attentions, self.unet.mid_block.resnets[1:] + ): + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + hidden_states = resnet(hidden_states, emb) + + h, w = hidden_states.shape[-2:] + + # c. upsample + current_upblock_id = 0 + for i, upsample_block in enumerate(self.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + for resnet, attn in zip( + upsample_block.resnets, upsample_block.attentions + ): + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + else: + for resnet in upsample_block.resnets: + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + + if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers:# and i!=3: #TODO ELIMINA and i!=3 + + hidden_states = self.resnet_ups[i](hidden_states, emb) + + # global_latent_views, pos_embed = self.cp_blocks_decoder[current_upblock_id]( + # hidden_states, + # emb, #--> time + # cameras = cameras, + # k_near_cameras = k_near_indices, + # pos_embed = self.pos_embed_up_0 if i== 0 else (self.pos_embed_up_1 if i==1 else (self.pos_embed_up_2 if i==2 else self.pos_embed_up_3)) + # ) + + # current_upblock_id += 1 + + # feature_pairs.append((global_latent_views, hidden_states.detach())) + + # pos_embeds.append(pos_embed) + + hidden_states = ( + hidden_states #+ global_latent_views + if self.use_residual# or i==3 + else global_latent_views #else (global_latent_views if i!=3 else hidden_states + global_latent_views) + ) + + if upsample_block.upsamplers is not None: + for upsample in upsample_block.upsamplers: + hidden_states = upsample(hidden_states) + + + # 4.post-process + sample = self.unet.conv_norm_out(hidden_states) + sample = self.unet.conv_act(sample) + sample = self.unet.conv_out(sample) + sample = rearrange(sample, "(b m) c h w -> b m c h w", m=m) + return sample, pos_embeds, feature_pairs + + + def channel_mixing_step(self, hidden_states, global_latent_views, step, max_steps=2000): + """ + hidden_states, global_latent_views: (B, C, H, W) + step: numero di step corrente + max_steps: step in cui alpha raggiunge 1 + """ + B, C, H, W = hidden_states.shape + # linear schedule da 0 a 1 + alpha = min(step / max_steps, 1.0) + + if alpha>=0.99: + return global_latent_views + + mixed = hidden_states.clone() + + for b in range(B): + mask = torch.rand(C, device=hidden_states.device) < alpha + mask = mask[:, None, None] # broadcast su H, W + mixed[b] = torch.where(mask, global_latent_views[b], hidden_states[b]) + + return mixed diff --git a/loomnet/models/mv_model_triplane_with_3d_conv.py b/loomnet/models/mv_model_triplane_with_3d_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..3be44acf275ce83769286cdfd21d94a10dab84b2 --- /dev/null +++ b/loomnet/models/mv_model_triplane_with_3d_conv.py @@ -0,0 +1,372 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union +from loomnet.models.blocks.resnet import ResBlock +import torch +import torch.nn as nn +from diffusers import UNet2DConditionModel +from einops import rearrange + +from loomnet.utils.project import HarmonicEmbedding, process_cameras + + +@dataclass +class RenderConfig: + ray_start: float = 0.5 + ray_end: float = 2.8 + resolution: int = 32 + n_samples: int = 8 + disparity_space_sampling: bool = False + box_warp: float = 1.0 + + +class MVModel(nn.Module): + def __init__( + self, + cp_block_model: nn.Module, + unet: Optional[UNet2DConditionModel] = None, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: str = "fp16_ema", + train_unet: bool = False, + insert_stages: List[int] = ["mid", "up"], + insert_up_layers: List[int] = [0, 1, 2, 3], + use_residual: bool = False, + plane_resolution: int = 32, + plane_channel_dim: int = 512 + ): + super().__init__() + + self.trainable_parameters = [] + + # prepare unet + self.unet = unet + if unet is None: + self.unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", variant=variant + ) + + if train_unet: + self.trainable_parameters += [(self.unet.parameters(), 0.01)] + else: + self.unet.requires_grad_(False) + + self.insert_stages = insert_stages + self.insert_up_layers = insert_up_layers + self.use_residual = use_residual + + # camera embedding + self.harmonic_embedding = HarmonicEmbedding() + embed_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + self.cp_blocks_encoder = nn.ModuleList() + self.cp_blocks_mid = nn.ModuleList() + self.cp_blocks_decoder = nn.ModuleList() + + if "down" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [32, 16, 8, 4] + + for i in range(len(self.unet.down_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_encoder.append( + cp_block_model( + dim=self.unet.down_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + if "mid" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolution = 4 + plane_resolution = 64 + plane_channel_dim = 1280 + n_samples_per_ray = 32 + + self.cp_blocks_mid.append( + cp_block_model( + self.unet.mid_block.resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolution, + plane_resolution = plane_resolution, + plane_channel_dim = plane_channel_dim, + plane_channel_dim_after_upsample = 320, + n_samples_per_ray = n_samples_per_ray + ) + ) + if "up" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [4,8,16,32] + plane_resolutions = [8, 16, 32, 64] + plane_channel_dims = [1280, 1280, 640, 256] + n_samples_per_ray_per_level = [16, 24, 48, 64] + + for i in range(len(self.unet.up_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_decoder.append( + cp_block_model( + self.unet.up_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i], + plane_resolution = plane_resolutions[i], + plane_channel_dim = plane_channel_dims[i], + plane_channel_dim_after_upsample = plane_channel_dims[i]//2, + n_samples_per_ray = n_samples_per_ray_per_level[i], + is_last_communication_block = True if i == max(insert_up_layers) else False + ) + ) + + + ''' + TRIPLANE TOKENS + ''' + plane_resolution = 32 + plane_channel_dim = 1280 + self.pos_embed_middle = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + self.pos_embed_up_0 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + plane_resolution = 16 + plane_channel_dim = 1280 + self.pos_embed_up_1 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + plane_resolution = 32 + plane_channel_dim = 640 + self.pos_embed_up_2 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + plane_resolution = 64 + plane_channel_dim = 256 + self.pos_embed_up_3 = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + + #adapters + self.resnet_middle = ResBlock(1280, 1280, use_scale_shift_norm=True) + self.resnet_up_0 = ResBlock(1280, 1280, use_scale_shift_norm=True) + self.resnet_up_1 = ResBlock(1280, 1280, use_scale_shift_norm=True) + self.resnet_up_2 = ResBlock(640, 1280, use_scale_shift_norm=True) + self.resnet_up_3 = ResBlock(320, 1280, use_scale_shift_norm=True) + self.resnet_ups = [self.resnet_up_0,self.resnet_up_1,self.resnet_up_2,self.resnet_up_3] + + + self.trainable_parameters += [ + ( + list(self.cp_blocks_mid.parameters()) + + list(self.cp_blocks_decoder.parameters()) + + list(self.cp_blocks_encoder.parameters()), + 1.0, + ), + ( + [self.pos_embed_middle, self.pos_embed_up_0, self.pos_embed_up_1, self.pos_embed_up_2, self.pos_embed_up_3], + 1.0 + ), + ( + list(self.resnet_middle.parameters()) + + list(self.resnet_up_0.parameters()) + + list(self.resnet_up_1.parameters()) + + list(self.resnet_up_2.parameters()) + + list(self.resnet_up_3.parameters()), + 1.0 + ) + ] + + + def set_use_memory_efficient_attention_xformers( + self, valid: bool, attention_op=None + ) -> None: + def fn_recursive_set_mem_eff(module: torch.nn.Module): + if hasattr(module, "set_use_memory_efficient_attention_xformers"): + module.set_use_memory_efficient_attention_xformers(valid, attention_op) + + for child in module.children(): + fn_recursive_set_mem_eff(child) + + for module in self.children(): + if isinstance(module, torch.nn.Module): + fn_recursive_set_mem_eff(module) + + def forward(self, latents, timestep, prompt_embd, meta): + cameras = meta["cameras"] + k_near_indices = meta["k_near_indices"] + b, m, c, h, w = latents.shape + + # [0, 1] -> [-1, 1] + # bs*m, 4, 64, 64 + hidden_states = rearrange(latents, "b m c h w -> (b m) c h w") + prompt_embd = rearrange(prompt_embd, "b m l c -> (b m) l c") + + # 1. process timesteps + timestep = timestep.reshape(-1) + t_emb = self.unet.time_proj(timestep) # (bs, 320) + emb = self.unet.time_embedding(t_emb) # (bs, 1280) + + hidden_states = self.unet.conv_in(hidden_states) # bs*m, 320, 64, 64 + + feature_pairs = [] + pos_embeds = [] + + # unet + # a. downsample + current_downblock_id = 0 + down_block_res_samples = (hidden_states,) + for i, downsample_block in enumerate(self.unet.down_blocks): + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + for resnet, attn in zip( + downsample_block.resnets, downsample_block.attentions + ): + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + down_block_res_samples += (hidden_states,) + else: + for resnet in downsample_block.resnets: + hidden_states = resnet(hidden_states, emb) + down_block_res_samples += (hidden_states,) + + if len(self.cp_blocks_encoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed = self.cp_blocks_encoder[current_downblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed #TODO USARE POS_EMBED_ENCODER + ) + + current_downblock_id += 1 + + feature_pairs.append((global_latent_views, hidden_states.detach())) + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if downsample_block.downsamplers is not None: + for downsample in downsample_block.downsamplers: + hidden_states = downsample(hidden_states) + down_block_res_samples += (hidden_states,) + + # b. mid + hidden_states = self.unet.mid_block.resnets[0](hidden_states, emb) + + if len(self.cp_blocks_mid) > 0: + + hidden_states = self.resnet_middle(hidden_states, emb) + + global_latent_views, pos_embed = self.cp_blocks_mid[0]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = self.pos_embed_middle + ) + + feature_pairs.append((global_latent_views, hidden_states.detach())) + + pos_embeds.append(pos_embed) + + hidden_states = ( + hidden_states #+ global_latent_views + if self.use_residual + else global_latent_views + ) + + + for attn, resnet in zip( + self.unet.mid_block.attentions, self.unet.mid_block.resnets[1:] + ): + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + hidden_states = resnet(hidden_states, emb) + + h, w = hidden_states.shape[-2:] + + # c. upsample + current_upblock_id = 0 + for i, upsample_block in enumerate(self.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + for resnet, attn in zip( + upsample_block.resnets, upsample_block.attentions + ): + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + else: + for resnet in upsample_block.resnets: + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + + if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers:# and i!=3: #TODO ELIMINA and i!=3 + + hidden_states = self.resnet_ups[i](hidden_states, emb) + + # if i==3: + # global_latent_views, pos_embed = self.cp_blocks_decoder[current_upblock_id]( + # hidden_states, + # emb, #--> time + # cameras = cameras, + # k_near_cameras = k_near_indices, + # pos_embed = self.pos_embed_up_0 if i== 0 else (self.pos_embed_up_1 if i==1 else (self.pos_embed_up_2 if i==2 else self.pos_embed_up_3)) + # ) + + + # feature_pairs.append((global_latent_views, hidden_states.detach())) + + # pos_embeds.append(pos_embed) + + current_upblock_id += 1 + + hidden_states = ( + hidden_states #+ global_latent_views + if self.use_residual# or i==3 + else global_latent_views #else (global_latent_views if i!=3 else hidden_states + global_latent_views) + ) + + if upsample_block.upsamplers is not None: + for upsample in upsample_block.upsamplers: + hidden_states = upsample(hidden_states) + + + # 4.post-process + sample = self.unet.conv_norm_out(hidden_states) + sample = self.unet.conv_act(sample) + sample = self.unet.conv_out(sample) + sample = rearrange(sample, "(b m) c h w -> b m c h w", m=m) + return sample, pos_embeds, feature_pairs + + + def channel_mixing_step(self, hidden_states, global_latent_views, step, max_steps=2000): + """ + hidden_states, global_latent_views: (B, C, H, W) + step: numero di step corrente + max_steps: step in cui alpha raggiunge 1 + """ + B, C, H, W = hidden_states.shape + # linear schedule da 0 a 1 + alpha = min(step / max_steps, 1.0) + + if alpha>=0.99: + return global_latent_views + + mixed = hidden_states.clone() + + for b in range(B): + mask = torch.rand(C, device=hidden_states.device) < alpha + mask = mask[:, None, None] # broadcast su H, W + mixed[b] = torch.where(mask, global_latent_views[b], hidden_states[b]) + + return mixed diff --git a/loomnet/models/mv_model_v7.py b/loomnet/models/mv_model_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..51551b783b9749e009c420a03d1897ea136046d7 --- /dev/null +++ b/loomnet/models/mv_model_v7.py @@ -0,0 +1,348 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union + +import torch +import torch.nn as nn +from diffusers import UNet2DConditionModel +from einops import rearrange + +from loomnet.utils.project import HarmonicEmbedding, process_cameras + + +@dataclass +class RenderConfig: + ray_start: float = 0.5 + ray_end: float = 2.8 + resolution: int = 32 + n_samples: int = 8 + disparity_space_sampling: bool = False + box_warp: float = 1.0 + + +class MVModel(nn.Module): + def __init__( + self, + cp_block_model: nn.Module, + unet: Optional[UNet2DConditionModel] = None, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: str = "fp16_ema", + train_unet: bool = False, + insert_stages: List[int] = ["mid", "up"], + insert_up_layers: List[int] = [0, 1, 2, 3], + render_options: RenderConfig = RenderConfig(), + use_residual: bool = False + ): + super().__init__() + + self.trainable_parameters = [] + + # prepare unet + self.unet = unet + if unet is None: + self.unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", variant=variant + ) + + if train_unet: + self.trainable_parameters += [(self.unet.parameters(), 0.01)] + else: + self.unet.requires_grad_(False) + + self.insert_stages = insert_stages + self.insert_up_layers = insert_up_layers + self.use_residual = use_residual + + render_options = vars(render_options) + self.render_options = vars(RenderConfig()) + self.render_options.update(render_options) + + # camera embedding + self.harmonic_embedding = HarmonicEmbedding() + embed_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + self.cp_blocks_encoder = nn.ModuleList() + self.cp_blocks_mid = nn.ModuleList() + self.cp_blocks_decoder = nn.ModuleList() + + if "down" in self.insert_stages: + for i in range(len(self.unet.down_blocks)): + self.cp_blocks_encoder.append( + cp_block_model( + dim=self.unet.down_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + ) + ) + if "mid" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolution = 4 + + self.cp_blocks_mid.append( + cp_block_model( + self.unet.mid_block.resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolution + ) + ) + if "up" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [4,8,16,32] + + for i in range(len(self.unet.up_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_decoder.append( + cp_block_model( + self.unet.up_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + + + self.trainable_parameters += [ + ( + list(self.cp_blocks_mid.parameters()) + + list(self.cp_blocks_decoder.parameters()) + + list(self.cp_blocks_encoder.parameters()), + 1.0, + ) + ] + + def set_use_memory_efficient_attention_xformers( + self, valid: bool, attention_op=None + ) -> None: + def fn_recursive_set_mem_eff(module: torch.nn.Module): + if hasattr(module, "set_use_memory_efficient_attention_xformers"): + module.set_use_memory_efficient_attention_xformers(valid, attention_op) + + for child in module.children(): + fn_recursive_set_mem_eff(child) + + for module in self.children(): + if isinstance(module, torch.nn.Module): + fn_recursive_set_mem_eff(module) + + def forward(self, latents, timestep, prompt_embd, meta): + cameras = meta["cameras"] + k_near_indices = meta["k_near_indices"] + b, m, c, h, w = latents.shape + + # [0, 1] -> [-1, 1] + # bs*m, 4, 64, 64 + hidden_states = rearrange(latents, "b m c h w -> (b m) c h w") + prompt_embd = rearrange(prompt_embd, "b m l c -> (b m) l c") + + # 1. process timesteps + timestep = timestep.reshape(-1) + t_emb = self.unet.time_proj(timestep) # (bs, 320) + emb = self.unet.time_embedding(t_emb) # (bs, 1280) + + hidden_states = self.unet.conv_in(hidden_states) # bs*m, 320, 64, 64 + + list_pixel_distances, list_feature_similarity = [], [] + + # unet + # a. downsample + down_block_res_samples = (hidden_states,) + for i, downsample_block in enumerate(self.unet.down_blocks): + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + for resnet, attn in zip( + downsample_block.resnets, downsample_block.attentions + ): + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + down_block_res_samples += (hidden_states,) + else: + for resnet in downsample_block.resnets: + hidden_states = resnet(hidden_states, emb) + down_block_res_samples += (hidden_states,) + + # if len(self.cp_blocks_encoder) > 0: + # ( + # projected_points, + # mask, + # query_plucker, + # reference_plucker, + # sample_depths, + # ) = process_cameras( + # cameras, + # k_near_indices, + # harmonic_embedding=self.harmonic_embedding, + # rendering_options=self.render_options, + # ) + # cp_block_states = self.cp_blocks_encoder[i]( + # hidden_states, + # projected_points, + # mask, + # query_plucker, + # reference_plucker, + # m, + # emb, + # ) + # hidden_states = ( + # hidden_states + cp_block_states + # if self.use_residual + # else cp_block_states + # ) + + if downsample_block.downsamplers is not None: + for downsample in downsample_block.downsamplers: + hidden_states = downsample(hidden_states) + down_block_res_samples += (hidden_states,) + self.render_options["resolution"] = ( + self.render_options["resolution"] // 2 + ) + + # b. mid + hidden_states = self.unet.mid_block.resnets[0](hidden_states, emb) + # if len(self.cp_blocks_mid) > 0: + # ( + # projected_points, + # mask, + # query_plucker, + # reference_plucker, + # sample_depths, + # ) = process_cameras( + # cameras, + # k_near_indices, + # harmonic_embedding=self.harmonic_embedding, + # rendering_options=self.render_options, + # ) + # assert self.render_options["resolution"] == hidden_states.shape[-1] + # cp_block_states = self.cp_blocks_mid[0]( + # hidden_states, + # projected_points, + # mask, + # query_plucker, + # reference_plucker, + # m, + # emb, + # ) + # hidden_states = ( + # hidden_states + cp_block_states + # if self.use_residual + # else cp_block_states + # ) + + # #MIO + if len(self.cp_blocks_mid) > 0: + + global_latent_views = self.cp_blocks_mid[0]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices + ) + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + + for attn, resnet in zip( + self.unet.mid_block.attentions, self.unet.mid_block.resnets[1:] + ): + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + hidden_states = resnet(hidden_states, emb) + + h, w = hidden_states.shape[-2:] + + # c. upsample + current_upblock_id = 0 + for i, upsample_block in enumerate(self.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + for resnet, attn in zip( + upsample_block.resnets, upsample_block.attentions + ): + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + else: + for resnet in upsample_block.resnets: + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + + # if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers: + # ( + # projected_points, + # mask, + # query_plucker, + # reference_plucker, + # sample_depths, + # ) = process_cameras( + # cameras, + # k_near_indices, + # harmonic_embedding=self.harmonic_embedding, + # rendering_options=self.render_options, + # ) + # cp_block_states = self.cp_blocks_decoder[current_upblock_id]( + # hidden_states, + # projected_points, + # mask, + # query_plucker, + # reference_plucker, + # m, + # emb, + # ) + # current_upblock_id += 1 + # hidden_states = ( + # hidden_states + cp_block_states + # if self.use_residual + # else cp_block_states + # ) + + #MIO + if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers: + global_latent_views = self.cp_blocks_decoder[current_upblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices + ) + + current_upblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if upsample_block.upsamplers is not None: + for upsample in upsample_block.upsamplers: + hidden_states = upsample(hidden_states) + self.render_options["resolution"] = ( + self.render_options["resolution"] * 2 + ) + + # 4.post-process + sample = self.unet.conv_norm_out(hidden_states) + sample = self.unet.conv_act(sample) + sample = self.unet.conv_out(sample) + sample = rearrange(sample, "(b m) c h w -> b m c h w", m=m) + return sample diff --git a/loomnet/models/mv_model_v8.py b/loomnet/models/mv_model_v8.py new file mode 100644 index 0000000000000000000000000000000000000000..144b4e3d85fa8ddacda0fcf4f4e672a4da4e9f90 --- /dev/null +++ b/loomnet/models/mv_model_v8.py @@ -0,0 +1,293 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union + +import torch +import torch.nn as nn +from diffusers import UNet2DConditionModel +from einops import rearrange + +from loomnet.utils.project import HarmonicEmbedding, process_cameras + + +@dataclass +class RenderConfig: + ray_start: float = 0.5 + ray_end: float = 2.8 + resolution: int = 32 + n_samples: int = 8 + disparity_space_sampling: bool = False + box_warp: float = 1.0 + + +class MVModel(nn.Module): + def __init__( + self, + cp_block_model: nn.Module, + unet: Optional[UNet2DConditionModel] = None, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: str = "fp16_ema", + train_unet: bool = False, + insert_stages: List[int] = ["mid", "up"], + insert_up_layers: List[int] = [0, 1, 2, 3], + use_residual: bool = False, + plane_resolution: int = 32, + plane_channel_dim: int = 512 + ): + super().__init__() + + self.trainable_parameters = [] + + # prepare unet + self.unet = unet + if unet is None: + self.unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", variant=variant + ) + + if train_unet: + self.trainable_parameters += [(self.unet.parameters(), 0.01)] + else: + self.unet.requires_grad_(False) + + self.insert_stages = insert_stages + self.insert_up_layers = insert_up_layers + self.use_residual = use_residual + + # camera embedding + self.harmonic_embedding = HarmonicEmbedding() + embed_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + self.cp_blocks_encoder = nn.ModuleList() + self.cp_blocks_mid = nn.ModuleList() + self.cp_blocks_decoder = nn.ModuleList() + + if "down" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [32, 16, 8, 4] + + for i in range(len(self.unet.down_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_encoder.append( + cp_block_model( + dim=self.unet.down_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + if "mid" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolution = 4 + + self.cp_blocks_mid.append( + cp_block_model( + self.unet.mid_block.resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolution + ) + ) + if "up" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [4,8,16,32] + + for i in range(len(self.unet.up_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_decoder.append( + cp_block_model( + self.unet.up_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i], + is_last_communication_block = True if i == max(insert_up_layers) else False + ) + ) + + + ''' + TRIPLANE TOKENS + ''' + self.pos_embed = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + + + + self.trainable_parameters += [ + ( + list(self.cp_blocks_mid.parameters()) + + list(self.cp_blocks_decoder.parameters()) + + list(self.cp_blocks_encoder.parameters()), + 1.0, + ), + ( + [self.pos_embed], + 1.0 + ) + ] + + def set_use_memory_efficient_attention_xformers( + self, valid: bool, attention_op=None + ) -> None: + def fn_recursive_set_mem_eff(module: torch.nn.Module): + if hasattr(module, "set_use_memory_efficient_attention_xformers"): + module.set_use_memory_efficient_attention_xformers(valid, attention_op) + + for child in module.children(): + fn_recursive_set_mem_eff(child) + + for module in self.children(): + if isinstance(module, torch.nn.Module): + fn_recursive_set_mem_eff(module) + + def forward(self, latents, timestep, prompt_embd, meta): + cameras = meta["cameras"] + k_near_indices = meta["k_near_indices"] + b, m, c, h, w = latents.shape + + # [0, 1] -> [-1, 1] + # bs*m, 4, 64, 64 + hidden_states = rearrange(latents, "b m c h w -> (b m) c h w") + prompt_embd = rearrange(prompt_embd, "b m l c -> (b m) l c") + + # 1. process timesteps + timestep = timestep.reshape(-1) + t_emb = self.unet.time_proj(timestep) # (bs, 320) + emb = self.unet.time_embedding(t_emb) # (bs, 1280) + + hidden_states = self.unet.conv_in(hidden_states) # bs*m, 320, 64, 64 + + list_pixel_distances, list_feature_similarity = [], [] + + pos_embed = self.pos_embed + + # unet + # a. downsample + current_downblock_id = 0 + down_block_res_samples = (hidden_states,) + for i, downsample_block in enumerate(self.unet.down_blocks): + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + for resnet, attn in zip( + downsample_block.resnets, downsample_block.attentions + ): + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + down_block_res_samples += (hidden_states,) + else: + for resnet in downsample_block.resnets: + hidden_states = resnet(hidden_states, emb) + down_block_res_samples += (hidden_states,) + + if len(self.cp_blocks_encoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed = self.cp_blocks_encoder[current_downblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + current_downblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if downsample_block.downsamplers is not None: + for downsample in downsample_block.downsamplers: + hidden_states = downsample(hidden_states) + down_block_res_samples += (hidden_states,) + + # b. mid + hidden_states = self.unet.mid_block.resnets[0](hidden_states, emb) + + if len(self.cp_blocks_mid) > 0: + + global_latent_views, pos_embed = self.cp_blocks_mid[0]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + + for attn, resnet in zip( + self.unet.mid_block.attentions, self.unet.mid_block.resnets[1:] + ): + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + hidden_states = resnet(hidden_states, emb) + + h, w = hidden_states.shape[-2:] + + # c. upsample + current_upblock_id = 0 + for i, upsample_block in enumerate(self.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + for resnet, attn in zip( + upsample_block.resnets, upsample_block.attentions + ): + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + else: + for resnet in upsample_block.resnets: + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + + if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed = self.cp_blocks_decoder[current_upblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + current_upblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if upsample_block.upsamplers is not None: + for upsample in upsample_block.upsamplers: + hidden_states = upsample(hidden_states) + + + # 4.post-process + sample = self.unet.conv_norm_out(hidden_states) + sample = self.unet.conv_act(sample) + sample = self.unet.conv_out(sample) + sample = rearrange(sample, "(b m) c h w -> b m c h w", m=m) + return sample, pos_embed diff --git a/loomnet/models/mv_model_with_distillation.py b/loomnet/models/mv_model_with_distillation.py new file mode 100644 index 0000000000000000000000000000000000000000..02857b7f3190e74dad8462d9f0fb8d97eaf679d0 --- /dev/null +++ b/loomnet/models/mv_model_with_distillation.py @@ -0,0 +1,294 @@ +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Union + +import torch +import torch.nn as nn +from diffusers import UNet2DConditionModel +from einops import rearrange + +from loomnet.utils.project import HarmonicEmbedding, process_cameras + + +@dataclass +class RenderConfig: + ray_start: float = 0.5 + ray_end: float = 2.8 + resolution: int = 32 + n_samples: int = 8 + disparity_space_sampling: bool = False + box_warp: float = 1.0 + + +class MVModel(nn.Module): + def __init__( + self, + cp_block_model: nn.Module, + unet: Optional[UNet2DConditionModel] = None, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: str = "fp16_ema", + train_unet: bool = False, + insert_stages: List[int] = ["mid", "up"], + insert_up_layers: List[int] = [0, 1, 2, 3], + use_residual: bool = False, + plane_resolution: int = 32, + plane_channel_dim: int = 512 + ): + super().__init__() + + self.trainable_parameters = [] + + # prepare unet + self.unet = unet + if unet is None: + self.unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", variant=variant + ) + + if train_unet: + self.trainable_parameters += [(self.unet.parameters(), 0.01)] + else: + self.unet.requires_grad_(False) + + self.insert_stages = insert_stages + self.insert_up_layers = insert_up_layers + self.use_residual = use_residual + + # camera embedding + self.harmonic_embedding = HarmonicEmbedding() + embed_dim = HarmonicEmbedding.get_output_dim_static( + 6, n_harmonic_functions=6, append_input=True + ) + + self.cp_blocks_encoder = nn.ModuleList() + self.cp_blocks_mid = nn.ModuleList() + self.cp_blocks_decoder = nn.ModuleList() + + if "down" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [32, 16, 8, 4] + + for i in range(len(self.unet.down_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_encoder.append( + cp_block_model( + dim=self.unet.down_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + if "mid" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolution = 4 + + self.cp_blocks_mid.append( + cp_block_model( + self.unet.mid_block.resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolution + ) + ) + if "up" in self.insert_stages: + #indico la risoluzione spaziale (H o W) ad ogni livello + spatial_resolutions = [4,8,16,32] + + for i in range(len(self.unet.up_blocks)): + if i in self.insert_up_layers: + self.cp_blocks_decoder.append( + cp_block_model( + self.unet.up_blocks[i].resnets[-1].out_channels, + embed_dim=embed_dim, + latent_dim = spatial_resolutions[i] + ) + ) + + + ''' + TRIPLANE TOKENS + ''' + self.pos_embed = nn.Parameter(torch.randn(1, 3*plane_resolution**2, plane_channel_dim) * (1. / plane_channel_dim) ** 0.5) + + + + self.trainable_parameters += [ + ( + list(self.cp_blocks_mid.parameters()) + + list(self.cp_blocks_decoder.parameters()) + + list(self.cp_blocks_encoder.parameters()), + 1.0, + ), + ( + [self.pos_embed], + 1.0 + ) + ] + + def set_use_memory_efficient_attention_xformers( + self, valid: bool, attention_op=None + ) -> None: + def fn_recursive_set_mem_eff(module: torch.nn.Module): + if hasattr(module, "set_use_memory_efficient_attention_xformers"): + module.set_use_memory_efficient_attention_xformers(valid, attention_op) + + for child in module.children(): + fn_recursive_set_mem_eff(child) + + for module in self.children(): + if isinstance(module, torch.nn.Module): + fn_recursive_set_mem_eff(module) + + def forward(self, latents, timestep, prompt_embd, meta): + cameras = meta["cameras"] + k_near_indices = meta["k_near_indices"] + b, m, c, h, w = latents.shape + + # [0, 1] -> [-1, 1] + # bs*m, 4, 64, 64 + hidden_states = rearrange(latents, "b m c h w -> (b m) c h w") + prompt_embd = rearrange(prompt_embd, "b m l c -> (b m) l c") + + # 1. process timesteps + timestep = timestep.reshape(-1) + t_emb = self.unet.time_proj(timestep) # (bs, 320) + emb = self.unet.time_embedding(t_emb) # (bs, 1280) + + hidden_states = self.unet.conv_in(hidden_states) # bs*m, 320, 64, 64 + + list_pixel_distances, list_feature_similarity = [], [] + + pos_embed = self.pos_embed + + # unet + # a. downsample + current_downblock_id = 0 + down_block_res_samples = (hidden_states,) + for i, downsample_block in enumerate(self.unet.down_blocks): + if ( + hasattr(downsample_block, "has_cross_attention") + and downsample_block.has_cross_attention + ): + for resnet, attn in zip( + downsample_block.resnets, downsample_block.attentions + ): + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + down_block_res_samples += (hidden_states,) + else: + for resnet in downsample_block.resnets: + hidden_states = resnet(hidden_states, emb) + down_block_res_samples += (hidden_states,) + + if len(self.cp_blocks_encoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed, decoded_sampled_features_by_student, decoded_sampled_features_by_teacher, alpha = self.cp_blocks_encoder[current_downblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + current_downblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if downsample_block.downsamplers is not None: + for downsample in downsample_block.downsamplers: + hidden_states = downsample(hidden_states) + down_block_res_samples += (hidden_states,) + + # b. mid + hidden_states = self.unet.mid_block.resnets[0](hidden_states, emb) + + if len(self.cp_blocks_mid) > 0: + + global_latent_views, pos_embed, decoded_sampled_features_by_student, decoded_sampled_features_by_teacher, alpha = self.cp_blocks_mid[0]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed + ) + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + + for attn, resnet in zip( + self.unet.mid_block.attentions, self.unet.mid_block.resnets[1:] + ): + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + hidden_states = resnet(hidden_states, emb) + + h, w = hidden_states.shape[-2:] + + # c. upsample + current_upblock_id = 0 + for i, upsample_block in enumerate(self.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[ + : -len(upsample_block.resnets) + ] + + if ( + hasattr(upsample_block, "has_cross_attention") + and upsample_block.has_cross_attention + ): + for resnet, attn in zip( + upsample_block.resnets, upsample_block.attentions + ): + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + hidden_states = attn( + hidden_states, encoder_hidden_states=prompt_embd + ).sample + else: + for resnet in upsample_block.resnets: + res_hidden_states = res_samples[-1] + res_samples = res_samples[:-1] + hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) + hidden_states = resnet(hidden_states, emb) + + if len(self.cp_blocks_decoder) > 0 and i in self.insert_up_layers: + global_latent_views, pos_embed, decoded_sampled_features_by_student, decoded_sampled_features_by_teacher, alpha = self.cp_blocks_decoder[current_upblock_id]( + hidden_states, + emb, #--> time + cameras = cameras, + k_near_cameras = k_near_indices, + pos_embed = pos_embed, + global_step = meta["global_step"], + training = meta["training"] + ) + + current_upblock_id += 1 + + + hidden_states = ( + hidden_states + global_latent_views + if self.use_residual + else global_latent_views + ) + + if upsample_block.upsamplers is not None: + for upsample in upsample_block.upsamplers: + hidden_states = upsample(hidden_states) + + + # 4.post-process + sample = self.unet.conv_norm_out(hidden_states) + sample = self.unet.conv_act(sample) + sample = self.unet.conv_out(sample) + sample = rearrange(sample, "(b m) c h w -> b m c h w", m=m) + return sample, pos_embed, decoded_sampled_features_by_student, decoded_sampled_features_by_teacher, alpha diff --git a/loomnet/systems/__init__.py b/loomnet/systems/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loomnet/systems/__pycache__/__init__.cpython-311.pyc b/loomnet/systems/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de76fccf7aaed84dfbaaf409b15988168b6f6bd7 Binary files /dev/null and b/loomnet/systems/__pycache__/__init__.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/base.cpython-311.pyc b/loomnet/systems/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d08a868299685fc1e22fa44c2d4663f1347fd3f Binary files /dev/null and b/loomnet/systems/__pycache__/base.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e18fe0120939872c23801009eeffff02f5d267f Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_1_to_infinity.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_1_to_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29d4e650db1a6fb4659f4eb088760da0d00f564b Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_1_to_infinity.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_for_geometric_loss.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_for_geometric_loss.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7978a2a59827db96da3ed534b37939e7ddc707f5 Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_for_geometric_loss.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_global.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_global.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..effc94b36e78c692483a3a83cb736bb0f52e9ed7 Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_global.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_infinity.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_infinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e953df0c58910eaf01d32c5752da8af127d88d38 Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_infinity.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_v8.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_v8.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1d4db8c27aaf5c88b73e74ba1bb036b9bb77bce Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_v8.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_with_distillation.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_with_distillation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e2ee0436584b6c41eb412eca4abbe3236b19c5d Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_with_distillation.cpython-311.pyc differ diff --git a/loomnet/systems/__pycache__/i2mv_system_with_projection.cpython-311.pyc b/loomnet/systems/__pycache__/i2mv_system_with_projection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86d9b286efbb03fb88dd10adff55fc261c6911eb Binary files /dev/null and b/loomnet/systems/__pycache__/i2mv_system_with_projection.cpython-311.pyc differ diff --git a/loomnet/systems/base.py b/loomnet/systems/base.py new file mode 100755 index 0000000000000000000000000000000000000000..2f2306b48f43173c2efed4694ecacd381da42854 --- /dev/null +++ b/loomnet/systems/base.py @@ -0,0 +1,34 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +from lightning import LightningModule + +from loomnet.utils.misc import load_module_weights, resolve_dir + + +class BaseSystem(LightningModule): + def __init__( + self, + save_dir: Optional[str] = None, + weights: Optional[str] = None, + weights_ignore_modules: Optional[List[str]] = None, + ) -> None: + super().__init__() + + self.save_dir = save_dir + + if weights is not None: + self.load_weights(weights, ignore_modules=weights_ignore_modules) + + def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): + state_dict, epoch, global_step = load_module_weights( + weights, ignore_modules=ignore_modules, map_location="cpu" + ) + self.load_state_dict(state_dict, strict=False) + + def setup(self, stage: str) -> None: + # set and make save dir for saving validation results, etc. + save_dir = resolve_dir(self.trainer, self.save_dir, "save") + save_dir = self.trainer.strategy.broadcast(save_dir) + self.save_dir = save_dir + os.makedirs(save_dir, exist_ok=True) diff --git a/loomnet/systems/i2mv_system.py b/loomnet/systems/i2mv_system.py new file mode 100644 index 0000000000000000000000000000000000000000..a409e2c8763de19f33e6bfad10c1b6fd42ca5a84 --- /dev/null +++ b/loomnet/systems/i2mv_system.py @@ -0,0 +1,655 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from loomnet.models.extras.geometry_loss.geometric_loss import VGGT_Geometric_Loss +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection + +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + use_geometric_loss: bool = False, + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.use_geometric_loss = use_geometric_loss + if use_geometric_loss: + #prepare geometric loss + self.geometry_loss = VGGT_Geometric_Loss() + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"]} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + loss = F.mse_loss(denoise, target) + + #geometry_loss = self.vggt_geometry_loss(noise_z, denoise, batch["images"], t) + + #loss = geometry_loss.mean() #loss*0.001 + geometry_loss.mean() + + self.log("train_loss", loss, prog_bar=True) + + return loss + + def vggt_geometry_loss(self, noise_latent, predicted_noise, grt_images, timesteps): + + B, num_views, c, d1, d2 = noise_latent.shape + + #STEP 1: extract only the predicted noise and the noisy latent z_t relative to views + predicted_noise = predicted_noise[:,:,0:4, :, :].view(B*num_views,c//2, d1, d2) + noise_latent = noise_latent[:,:,0:4, :, :].view(B*num_views,c//2, d1, d2) + + #STEP 2: predict original latent from noise + alphas_cumprod = self.scheduler.alphas_cumprod.to(predicted_noise.device).to(dtype=predicted_noise.dtype) + sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5 + sqrt_alpha_prod = sqrt_alpha_prod.flatten() + while len(sqrt_alpha_prod.shape) < len(predicted_noise.shape): + sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1) + + sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5 + sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten() + while len(sqrt_one_minus_alpha_prod.shape) < len(predicted_noise.shape): + sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1) + + #noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise + predicted_clean_latent = (noise_latent - sqrt_one_minus_alpha_prod * predicted_noise) / sqrt_alpha_prod + + #batch to original shape + predicted_clean_latent = predicted_clean_latent.view(B, num_views, c//2, d1, d2) + + #decode predicted latent into images + b, m = predicted_clean_latent.shape[0:2] + predicted_clean_latent = 1 / self.vae.config.scaling_factor * predicted_clean_latent + predicted_images = [] + for j in range(m): + image = self.vae.decode(predicted_clean_latent[:, j]).sample + predicted_images.append(image) + predicted_images = torch.stack(predicted_images, dim=1) + predicted_images = (predicted_images / 2 + 0.5) + + + return self.geometry_loss(grt_images, predicted_images) + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + noise_pred = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/systems/i2mv_system_1_to_infinity.py b/loomnet/systems/i2mv_system_1_to_infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..c7c26970b4553fa270d05ff5705f503db60dccfe --- /dev/null +++ b/loomnet/systems/i2mv_system_1_to_infinity.py @@ -0,0 +1,716 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection + +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class TVLoss(nn.Module): + """ + Total variance loss. + """ + + def __init__(self): + super().__init__() + + def numel_excluding_first_dim(self, x): + return x.numel() // x.shape[0] + + @torch.compile + def forward(self, x): + """ + Assume batched and channel first with inner sizes. + + Args: + x: [N, M, C, H, W] + + Returns: + Mean-reduced TV loss with element-level scaling. + """ + N, M, C, H, W = x.shape + x = x.reshape(N*M, C, H, W) + diff_i = x[..., 1:, :] - x[..., :-1, :] + diff_j = x[..., :, 1:] - x[..., :, :-1] + div_i = self.numel_excluding_first_dim(diff_i) + div_j = self.numel_excluding_first_dim(diff_j) + tv_i = diff_i.pow(2).sum(dim=[1,2,3]) / div_i + tv_j = diff_j.pow(2).sum(dim=[1,2,3]) / div_j + tv = tv_i + tv_j + batch_tv = tv.reshape(N, M).mean(dim=1) + all_tv = batch_tv.mean() + return all_tv + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + tv_weight: float = 0.001, + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + self.tv_loss_fn = TVLoss() + self.tv_weight = tv_weight + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"]} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise, planes = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + loss = F.mse_loss(denoise, target) + + triplane_loss = self.triplane_loss(planes) + + loss += triplane_loss + + self.log("train_loss", loss, prog_bar=True) + + return loss + + def triplane_loss(self, x): + + loss_tv = self.tv_loss_fn(x) + loss_tv = loss_tv * self.tv_weight + + return loss_tv + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + + import time + start = time.time() + + images_pred = self._generate_images(batch) + + end = time.time() + print(f"Tempo impiegato: {end - start} secondi") + + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_test_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + object_name=batch["obj_dir"] + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + noise_pred, _ = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + + ''' + NB: VALIDO SOLO PER BATCH SIZE 1 !!! + ''' + @torch.no_grad() + @rank_zero_only + def _save_test_image(self, images_pred, images, prompt, batch_idx, stage="validation", object_name=""): + + obj_dir = object_name[0] + save_dir = os.path.join(self.save_dir, obj_dir) + images_grt = rearrange(images, "b m c h w -> b m h w c") + images_pred = rearrange(images_pred, "b m h w c -> b m h w c") + os.makedirs(os.path.join(save_dir, "ground_truth"), exist_ok=True) + os.makedirs(os.path.join(save_dir, "predicted"), exist_ok=True) + + b, num_views, _,_,_ = images.shape + + for view_id in np.arange(num_views): + + im = Image.fromarray(images_grt[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "ground_truth"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + im = Image.fromarray(images_pred[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "predicted"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + full_image = np.concatenate([images, images_pred], axis=0) + + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"grt_vs_prediction.jpg", + ) + im.save(im_fp) + + + return im_fp + + + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/systems/i2mv_system_for_geometric_loss.py b/loomnet/systems/i2mv_system_for_geometric_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..41378c252f5e20936adbafaa8534660a0729cf8f --- /dev/null +++ b/loomnet/systems/i2mv_system_for_geometric_loss.py @@ -0,0 +1,816 @@ +import os +from typing import Any, Dict, List, Optional, Tuple +import math +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection +from loomnet.models.extras.geometry_loss.geometric_loss import VGGT_Geometric_Loss +from collections import deque +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class TVLoss(nn.Module): + """ + Total variance loss. + """ + + def __init__(self): + super().__init__() + + def numel_excluding_first_dim(self, x): + return x.numel() // x.shape[0] + + @torch.compile + def forward(self, x): + """ + Assume batched and channel first with inner sizes. + + Args: + x: [N, M, C, H, W] + + Returns: + Mean-reduced TV loss with element-level scaling. + """ + N, M, C, H, W = x.shape + x = x.reshape(N*M, C, H, W) + diff_i = x[..., 1:, :] - x[..., :-1, :] + diff_j = x[..., :, 1:] - x[..., :, :-1] + div_i = self.numel_excluding_first_dim(diff_i) + div_j = self.numel_excluding_first_dim(diff_j) + tv_i = diff_i.pow(2).sum(dim=[1,2,3]) / div_i + tv_j = diff_j.pow(2).sum(dim=[1,2,3]) / div_j + tv = tv_i + tv_j + batch_tv = tv.reshape(N, M).mean(dim=1) + all_tv = batch_tv.mean() + return all_tv + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + extras, + use_vggt_gradient_checkpoint: bool = True, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + tv_weight: float = 0.001, + type_of_geometric_loss: str = "token_based_geometric_loss", + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + + #VGGT LOSS + self.type_of_geometric_loss = type_of_geometric_loss + if type_of_geometric_loss == 'token_based_geometric_loss': + self.geometric_loss = VGGT_Geometric_Loss(target_layers=extras.token_based_geometric_loss.target_vggt_layers, use_gradient_checkpoint=use_vggt_gradient_checkpoint) + self.max_geometric_loss_weight = extras.token_based_geometric_loss.max_geometric_loss_weight + self.min_geometric_loss_weight = extras.token_based_geometric_loss.min_geometric_loss_weight + self.geometric_loss_scheduler = extras.token_based_geometric_loss.geometric_loss_scheduler + elif type_of_geometric_loss == 'register_token_based_geometric_loss': + self.geometric_loss = VGGT_Geometric_Loss(target_layers=extras.register_token_based_geometric_loss.target_vggt_layers, use_gradient_checkpoint=use_vggt_gradient_checkpoint, type_of_geometric_loss="register_token_based_geometric_loss") + self.max_geometric_loss_weight = extras.register_token_based_geometric_loss.max_geometric_loss_weight + self.min_geometric_loss_weight = extras.register_token_based_geometric_loss.min_geometric_loss_weight + self.geometric_loss_scheduler = extras.register_token_based_geometric_loss.geometric_loss_scheduler + elif type_of_geometric_loss == 'point_matching_geometric_loss': + self.geometric_loss = VGGT_Geometric_Loss(use_gradient_checkpoint=use_vggt_gradient_checkpoint, + type_of_geometric_loss="point_matching_geometric_loss", + num_query_points= extras.point_matching_geometric_loss.num_points, + num_views_to_check=extras.point_matching_geometric_loss.num_views_to_check) + self.max_geometric_loss_weight = extras.register_token_based_geometric_loss.max_geometric_loss_weight + self.min_geometric_loss_weight = extras.register_token_based_geometric_loss.min_geometric_loss_weight + self.geometric_loss_scheduler = extras.register_token_based_geometric_loss.geometric_loss_scheduler + + + self.rolling_window = deque(maxlen=100) + self.rolling_avg_list = [] + + self.tv_loss_fn = TVLoss() + self.tv_weight = tv_weight + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"]} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise, planes = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + loss = F.mse_loss(denoise, target) + + triplane_loss = self.triplane_loss(planes) + + geometric_loss = self.vggt_geometric_loss(noise_z, denoise, batch["images"], batch['k_near_indices'], t) + geometric_loss_weights = self.get_geometric_loss_weight(t[:,0], self.scheduler.config.num_train_timesteps, max_weight=self.max_geometric_loss_weight, min_weight=self.min_geometric_loss_weight, mode=self.geometric_loss_scheduler) + if self.type_of_geometric_loss == "token_based_geometric_loss" or self.type_of_geometric_loss == "register_token_based_geometric_loss": + geometric_loss = geometric_loss.view(latents.shape[0],latents.shape[1]) + + geometric_loss = (geometric_loss.mean(dim=1)*geometric_loss_weights).mean() + + self.rolling_window.append(geometric_loss.item()) + rolling_avg = sum(self.rolling_window) / len(self.rolling_window) + self.rolling_avg_list.append(rolling_avg) + + + loss += triplane_loss + geometric_loss + + self.log("train_loss", loss, prog_bar=True) + self.log(f"train_loss_geometric", geometric_loss, prog_bar=True) + self.log(f"train_loss_geometric_avg_window", rolling_avg, prog_bar=True) + + return loss + + def triplane_loss(self, x): + + loss_tv = self.tv_loss_fn(x) + loss_tv = loss_tv * self.tv_weight + + return loss_tv + + def get_geometric_loss_weight(self, t, T, max_weight=0.9, min_weight=0.001, mode="linear"): + if mode == "linear": + alpha = 1.0 - t / T # da 1 → 0 + elif mode == "cosine": + alpha = 0.5 * (1 + torch.cos(math.pi * t / T)) # da 1 → 0 + else: + raise ValueError("Unknown mode") + + return min_weight + (max_weight - min_weight) * alpha + + + def vggt_geometric_loss(self, noise_latent, predicted_noise, grt_images, k_near_indices, timesteps): + + + ''' + Reconstructs x_0 from x_t and the predicted noise eps_theta using the formula: + + x_0 = (x_t - sqrt(1 - alpha_bar_t) * eps_theta) / sqrt(alpha_bar_t) + ''' + + B, num_views, c, d1, d2 = noise_latent.shape + + #STEP 1: extract only the predicted noise and the noisy latent z_t relative to views + predicted_noise = predicted_noise[:,:,:4, :, :].view(B*num_views,c//2, d1, d2) + noise_latent = noise_latent[:,:,:4, :, :].view(B*num_views,c//2, d1, d2) + + #STEP 2: find 1-alpha_bar_t and alpha_bar_t + alphas_cumprod = self.scheduler.alphas_cumprod.to(predicted_noise.device) + alpha_bar_t = alphas_cumprod[timesteps.view(-1)].reshape(-1, 1, 1, 1) + + sqrt_alpha_bar = alpha_bar_t.sqrt() + sqrt_one_minus_alpha_bar = (1.0 - alpha_bar_t).sqrt() + + # Estimate x_0 + x0_pred = (noise_latent - sqrt_one_minus_alpha_bar * predicted_noise) / sqrt_alpha_bar + + #batch to original shape + predicted_clean_latent = x0_pred.view(B, num_views, c//2, d1, d2) + + #decode predicted latent into RGB images + b, m = predicted_clean_latent.shape[0:2] + predicted_clean_latent = 1 / self.vae.config.scaling_factor * predicted_clean_latent + predicted_images = [] + for j in range(m): + image = self.vae.decode(predicted_clean_latent[:, j]).sample + predicted_images.append(image) + predicted_images = torch.stack(predicted_images, dim=1) + predicted_images = (predicted_images / 2 + 0.5).clamp(0, 1) + + #grt images are between [-1,1], but VGGT expects images with values between [0,1] + grt_images = (grt_images + 1)/2 + + return self.geometric_loss(grt_images, predicted_images, k_near_indices) + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + + import time + start = time.time() + + images_pred = self._generate_images(batch) + + end = time.time() + print(f"Tempo impiegato: {end - start} secondi") + + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_test_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + object_name=batch["obj_dir"] + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + noise_pred, _ = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + + ''' + NB: VALIDO SOLO PER BATCH SIZE 1 !!! + ''' + @torch.no_grad() + @rank_zero_only + def _save_test_image(self, images_pred, images, prompt, batch_idx, stage="validation", object_name=""): + + obj_dir = object_name[0] + save_dir = os.path.join(self.save_dir, obj_dir) + images_grt = rearrange(images, "b m c h w -> b m h w c") + images_pred = rearrange(images_pred, "b m h w c -> b m h w c") + os.makedirs(os.path.join(save_dir, "ground_truth"), exist_ok=True) + os.makedirs(os.path.join(save_dir, "predicted"), exist_ok=True) + + b, num_views, _,_,_ = images.shape + + for view_id in np.arange(num_views): + + im = Image.fromarray(images_grt[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "ground_truth"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + im = Image.fromarray(images_pred[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "predicted"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + full_image = np.concatenate([images, images_pred], axis=0) + + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"grt_vs_prediction.jpg", + ) + im.save(im_fp) + + + return im_fp + + + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/systems/i2mv_system_global.py b/loomnet/systems/i2mv_system_global.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe169c3adcd2b9fe56bcc8011fbef300c725e56 --- /dev/null +++ b/loomnet/systems/i2mv_system_global.py @@ -0,0 +1,727 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection + +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class TVLoss(nn.Module): + """ + Total variance loss. + """ + + def __init__(self): + super().__init__() + + def numel_excluding_first_dim(self, x): + return x.numel() // x.shape[0] + + @torch.compile + def forward(self, x): + """ + Assume batched and channel first with inner sizes. + + Args: + x: [N, M, C, H, W] + + Returns: + Mean-reduced TV loss with element-level scaling. + """ + N, M, C, H, W = x.shape + x = x.reshape(N*M, C, H, W) + diff_i = x[..., 1:, :] - x[..., :-1, :] + diff_j = x[..., :, 1:] - x[..., :, :-1] + div_i = self.numel_excluding_first_dim(diff_i) + div_j = self.numel_excluding_first_dim(diff_j) + tv_i = diff_i.pow(2).sum(dim=[1,2,3]) / div_i + tv_j = diff_j.pow(2).sum(dim=[1,2,3]) / div_j + tv = tv_i + tv_j + batch_tv = tv.reshape(N, M).mean(dim=1) + all_tv = batch_tv.mean() + return all_tv + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + tv_weight: float = 0.001, + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + self.tv_loss_fn = TVLoss() + self.tv_weight = tv_weight + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def get_num_views(self, current_step, start_views=3, end_views=16, total_steps=5000): + if current_step >= total_steps: + return end_views + # Linear interpolation from start_views to end_views + progress = current_step / total_steps # da 0 a 1 + num_views = start_views + progress * (end_views - start_views) + # Arrotonda all'intero più vicino + return int(round(num_views)) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"]} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise, planes = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + loss = F.mse_loss(denoise, target) + + triplane_loss = self.triplane_loss(planes) + + loss += triplane_loss + + self.log("train_loss", loss, prog_bar=True) + + return loss + + def triplane_loss(self, x): + + loss_tv = self.tv_loss_fn(x) + loss_tv = loss_tv * self.tv_weight + + return loss_tv + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + + import time + start = time.time() + + images_pred = self._generate_images(batch) + + end = time.time() + print(f"Tempo impiegato: {end - start} secondi") + + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_test_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + object_name=batch["obj_dir"] + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + noise_pred, _ = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + + ''' + NB: VALIDO SOLO PER BATCH SIZE 1 !!! + ''' + @torch.no_grad() + @rank_zero_only + def _save_test_image(self, images_pred, images, prompt, batch_idx, stage="validation", object_name=""): + + obj_dir = object_name[0] + save_dir = os.path.join(self.save_dir, obj_dir) + images_grt = rearrange(images, "b m c h w -> b m h w c") + images_pred = rearrange(images_pred, "b m h w c -> b m h w c") + os.makedirs(os.path.join(save_dir, "ground_truth"), exist_ok=True) + os.makedirs(os.path.join(save_dir, "predicted"), exist_ok=True) + + b, num_views, _,_,_ = images.shape + + for view_id in np.arange(num_views): + + im = Image.fromarray(images_grt[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "ground_truth"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + im = Image.fromarray(images_pred[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "predicted"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + full_image = np.concatenate([images, images_pred], axis=0) + + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"grt_vs_prediction.jpg", + ) + im.save(im_fp) + + + return im_fp + + + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/systems/i2mv_system_v8.py b/loomnet/systems/i2mv_system_v8.py new file mode 100644 index 0000000000000000000000000000000000000000..fd15bf61c36b3720c28f11cd976d715d0d6dc1b2 --- /dev/null +++ b/loomnet/systems/i2mv_system_v8.py @@ -0,0 +1,754 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection + +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class TVLoss(nn.Module): + """ + Total variance loss. + """ + + def __init__(self): + super().__init__() + + def numel_excluding_first_dim(self, x): + return x.numel() // x.shape[0] + + @torch.compile + def forward(self, x): + """ + Assume batched and channel first with inner sizes. + + Args: + x: [N, M, C, H, W] + + Returns: + Mean-reduced TV loss with element-level scaling. + """ + N, M, C, H, W = x.shape + x = x.reshape(N*M, C, H, W) + diff_i = x[..., 1:, :] - x[..., :-1, :] + diff_j = x[..., :, 1:] - x[..., :, :-1] + div_i = self.numel_excluding_first_dim(diff_i) + div_j = self.numel_excluding_first_dim(diff_j) + tv_i = diff_i.pow(2).sum(dim=[1,2,3]) / div_i + tv_j = diff_j.pow(2).sum(dim=[1,2,3]) / div_j + tv = tv_i + tv_j + batch_tv = tv.reshape(N, M).mean(dim=1) + all_tv = batch_tv.mean() + return all_tv + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + tv_weight: float = 0.001, + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + self.tv_loss_fn = TVLoss() + self.tv_weight = tv_weight + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"], "global_step": self.global_step} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise, list_planes, pairs = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + diff_loss = F.mse_loss(denoise, target) + + triplane_loss = self.triplane_loss(list_planes) + + feature_loss = self.feature_distillation_loss(pairs) + + loss = diff_loss + triplane_loss + 0.5*feature_loss + + self.log("train_loss", loss, prog_bar=True) + self.log("diffusion_loss", diff_loss, prog_bar=True) + self.log("feature_loss", feature_loss, prog_bar=True) + self.log("triplane_loss", triplane_loss, prog_bar=True) + + + + return loss + + def triplane_loss(self, x): + + loss_tv = 0 + for p_i in x: + loss_tv += self.tv_loss_fn(p_i) + + loss_tv = (loss_tv/len(x)) * self.tv_weight + + return loss_tv + + def feature_distillation_loss(self, pairs, alpha=0.5): + """ + pairs: lista di tuple (global_latent_views, hidden_states) + es: [(G_bottleneck, H_bottleneck), (G_dec1, H_dec1), ...] + + alpha: peso per bilanciare MSE vs Cosine loss + 1.0 -> solo MSE + 0.0 -> solo Cosine + """ + total_loss = 0.0 + + for G, H in pairs: + # Flatten per cosine sim + G_flat = G.flatten(1) # [B, C*H*W] + H_flat = H.flatten(1) + + # Cosine similarity (1 - cos) + cos_loss = 1 - F.cosine_similarity(G_flat, H_flat, dim=-1).mean() + + # MSE + mse_loss = F.mse_loss(G, H) + + # Combinazione + loss = alpha * mse_loss + (1 - alpha) * cos_loss + total_loss += loss + + return total_loss / len(pairs) + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + + import time + start = time.time() + + images_pred = self._generate_images(batch) + + end = time.time() + print(f"Tempo impiegato: {end - start} secondi") + + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_test_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + object_name=batch["obj_dir"] + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices, "global_step": self.global_step} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + noise_pred, _ = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + + ''' + NB: VALIDO SOLO PER BATCH SIZE 1 !!! + ''' + @torch.no_grad() + @rank_zero_only + def _save_test_image(self, images_pred, images, prompt, batch_idx, stage="validation", object_name=""): + + obj_dir = object_name[0] + save_dir = os.path.join(self.save_dir, obj_dir) + images_grt = rearrange(images, "b m c h w -> b m h w c") + images_pred = rearrange(images_pred, "b m h w c -> b m h w c") + os.makedirs(os.path.join(save_dir, "ground_truth"), exist_ok=True) + os.makedirs(os.path.join(save_dir, "predicted"), exist_ok=True) + + b, num_views, _,_,_ = images.shape + + for view_id in np.arange(num_views): + + im = Image.fromarray(images_grt[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "ground_truth"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + im = Image.fromarray(images_pred[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "predicted"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + full_image = np.concatenate([images, images_pred], axis=0) + + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"grt_vs_prediction.jpg", + ) + im.save(im_fp) + + + return im_fp + + + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/systems/i2mv_system_with_distillation.py b/loomnet/systems/i2mv_system_with_distillation.py new file mode 100644 index 0000000000000000000000000000000000000000..b154fe9e49ec6ca179f8cc96c781256da218c6d6 --- /dev/null +++ b/loomnet/systems/i2mv_system_with_distillation.py @@ -0,0 +1,730 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection + +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class TVLoss(nn.Module): + """ + Total variance loss. + """ + + def __init__(self): + super().__init__() + + def numel_excluding_first_dim(self, x): + return x.numel() // x.shape[0] + + @torch.compile + def forward(self, x): + """ + Assume batched and channel first with inner sizes. + + Args: + x: [N, M, C, H, W] + + Returns: + Mean-reduced TV loss with element-level scaling. + """ + N, M, C, H, W = x.shape + x = x.reshape(N*M, C, H, W) + diff_i = x[..., 1:, :] - x[..., :-1, :] + diff_j = x[..., :, 1:] - x[..., :, :-1] + div_i = self.numel_excluding_first_dim(diff_i) + div_j = self.numel_excluding_first_dim(diff_j) + tv_i = diff_i.pow(2).sum(dim=[1,2,3]) / div_i + tv_j = diff_j.pow(2).sum(dim=[1,2,3]) / div_j + tv = tv_i + tv_j + batch_tv = tv.reshape(N, M).mean(dim=1) + all_tv = batch_tv.mean() + return all_tv + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + tv_weight: float = 0.001, + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + self.tv_loss_fn = TVLoss() + self.tv_weight = tv_weight + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"]} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + meta["global_step"] = self.global_step + meta["training"] = self.training + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise, planes, decoded_sampled_features_by_student, decoded_sampled_features_by_teacher, alpha = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + loss = F.mse_loss(denoise, target) + + triplane_loss = self.triplane_loss(planes) + + loss += triplane_loss + + self.log("train_loss", loss, prog_bar=True) + + if self.global_step > 37544: #TODO METTI 37000 nel config + # # Annealing + # anneal_steps = 7500 #TODO SOSTITUISCI 15000 nel config + # w_distill = 0.2*max(0.0, (self.global_step - 37544) / anneal_steps) #TODO sostituisci 37544 nel config + loss += F.mse_loss(decoded_sampled_features_by_student, decoded_sampled_features_by_teacher)*0.1 + self.log("alpha_distillation", alpha, prog_bar=True) + #self.log("w_distillation", w_distill, prog_bar=True) + + + return loss + + def triplane_loss(self, x): + + loss_tv = self.tv_loss_fn(x) + loss_tv = loss_tv * self.tv_weight + + return loss_tv + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + + import time + start = time.time() + + images_pred = self._generate_images(batch) + + end = time.time() + print(f"Tempo impiegato: {end - start} secondi") + + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_test_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + object_name=batch["obj_dir"] + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + + meta["global_step"] = self.global_step + meta["training"] = self.training + noise_pred, _, _, _, _ = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + + ''' + NB: VALIDO SOLO PER BATCH SIZE 1 !!! + ''' + @torch.no_grad() + @rank_zero_only + def _save_test_image(self, images_pred, images, prompt, batch_idx, stage="validation", object_name=""): + + obj_dir = object_name[0] + save_dir = os.path.join(self.save_dir, obj_dir) + images_grt = rearrange(images, "b m c h w -> b m h w c") + images_pred = rearrange(images_pred, "b m h w c -> b m h w c") + os.makedirs(os.path.join(save_dir, "ground_truth"), exist_ok=True) + os.makedirs(os.path.join(save_dir, "predicted"), exist_ok=True) + + b, num_views, _,_,_ = images.shape + + for view_id in np.arange(num_views): + + im = Image.fromarray(images_grt[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "ground_truth"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + im = Image.fromarray(images_pred[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "predicted"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + full_image = np.concatenate([images, images_pred], axis=0) + + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"grt_vs_prediction.jpg", + ) + im.save(im_fp) + + + return im_fp + + + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/systems/i2mv_system_with_projection.py b/loomnet/systems/i2mv_system_with_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe169c3adcd2b9fe56bcc8011fbef300c725e56 --- /dev/null +++ b/loomnet/systems/i2mv_system_with_projection.py @@ -0,0 +1,727 @@ +import os +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +import torchvision as tv +from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel +from einops import rearrange, repeat +from lightning import LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only +from PIL import Image +from torch import nn +from torchmetrics import MaxMetric, MeanMetric +from torchmetrics.image import PeakSignalNoiseRatio +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.image.ssim import StructuralSimilarityIndexMeasure +from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection +from extern.zero123 import CLIPCameraProjection +from extern.zero123_official import CCProjection + +from .base import BaseSystem + +BASE_MODEL_OPTIONS = [ + "bennyguo/zero123-xl-diffusers", + "kxic/zero123-xl", + "ashawkey/stable-zero123-diffusers", +] + + +class TVLoss(nn.Module): + """ + Total variance loss. + """ + + def __init__(self): + super().__init__() + + def numel_excluding_first_dim(self, x): + return x.numel() // x.shape[0] + + @torch.compile + def forward(self, x): + """ + Assume batched and channel first with inner sizes. + + Args: + x: [N, M, C, H, W] + + Returns: + Mean-reduced TV loss with element-level scaling. + """ + N, M, C, H, W = x.shape + x = x.reshape(N*M, C, H, W) + diff_i = x[..., 1:, :] - x[..., :-1, :] + diff_j = x[..., :, 1:] - x[..., :, :-1] + div_i = self.numel_excluding_first_dim(diff_i) + div_j = self.numel_excluding_first_dim(diff_j) + tv_i = diff_i.pow(2).sum(dim=[1,2,3]) / div_i + tv_j = diff_j.pow(2).sum(dim=[1,2,3]) / div_j + tv = tv_i + tv_j + batch_tv = tv.reshape(N, M).mean(dim=1) + all_tv = batch_tv.mean() + return all_tv + + +class I2MVSystem(BaseSystem): + def __init__( + self, + mv_model: torch.nn.Module, + lr: float, + base_model_id: str = "bennyguo/zero123-xl-diffusers", + variant: Optional[str] = None, + cfg: float = 0.1, # classifier free guidance + diffusion_timesteps: int = 50, + guidance_scale: float = 3.0, + num_val_dataloaders: int = 2, + num_test_dataloaders: int = 2, + report_to: str = "wandb", + compile: bool = False, + tv_weight: float = 0.001, + **kwargs, + ) -> None: + super().__init__(**kwargs) + + # this line allows to access init params with 'self.hparams' attribute + # also ensures init params will be stored in ckpt + self.save_hyperparameters(logger=False, ignore=["mv_model"]) + + # check pretrained base model + assert ( + base_model_id in BASE_MODEL_OPTIONS + ), f"base_model_id must be one of {BASE_MODEL_OPTIONS}" + + # prepare pretrain image encoder, vae, unet, scheduler for diffusion + pipe_kwargs = {} + if variant is not None: + pipe_kwargs["variant"] = variant + unet = UNet2DConditionModel.from_pretrained( + base_model_id, subfolder="unet", **pipe_kwargs + ) + self.image_encoder = CLIPVisionModelWithProjection.from_pretrained( + base_model_id, subfolder="image_encoder", **pipe_kwargs + ) + self.vae = AutoencoderKL.from_pretrained( + base_model_id, subfolder="vae", **pipe_kwargs + ) + self.feature_extractor = CLIPImageProcessor.from_pretrained( + base_model_id, subfolder="feature_extractor", **pipe_kwargs + ) + self.scheduler = DDIMScheduler.from_pretrained( + base_model_id, subfolder="scheduler" + ) + self.image_encoder.eval() + self.vae.eval() + self.image_encoder.requires_grad_(False) + self.vae.requires_grad_(False) + + # prepare clip camera projection for different base models + if base_model_id.endswith("diffusers"): + self.clip_camera_projection = CLIPCameraProjection.from_pretrained( + base_model_id, subfolder="clip_camera_projection", **pipe_kwargs + ) + else: + self.clip_camera_projection = CCProjection.from_pretrained( + base_model_id, subfolder="cc_projection", **pipe_kwargs + ) + + # prepare model + self.mv_model = mv_model(unet=unet) + try: + self.mv_model.set_use_memory_efficient_attention_xformers(True) + except Exception as e: + print(f"Could not enable xFormers: {e}") + + self.trainable_parameters = list(self.mv_model.trainable_parameters) + + # metric objects for calculating and averaging accuracy across batches + self.val_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_val_dataloaders)] + ) + self.val_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_val_dataloaders)] + ) + self.val_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_val_dataloaders) + ] + ) + self.val_psnr_best = nn.ModuleList( + [MaxMetric() for _ in range(num_val_dataloaders)] + ) + + self.test_psnr = nn.ModuleList( + [PeakSignalNoiseRatio(data_range=1.0) for _ in range(num_test_dataloaders)] + ) + self.test_ssim = nn.ModuleList( + [StructuralSimilarityIndexMeasure() for _ in range(num_test_dataloaders)] + ) + self.test_lpips = nn.ModuleList( + [ + LearnedPerceptualImagePatchSimilarity(normalize=True) + for _ in range(num_test_dataloaders) + ] + ) + + self.tv_loss_fn = TVLoss() + self.tv_weight = tv_weight + + def setup(self, stage: str) -> None: + super().setup(stage) + + if self.hparams.compile and stage == "fit": + self.mv_model = torch.compile(self.mv_model) + + def configure_optimizers(self): + """Configure optimizers and learning rate schedulers for training.""" + param_groups = [] + for params, lr_scale in self.trainable_parameters: + param_groups.append({"params": params, "lr": self.hparams.lr * lr_scale}) + + optimizer = torch.optim.AdamW(param_groups) + return optimizer + + def forward(self, latents, timestep, prompt_embd, meta) -> torch.Tensor: + return self.mv_model(latents, timestep, prompt_embd, meta) + + def get_num_views(self, current_step, start_views=3, end_views=16, total_steps=5000): + if current_step >= total_steps: + return end_views + # Linear interpolation from start_views to end_views + progress = current_step / total_steps # da 0 a 1 + num_views = start_views + progress * (end_views - start_views) + # Arrotonda all'intero più vicino + return int(round(num_views)) + + def on_train_start(self) -> None: + """Lightning hook that is called when training begins.""" + # by default lightning executes validation step sanity checks before training starts, + # so it's worth to make sure validation metrics don't store results from these checks + for metrics in [ + self.val_psnr, + self.val_ssim, + self.val_lpips, + self.val_psnr_best, + ]: + if isinstance(metrics, nn.ModuleList): + for metric in metrics: + metric.reset() + else: + metrics.reset() + + def training_step(self, batch, batch_idx): + meta = {"cameras": batch["cameras"], "k_near_indices": batch["k_near_indices"]} + image_0 = batch["image_0"] # cond image (b c h w) + elevations = batch["elevations"] # (b f 1) + azimuths = batch["azimuths"] # (b f 1) + distances = batch["distances"] # (b f 1) + + ''' + Find latent representation (4x32x32) for ref view + + 1) ref_view -> AutoencoderKL -> latent_ref (4, 32, 32) + 2) replicate each latent_ref for each view -> latent_image (16, 4, 32, 32) + + + Find embedding of the relative position of each of the 16 views (16, 1, 768) respect to the ref view (image_embeddings) + + 3) ref_view -> ClipVisionModelWithProjection -> cls_ref_view (768) + 4) for each view: + pos_view_i [relative elevation, sin(relative azimuth), cos(relative azimuth), ref view elevation, cls_ref_view ] -> ClipCameraProjection -> image_embedding (1, 768) + + ''' + + + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # (b f 1 768) + + if torch.rand(1) < self.hparams.cfg: + latent_image = torch.zeros_like(latent_image) + + ''' + For each view find the latent representation (16, 4,32,32) + + ''' + latents = self._encode_image(batch["images"], self.vae) + + + ''' + Sample a timestep of diffusion + Make noisy the latent of each view (modulated with t) + Concat the noisy latent of each view with the clean latent of the ref view --> noise_z = [noisy_latent_view, latent_ref_view] (16, 8, 32, 32) + ''' + + t = torch.randint( + 0, + self.scheduler.config.num_train_timesteps, + (latents.shape[0],), + device=latents.device, + ).long() + + noise = torch.randn_like(latents) + noise_z = self.scheduler.add_noise(latents, noise, t) + noise_z = torch.cat([noise_z, latent_image], dim=2) # b x f x 8 + t = t[:, None].repeat(1, latents.shape[1]) + + denoise, planes = self.forward(noise_z, t, image_embeddings, meta) + target = noise + + # eps mode + loss = F.mse_loss(denoise, target) + + triplane_loss = self.triplane_loss(planes) + + loss += triplane_loss + + self.log("train_loss", loss, prog_bar=True) + + return loss + + def triplane_loss(self, x): + + loss_tv = self.tv_loss_fn(x) + loss_tv = loss_tv * self.tv_weight + + return loss_tv + + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + images_pred = self._generate_images(batch) + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # compute image & save + image_fp = self._save_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="validation", + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.val_psnr[dataloader_idx](images_gt_, images_pred_) + self.val_ssim[dataloader_idx](images_gt_, images_pred_) + self.val_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"val_psnr_{dataloader_idx}", + self.val_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_ssim_{dataloader_idx}", + self.val_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"val_lpips_{dataloader_idx}", + self.val_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_validation_epoch_end(self) -> None: + "Lightning hook that is called when a validation epoch ends." + for i in range(self.hparams.num_val_dataloaders): + acc = self.val_psnr[i].compute() # get current val acc + self.val_psnr_best[i](acc) # update best so far val acc + # log `val_acc_best` as a value through `.compute()` method, instead of as a metric object + # otherwise metric would be reset by lightning after each epoch + self.log( + f"val_psnr_best_{i}", + self.val_psnr_best[i].compute(), + sync_dist=True, + prog_bar=True, + ) + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("validation") + + def test_step(self, batch, batch_idx, dataloader_idx=0): + + import time + start = time.time() + + images_pred = self._generate_images(batch) + + end = time.time() + print(f"Tempo impiegato: {end - start} secondi") + + images = ((batch["images"] / 2 + 0.5) * 255).cpu().numpy().astype(np.uint8) + + # save images + image_fp = self._save_test_image( + images_pred, + images, + batch["caption"], + f"{dataloader_idx}_{batch_idx}_{self.global_rank}", + stage="test", + object_name=batch["obj_dir"] + ) + + # update and log metrics + images_gt_ = rearrange( + batch["images"] / 2 + 0.5, "b m c h w -> (b m) c h w" + ).float() + images_pred_ = torch.tensor( + rearrange(images_pred, "b m h w c -> (b m) c h w") / 255.0, + dtype=torch.float32, + ).to(images_gt_.device) + + self.test_psnr[dataloader_idx](images_gt_, images_pred_) + self.test_ssim[dataloader_idx](images_gt_, images_pred_) + self.test_lpips[dataloader_idx](images_gt_, images_pred_) + self.log( + f"test_psnr_{dataloader_idx}", + self.test_psnr[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_ssim_{dataloader_idx}", + self.test_ssim[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + self.log( + f"test_lpips_{dataloader_idx}", + self.test_lpips[dataloader_idx], + on_step=False, + on_epoch=True, + prog_bar=True, + add_dataloader_idx=False, + ) + + return image_fp + + def on_test_epoch_end(self) -> None: + """Lightning hook that is called when a test epoch ends.""" + + # log images + if self.hparams.report_to == "wandb": + self._log_to_wandb("test") + + @torch.no_grad() + def _encode_cond(self, image, elevation, azimuth, distance): + (b, f, _), device = elevation.shape, elevation.device + latent_image = self._encode_image(image, self.vae, False) + latent_image = repeat(latent_image, "b 1 c h w -> b f c h w", f=f) + # image to PIL image + image = (image + 1.0) / 2.0 + pil_images = [tv.transforms.ToPILImage()(img) for img in image] + image = self.feature_extractor( + images=pil_images, return_tensors="pt" + ).pixel_values + image = image.to(device) + image_embedding = self.image_encoder(image).image_embeds + image_embedding = image_embedding.unsqueeze(1) + camera_embeddings = torch.stack( + [ + elevation, + torch.sin(azimuth), + torch.cos(azimuth), + distance, + ], + dim=-1, + ) + + image_embeddings = repeat( + image_embedding, "b n c -> b f n c", f=f + ) # (b f 1 768) + image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1) + + image_embeddings = rearrange(image_embeddings, "b f n c -> (b f) n c") + image_embeddings = self.clip_camera_projection(image_embeddings) + + image_embeddings = rearrange(image_embeddings, "(b f) n c -> b f n c", b=b) + return latent_image, image_embeddings + + @torch.no_grad() + def _encode_image(self, x_input, vae, scale=True): + b = x_input.shape[0] + + x_input = x_input.reshape( + -1, x_input.shape[-3], x_input.shape[-2], x_input.shape[-1] + ) + z = vae.encode(x_input).latent_dist # (bs, 2, 4, 64, 64) + + z = z.sample() + z = z.reshape( + b, -1, z.shape[-3], z.shape[-2], z.shape[-1] + ) # (bs, 2, 4, 64, 64) + + # use the scaling factor from the vae config + if scale: + z = z * vae.config.scaling_factor + z = z.float() + return z + + @torch.no_grad() + def _decode_latent(self, latents, vae): + b, m = latents.shape[0:2] + latents = 1 / vae.config.scaling_factor * latents + images = [] + for j in range(m): + image = vae.decode(latents[:, j]).sample + images.append(image) + image = torch.stack(images, dim=1) + image = (image / 2 + 0.5).clamp(0, 1) + image = image.cpu().permute(0, 1, 3, 4, 2).float().numpy() + image = (image * 255).round().astype("uint8") + + return image + + + def _gen_cls_free_guide_pair( + self, latents, latent_image, timestep, prompt_embd, batch + ): + latents = torch.cat([latents] * 2) + latent_image = torch.cat([torch.zeros_like(latent_image), latent_image]) + + latents = torch.cat([latents, latent_image], dim=2) + timestep = torch.cat([timestep] * 2) + + cameras = torch.cat([batch["cameras"]] * 2) + k_near_indices = torch.cat([batch["k_near_indices"]] * 2) + meta = {"cameras": cameras, "k_near_indices": k_near_indices} + + return latents, timestep, prompt_embd, meta + + @torch.no_grad() + def _forward_cls_free( + self, latents_high_res, latent_image, _timestep, prompt_embd, batch, model + ): + latents, _timestep, _prompt_embd, meta = self._gen_cls_free_guide_pair( + latents_high_res, latent_image, _timestep, prompt_embd, batch + ) + noise_pred, _ = model(latents, _timestep, _prompt_embd, meta) + + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.hparams.guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + return noise_pred + + @torch.no_grad() + def _generate_images(self, batch): + image_0 = batch["image_0"] # cond image b x c x h x w + elevations = batch["elevations"] # b x f x 1 + azimuths = batch["azimuths"] # b x f x 1 + distances = batch["distances"] # b x f x 1 + + bs, m, _ = elevations.shape + bs, _, h, w = image_0.shape + device = image_0.device + latents = torch.randn(bs, m, 4, h // 8, w // 8, device=device) + + latent_image, image_embeddings = self._encode_cond( + image_0, elevations, azimuths, distances + ) # b x f x 1 x 768 + negative_prompt_embeds = torch.zeros_like(image_embeddings) + + image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings]) + + self.scheduler.set_timesteps(self.hparams.diffusion_timesteps, device=device) + timesteps = self.scheduler.timesteps + + for i, t in enumerate(timesteps): + _timestep = torch.cat([t[None, None]] * m, dim=1) + _timestep = _timestep.expand(bs, -1) + + noise_pred = self._forward_cls_free( + latents, + latent_image, + _timestep, + image_embeddings, + batch, + self.mv_model, + ) + + latents = self.scheduler.step(noise_pred, t, latents).prev_sample + images_pred = self._decode_latent(latents, self.vae) + return images_pred + + @torch.no_grad() + @rank_zero_only + def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + + b, num_views, c, d1, d2 = images.shape + + save_dir = self.save_dir + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + + full_image = np.zeros(shape=(2*b*d1,num_views*d2, 3), dtype=np.uint8) + + offset_full = 0 + for batch_i in range(b): + start = offset_full + end = offset_full + d1 + #insert grt + full_image[start:end] = images[batch_i*d1:batch_i*d1 + d1] + #insert prediction + full_image[end:end + d1] = images_pred[batch_i*d1:batch_i*d1 + d1] + offset_full += d1*2 + + + with open( + os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + ) as f: + f.write("\n".join(prompt)) + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + ) + im.save(im_fp) + + # add image to logger + if self.hparams.report_to == "tensorboard": + log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + self.logger.experiment.add_image( + f"{stage}/{self.global_step}_{batch_idx}", + log_image, + global_step=self.global_step, + ) + + return im_fp + + + ''' + NB: VALIDO SOLO PER BATCH SIZE 1 !!! + ''' + @torch.no_grad() + @rank_zero_only + def _save_test_image(self, images_pred, images, prompt, batch_idx, stage="validation", object_name=""): + + obj_dir = object_name[0] + save_dir = os.path.join(self.save_dir, obj_dir) + images_grt = rearrange(images, "b m c h w -> b m h w c") + images_pred = rearrange(images_pred, "b m h w c -> b m h w c") + os.makedirs(os.path.join(save_dir, "ground_truth"), exist_ok=True) + os.makedirs(os.path.join(save_dir, "predicted"), exist_ok=True) + + b, num_views, _,_,_ = images.shape + + for view_id in np.arange(num_views): + + im = Image.fromarray(images_grt[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "ground_truth"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + im = Image.fromarray(images_pred[0,view_id ]) + im_fp = os.path.join( + os.path.join(save_dir, "predicted"), + f"{view_id}.jpg", + ) + im.save(im_fp) + + + images = rearrange(images, "b m c h w -> (b h) (m w) c") + images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + full_image = np.concatenate([images, images_pred], axis=0) + + + im = Image.fromarray(full_image) + im_fp = os.path.join( + save_dir, + f"grt_vs_prediction.jpg", + ) + im.save(im_fp) + + + return im_fp + + + + # @torch.no_grad() + # @rank_zero_only + # def _save_image(self, images_pred, images, prompt, batch_idx, stage="validation"): + # save_dir = self.save_dir + # images = rearrange(images, "b m c h w -> (b h) (m w) c") + # images_pred = rearrange(images_pred, "b m h w c -> (b h) (m w) c") + # full_image = np.concatenate([images, images_pred], axis=0) + + # with open( + # os.path.join(save_dir, f"{stage}_{self.global_step}_{batch_idx}.txt"), "w" + # ) as f: + # f.write("\n".join(prompt)) + + # im = Image.fromarray(full_image) + # im_fp = os.path.join( + # save_dir, + # f"{stage}_{self.global_step}_{batch_idx}--{prompt[0].replace(' ', '_').replace('/', '_')}.jpg", + # ) + # im.save(im_fp) + + # # add image to logger + # if self.hparams.report_to == "tensorboard": + # log_image = torch.tensor(full_image / 255.0).permute(2, 0, 1).float().cpu() + # self.logger.experiment.add_image( + # f"{stage}/{self.global_step}_{batch_idx}", + # log_image, + # global_step=self.global_step, + # ) + + # return im_fp + + @torch.no_grad() + @rank_zero_only + def _log_to_wandb(self, stage): + import wandb + + num_dataloaders = ( + self.hparams.num_val_dataloaders + if stage == "validation" + else self.hparams.num_test_dataloaders + ) + for i in range(num_dataloaders): + captions, images = [], [] + # get images which start with {stage}_{self.global_step}_{self.dataloader_idx} from self.save_dir + for f in os.listdir(self.save_dir): + if f.startswith(f"{stage}_{self.global_step}_{i}") and f.endswith( + ".jpg" + ): + captions.append(f) + images.append(os.path.join(self.save_dir, f)) + + self.logger.experiment.log( + { + f"{stage}_{i}": [ + wandb.Image(im_fp, caption=caption) + for im_fp, caption in zip(images, captions) + ] + }, + step=self.global_step, + ) diff --git a/loomnet/utils/__init__.py b/loomnet/utils/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..58b447cf13fabb3601825c66f29a23ef6ec2e8d4 --- /dev/null +++ b/loomnet/utils/__init__.py @@ -0,0 +1,7 @@ +from .logger_utils import RankedLogger, log_hyperparameters +from .config import ExperimentConfig, load_config +from .instantiators import ( + instantiate_from_config, + instantiate_callbacks, + instantiate_loggers, +) diff --git a/loomnet/utils/__pycache__/__init__.cpython-311.pyc b/loomnet/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c03b6d3b2fcc7de4137e837586a5dddf1b8839fd Binary files /dev/null and b/loomnet/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/callbacks.cpython-311.pyc b/loomnet/utils/__pycache__/callbacks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef1492cd4a0188cce327ff0b617e15356952f7b9 Binary files /dev/null and b/loomnet/utils/__pycache__/callbacks.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/config.cpython-311.pyc b/loomnet/utils/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c28e67be066d7fb0c824440ea37767805b15e6f3 Binary files /dev/null and b/loomnet/utils/__pycache__/config.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/generic_utils.cpython-311.pyc b/loomnet/utils/__pycache__/generic_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42c39325c27a3f2a7536f3cadbcb5adddc5efe81 Binary files /dev/null and b/loomnet/utils/__pycache__/generic_utils.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/instantiators.cpython-311.pyc b/loomnet/utils/__pycache__/instantiators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cfd25ed4c2a69ebe54eeadfe962f5d305c7f1a6 Binary files /dev/null and b/loomnet/utils/__pycache__/instantiators.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/logger_utils.cpython-311.pyc b/loomnet/utils/__pycache__/logger_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bd81ada858ae2981f3a7bb4c29b20eb2e686d35 Binary files /dev/null and b/loomnet/utils/__pycache__/logger_utils.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/media.cpython-311.pyc b/loomnet/utils/__pycache__/media.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a46e4466d3a87e2f64aea7a3be46f4bc9b5b5fe2 Binary files /dev/null and b/loomnet/utils/__pycache__/media.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/misc.cpython-311.pyc b/loomnet/utils/__pycache__/misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da32eb2fb5a65023d7e93ce804b1c323edad2ff8 Binary files /dev/null and b/loomnet/utils/__pycache__/misc.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/ops.cpython-311.pyc b/loomnet/utils/__pycache__/ops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed37c4abd8f719e93708aa691480e1e01bcf33ec Binary files /dev/null and b/loomnet/utils/__pycache__/ops.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/pose.cpython-311.pyc b/loomnet/utils/__pycache__/pose.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26a4943f4bb525a6eb0d2b68a3d8f17b1aa1401f Binary files /dev/null and b/loomnet/utils/__pycache__/pose.cpython-311.pyc differ diff --git a/loomnet/utils/__pycache__/project.cpython-311.pyc b/loomnet/utils/__pycache__/project.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6371d5077156c2131e4ade963c200ac46f170625 Binary files /dev/null and b/loomnet/utils/__pycache__/project.cpython-311.pyc differ diff --git a/loomnet/utils/callbacks.py b/loomnet/utils/callbacks.py new file mode 100755 index 0000000000000000000000000000000000000000..0748cfb27cd74f499b59b30b158092fad71f00f0 --- /dev/null +++ b/loomnet/utils/callbacks.py @@ -0,0 +1,102 @@ +from typing import Optional + +import os +import shutil +from omegaconf import OmegaConf, DictConfig + +from lightning import Trainer, Callback, LightningModule +from lightning_utilities.core.rank_zero import rank_zero_only + +from .config import get_hparams, dump_config +from .misc import resolve_dir + + +class SavePathCallback(Callback): + def __init__(self, dirpath: Optional[str] = None, sub_dir: Optional[str] = None): + super().__init__() + + self.dirpath = dirpath + self.sub_dir = sub_dir + + def setup(self, trainer: Trainer, pl_module: LightningModule, stage: str): + dirpath = self.__resolve_dir(trainer) + self.savedir = dirpath + + def __resolve_dir(self, trainer: Trainer) -> str: + """Determines save directory at runtime. Reference attributes from the trainer's logger to + determine where to save. The path for saving weights is set in this priority: + + 1. The ``Callback``'s ``dirpath`` if passed in + 2. The ``Logger``'s ``log_dir`` if the trainer has loggers + 3. The ``Trainer``'s ``default_root_dir`` if the trainer has no loggers + + The path gets extended with subdirectory ``sub_dir`` if passed in. + + """ + return resolve_dir(trainer, self.dirpath, self.sub_dir) + + +class VersionedCallback(Callback): + def __init__(self, dirpath, version=None, use_version=True): + self.dirpath = dirpath + self._version = version + self.use_version = use_version + + @property + def version(self) -> int: + """Get the experiment version. + + Returns: + The experiment version if specified else the next version. + """ + if self._version is None: + self._version = self._get_next_version() + return self._version + + def _get_next_version(self): + existing_versions = [] + if os.path.isdir(self.dirpath): + for f in os.listdir(self.dirpath): + bn = os.path.basename(f) + if bn.startswith("version_"): + dir_ver = os.path.splitext(bn)[0].split("_")[1].replace("/", "") + existing_versions.append(int(dir_ver)) + if len(existing_versions) == 0: + return 0 + return max(existing_versions) + 1 + + @property + def savedir(self): + if not self.use_version: + return self.dirpath + return os.path.join( + self.dirpath, + self.version + if isinstance(self.version, str) + else f"version_{self.version}", + ) + + +class ConfigSnapshotCallback(SavePathCallback): + def __init__( + self, + config: DictConfig, + config_path: Optional[str] = None, + dirpath: Optional[str] = None, + sub_dir: Optional[str] = "configs", + ): + super().__init__(dirpath, sub_dir) + self.config = config + self.config_path = config_path + + @rank_zero_only + def save_config_snapshot(self, pl_module: LightningModule = None): + os.makedirs(self.savedir, exist_ok=True) + hparams = get_hparams(self.config) + dump_config(os.path.join(self.savedir, "parsed.yaml"), hparams) + + if self.config_path: + shutil.copy(self.config_path, os.path.join(self.savedir, "raw.yaml")) + + def on_fit_start(self, trainer, pl_module: LightningModule): + self.save_config_snapshot(pl_module) diff --git a/loomnet/utils/config.py b/loomnet/utils/config.py new file mode 100755 index 0000000000000000000000000000000000000000..80fd769cd629a87fe8acff985e0d6d6989d57c38 --- /dev/null +++ b/loomnet/utils/config.py @@ -0,0 +1,75 @@ +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Union +from omegaconf import OmegaConf, DictConfig + + +@dataclass +class ExperimentConfig: + name: str = "default" + tags: List[str] = field(default_factory=list) + description: str = "" + version: Optional[str] = None + output_dir: str = "outputs/" + + seed: int = 42 + resume: Optional[str] = None + + data: Dict[str, Any] = field(default_factory=dict) + system: Dict[str, Any] = field(default_factory=dict) + trainer: Dict[str, Any] = field(default_factory=dict) + callbacks: Optional[Dict[str, Any]] = None + logger: Optional[Dict[str, Any]] = None + + train: bool = True + test: bool = True + + extras: Optional[Dict[str, Any]] = None + save_config: bool = True + + +def load_config(*yamls: str, cli_args: list = [], from_string=False, **kwargs) -> Any: + if from_string: + yaml_confs = [OmegaConf.create(s) for s in yamls] + else: + yaml_confs = [OmegaConf.load(f) for f in yamls] + cli_conf = OmegaConf.from_cli(cli_args) + cfg = OmegaConf.merge(*yaml_confs, cli_conf, kwargs) + OmegaConf.resolve(cfg) + assert isinstance(cfg, DictConfig) + scfg = parse_structured(ExperimentConfig, cfg) + return scfg + + +def dump_config(path: str, config) -> None: + with open(path, "w") as fp: + OmegaConf.save(config=config, f=fp) + + +def parse_structured(fields: Any, cfg: Optional[Union[dict, DictConfig]] = None) -> Any: + scfg = OmegaConf.structured(fields(**cfg)) + return scfg + + +def get_hparams(cfg: DictConfig, model=None): + hparams = OmegaConf.to_container(cfg) + + if model: + # save number of model parameters + total = sum(p.numel() for p in model.parameters()) + trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) + non_trainable = sum( + p.numel() for p in model.parameters() if not p.requires_grad + ) + + hparams.update( + { + "model/params/total": total, + "model/params/trainable": trainable, + "model/params/non_trainable": non_trainable, + "model/params/total_mb": total * 4 / 1024**2, + "model/params/trainable_mb": trainable * 4 / 1024**2, + "model/params/non_trainable_mb": non_trainable * 4 / 1024**2, + } + ) + + return hparams diff --git a/loomnet/utils/generic_utils.py b/loomnet/utils/generic_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..830130ae045e10c971af1a0252f5bf51ad38fc66 --- /dev/null +++ b/loomnet/utils/generic_utils.py @@ -0,0 +1,123 @@ + +import numpy as np +import torch + +def fibonacci_sphere(num_points: int, radius: float = 1.0): + ga = (3 - np.sqrt(5)) * np.pi # golden angle in radians + + theta = ga * np.arange(num_points) + z = np.linspace(1/num_points - 1, 1 - 1/num_points, num_points) + r = np.sqrt(1 - z * z) + + x = r * np.cos(theta) + y = r * np.sin(theta) + + # Combine into a (num_points, 3) array and scale by radius + points = np.vstack((x, y, z)).T * radius + return points + + + +def ray_sample(cam2world_matrix, intrinsics, grid): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + + #move grid from (B*num_views, d1, d2, 2) --> (B*num_views, d1*d2, 2) + B_and_num_views, d1, d2, _ = grid.shape + N, M = cam2world_matrix.shape[0], d1**2 + grid = grid.view(B_and_num_views, d1*d2, 2) + #move grid from [-1, 1] to [0, 1] + uv = (grid + 1)/2 + # uv = torch.stack( + # torch.meshgrid( + # torch.arange( + # resolution, dtype=torch.float32, device=cam2world_matrix.device + # ), + # torch.arange( + # resolution, dtype=torch.float32, device=cam2world_matrix.device + # ), + # indexing="ij", + # ) + # ) * (1.0 / resolution) + (0.5 / resolution) + # uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs + + + +def intersect_ray_sphere_batch(ray_origins, ray_dirs, sphere_center, sphere_radius): + """ + ray_origins: [B, N, 3] + ray_dirs: [B, N, 3] + sphere_center: [3] oppure [1, 1, 3] + sphere_radius: float o tensor scalare + """ + # Assicura shape broadcastabili + if sphere_center.ndim == 1: + sphere_center = sphere_center.view(1, 1, 3) + if isinstance(sphere_radius, float): + sphere_radius = torch.tensor(sphere_radius, dtype=ray_origins.dtype, device=ray_origins.device) + + # OC: vettore dall'origine del raggio al centro della sfera + oc = ray_origins - sphere_center # [B, N, 3] + + a = torch.sum(ray_dirs ** 2, dim=-1) # [B, N] + b = 2.0 * torch.sum(oc * ray_dirs, dim=-1) # [B, N] + c = torch.sum(oc ** 2, dim=-1) - sphere_radius**2 # [B, N] + + discriminant = b**2 - 4*a*c # [B, N] + valid = discriminant >= 0 # [B, N] + + # Prepara t come zeri + t = torch.zeros_like(a) # [B, N] + sqrt_disc = torch.sqrt(discriminant[valid]) + t_valid = (-b[valid] - sqrt_disc) / (2.0 * a[valid]) + t[valid] = t_valid + + # Calcola il punto di intersezione + intersection = ray_origins + t.unsqueeze(-1) * ray_dirs # [B, N, 3] + + return intersection, valid \ No newline at end of file diff --git a/loomnet/utils/instantiators.py b/loomnet/utils/instantiators.py new file mode 100755 index 0000000000000000000000000000000000000000..0c7aa213b1908ca21bdbd89513db88e8180e7fb7 --- /dev/null +++ b/loomnet/utils/instantiators.py @@ -0,0 +1,78 @@ +import importlib +from typing import List + +import hydra +from lightning import Callback +from lightning.pytorch.loggers import Logger +from omegaconf import DictConfig + +from loomnet.utils import RankedLogger + +log = RankedLogger(__name__, rank_zero_only=True) + + +def instantiate_from_config(config, **kwargs): + """Instantiates an object from a configuration. + + This method does not use `hydra.utils.instantiate`. Thus, it does not support + hydra's deep instantiation functionality. + """ + if not "_target_" in config: + if config == "__is_unconditional__": + return None + raise KeyError("Expected key `_target_` to instantiate.") + return get_obj_from_str(config.pop("_target_"))(**config, **kwargs) + + +def get_obj_from_str(string, reload=False): + module, cls = string.rsplit(".", 1) + if reload: + module_imp = importlib.import_module(module) + importlib.reload(module_imp) + return getattr(importlib.import_module(module, package=None), cls) + + +def instantiate_callbacks(callbacks_cfg: DictConfig) -> List[Callback]: + """Instantiates callbacks from config. + + :param callbacks_cfg: A DictConfig object containing callback configurations. + :return: A list of instantiated callbacks. + """ + callbacks: List[Callback] = [] + + if not callbacks_cfg: + log.warning("No callback configs found! Skipping..") + return callbacks + + if not isinstance(callbacks_cfg, DictConfig): + raise TypeError("Callbacks config must be a DictConfig!") + + for _, cb_conf in callbacks_cfg.items(): + if isinstance(cb_conf, DictConfig) and "_target_" in cb_conf: + log.info(f"Instantiating callback <{cb_conf._target_}>") + callbacks.append(hydra.utils.instantiate(cb_conf)) + + return callbacks + + +def instantiate_loggers(logger_cfg: DictConfig) -> List[Logger]: + """Instantiates loggers from config. + + :param logger_cfg: A DictConfig object containing logger configurations. + :return: A list of instantiated loggers. + """ + logger: List[Logger] = [] + + if not logger_cfg: + log.warning("No logger configs found! Skipping...") + return logger + + if not isinstance(logger_cfg, DictConfig): + raise TypeError("Logger config must be a DictConfig!") + + for _, lg_conf in logger_cfg.items(): + if isinstance(lg_conf, DictConfig) and "_target_" in lg_conf: + log.info(f"Instantiating logger <{lg_conf._target_}>") + logger.append(hydra.utils.instantiate(lg_conf)) + + return logger diff --git a/loomnet/utils/logger_utils.py b/loomnet/utils/logger_utils.py new file mode 100755 index 0000000000000000000000000000000000000000..e4a4d656dc4a53a4fa53d3f44164e58888d205b0 --- /dev/null +++ b/loomnet/utils/logger_utils.py @@ -0,0 +1,85 @@ +import logging +from typing import Any, Dict, Mapping, Optional + +from lightning_utilities.core.rank_zero import rank_prefixed_message, rank_zero_only +from omegaconf import OmegaConf + +from .config import get_hparams + + +class RankedLogger(logging.LoggerAdapter): + """A multi-GPU-friendly python command line logger.""" + + def __init__( + self, + name: str = __name__, + rank_zero_only: bool = False, + extra: Optional[Mapping[str, object]] = None, + ) -> None: + """Initializes a multi-GPU-friendly python command line logger that logs on all processes + with their rank prefixed in the log message. + + :param name: The name of the logger. Default is ``__name__``. + :param rank_zero_only: Whether to force all logs to only occur on the rank zero process. Default is `False`. + :param extra: (Optional) A dict-like object which provides contextual information. See `logging.LoggerAdapter`. + """ + logger = logging.getLogger(name) + super().__init__(logger=logger, extra=extra) + self.rank_zero_only = rank_zero_only + + def log( + self, level: int, msg: str, rank: Optional[int] = None, *args, **kwargs + ) -> None: + """Delegate a log call to the underlying logger, after prefixing its message with the rank + of the process it's being logged from. If `'rank'` is provided, then the log will only + occur on that rank/process. + + :param level: The level to log at. Look at `logging.__init__.py` for more information. + :param msg: The message to log. + :param rank: The rank to log at. + :param args: Additional args to pass to the underlying logging function. + :param kwargs: Any additional keyword args to pass to the underlying logging function. + """ + if self.isEnabledFor(level): + msg, kwargs = self.process(msg, kwargs) + current_rank = getattr(rank_zero_only, "rank", None) + if current_rank is None: + raise RuntimeError( + "The `rank_zero_only.rank` needs to be set before use" + ) + msg = rank_prefixed_message(msg, current_rank) + if self.rank_zero_only: + if current_rank == 0: + self.logger.log(level, msg, *args, **kwargs) + else: + if rank is None: + self.logger.log(level, msg, *args, **kwargs) + elif current_rank == rank: + self.logger.log(level, msg, *args, **kwargs) + + +log = RankedLogger(__name__, rank_zero_only=True) + + +@rank_zero_only +def log_hyperparameters(object_dict: Dict[str, Any]) -> None: + """Controls which config parts are saved by Lightning loggers. + + Additionally saves: + - Number of model parameters + + :param object_dict: A dictionary containing the following objects: + - `"cfg"`: A DictConfig object containing the main config. + - `"model"`: The Lightning model. + - `"trainer"`: The Lightning trainer. + """ + trainer = object_dict["trainer"] + if not trainer.logger: + log.warning("Logger not found! Skipping hyperparameter logging...") + return + + hparams = get_hparams(object_dict["cfg"], object_dict["model"]) + + # send hparams to all loggers + for logger in trainer.loggers: + logger.log_hyperparams(hparams) diff --git a/loomnet/utils/media.py b/loomnet/utils/media.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1d22096e507bfc60267bdad673e6bbd1fa2d61 --- /dev/null +++ b/loomnet/utils/media.py @@ -0,0 +1,39 @@ +import torch +import numpy as np +from PIL import Image + + +def get_bg_color(bg_color): + if bg_color == "white": + bg_color = np.array([1.0, 1.0, 1.0], dtype=np.float32) + elif bg_color == "black": + bg_color = np.array([0.0, 0.0, 0.0], dtype=np.float32) + elif bg_color == "gray": + bg_color = np.array([0.5, 0.5, 0.5], dtype=np.float32) + elif bg_color == "random": + bg_color = np.random.rand(3) + elif isinstance(bg_color, float): + bg_color = np.array([bg_color] * 3, dtype=np.float32) + else: + raise NotImplementedError + return bg_color + + +def load_image(img_path, img_wh, bg_color, rescale=True, return_type="np"): + img = np.array(Image.open(img_path).resize(img_wh)) + img = img.astype(np.float32) / 255.0 # [0, 1] + + if img.shape[-1] == 4: + alpha = img[..., 3:4] + img = img[..., :3] * alpha + bg_color * (1 - alpha) + if rescale: + img = img * 2.0 - 1.0 # to -1 ~ 1 + + if return_type == "np": + pass + elif return_type == "pt": + img = torch.from_numpy(img) + else: + raise NotImplementedError + + return img diff --git a/loomnet/utils/misc.py b/loomnet/utils/misc.py new file mode 100755 index 0000000000000000000000000000000000000000..e9a0a65ab36f86cac36767b117fcf3a80abfc2f6 --- /dev/null +++ b/loomnet/utils/misc.py @@ -0,0 +1,190 @@ +import os +import re +import warnings +from importlib.util import find_spec +from typing import Callable, Optional, Tuple + +import torch +from lightning import Trainer +from omegaconf import DictConfig + +from loomnet.utils import RankedLogger + +log = RankedLogger(__name__, rank_zero_only=True) + + +def count_params(model, verbose=False): + total_params = sum(p.numel() for p in model.parameters()) + if verbose: + print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.") + return total_params + + +def get_rank(): + # SLURM_PROCID can be set even if SLURM is not managing the multiprocessing, + # therefore LOCAL_RANK needs to be checked first + rank_keys = ("RANK", "LOCAL_RANK", "SLURM_PROCID", "JSM_NAMESPACE_RANK") + for key in rank_keys: + rank = os.environ.get(key) + if rank is not None: + return int(rank) + return 0 + + +def get_device(): + return torch.device(f"cuda:{get_rank()}") + + +def load_module_weights( + path, module_name=None, ignore_modules=None, map_location=None +) -> Tuple[dict, int, int]: + """Load module weights from a checkpoint. + This method is useful when you want to load weights from a checkpoint. You can specify + a module name, and only the weights of that module will be loaded. You can also specify + a list of modules to ignore. + + :param path: Path to the checkpoint. + :param module_name: Name of the module to load. + :param ignore_modules: List of modules to ignore. + :param map_location: Map location for the checkpoint. Defaults to the current device. + :return: A tuple containing the state dict, the epoch and the global step. + """ + if module_name is not None and ignore_modules is not None: + raise ValueError("module_name and ignore_modules cannot be both set") + if map_location is None: + map_location = get_device() + + ckpt = torch.load(path, map_location=map_location, weights_only=False) + state_dict = ckpt["state_dict"] + state_dict_to_load = state_dict + + if ignore_modules is not None: + state_dict_to_load = {} + for k, v in state_dict.items(): + ignore = any( + [k.startswith(ignore_module + ".") for ignore_module in ignore_modules] + ) + if ignore: + continue + state_dict_to_load[k] = v + + if module_name is not None: + state_dict_to_load = {} + for k, v in state_dict.items(): + m = re.match(rf"^{module_name}\.(.*)$", k) + if m is None: + continue + state_dict_to_load[m.group(1)] = v + + return state_dict_to_load, ckpt["epoch"], ckpt["global_step"] + + +def resolve_dir( + trainer: Trainer, + dirpath: Optional[str] = None, + sub_dir: Optional[str] = None, +) -> str: + """Determines save directory at runtime. Reference attributes from the trainer's logger to + determine where to save. The path for saving weights is set in this priority: + + 1. The ``dirpath`` if passed in + 2. The ``Logger``'s ``log_dir`` if the trainer has loggers + 3. The ``Trainer``'s ``default_root_dir`` if the trainer has no loggers + + The path gets extended with subdirectory ``name`` if passed in. + + """ + if dirpath is not None: + # short circuit if dirpath was passed to ModelCheckpoint + return dirpath + + if len(trainer.loggers) > 0: + if trainer.loggers[0].save_dir is not None: + save_dir = trainer.loggers[0].save_dir + else: + save_dir = trainer.default_root_dir + _name = trainer.loggers[0]._name + version = trainer.loggers[0].version + version = version if isinstance(version, str) else f"version_{version}" + dirpath = os.path.join(save_dir, _name or version) + else: + # if no loggers, use default_root_dir + dirpath = trainer.default_root_dir + + if sub_dir is not None: + dirpath = os.path.join(dirpath, sub_dir) + + return dirpath + + +def apply_extras(cfg: DictConfig) -> None: + """Applies optional utilities before the task is started. + + Utilities: + - Ignoring python warnings + - ... + + :param cfg: A DictConfig object containing the config tree. + """ + # return if no `extras` config + if not cfg.get("extras"): + log.warning("Extras config not found! ") + return + + # disable python warnings + if cfg.extras.get("ignore_warnings"): + log.info("Disabling python warnings! ") + warnings.filterwarnings("ignore") + + +def task_wrapper(task_func: Callable) -> Callable: + """Optional decorator that controls the failure behavior when executing the task function. + + This wrapper can be used to: + - make sure loggers are closed even if the task function raises an exception (prevents multirun failure) + - save the exception to a `.log` file + - mark the run as failed with a dedicated file in the `logs/` folder (so we can find and rerun it later) + - etc. (adjust depending on your needs) + + Example: + ``` + @utils.task_wrapper + def train(**kwargs): + ... + return + ``` + + :param task_func: The task function to be wrapped. + + :return: The wrapped task function. + """ + + def wrap(cfg, config_path=None): + # execute the task + try: + task_func(cfg, config_path=config_path) + + # things to do if exception occurs + except Exception as ex: + # save exception to `.log` file + log.exception("") + + # some hyperparameter combinations might be invalid or cause out-of-memory errors + # so when using hparam search plugins like Optuna, you might want to disable + # raising the below exception to avoid multirun failure + raise ex + + # things to always do after either success or exception + finally: + # display output dir path in terminal + log.info(f"Output dir: {cfg.output_dir}") + + # always close wandb run (even if exception occurs so multirun won't fail) + if find_spec("wandb"): # check if wandb is installed + import wandb + + if wandb.run: + log.info("Closing wandb!") + wandb.finish() + + return wrap diff --git a/loomnet/utils/ops.py b/loomnet/utils/ops.py new file mode 100755 index 0000000000000000000000000000000000000000..2d44f47b9ae122d9e9638a013273fc2512a06b90 --- /dev/null +++ b/loomnet/utils/ops.py @@ -0,0 +1,83 @@ +import torch +import numpy as np +from einops import rearrange + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def default(val, d): + """ + Return val if val is not None, else return d. + """ + return val if val is not None else d + + +def exists(val): + return val is not None + + +def pi_inv(K, x, d): + fx, fy, cx, cy = K[:, 0:1, 0:1], K[:, 1:2, 1:2], K[:, 0:1, 2:3], K[:, 1:2, 2:3] + X_x = d * (x[..., 0] - cx) / fx + X_y = d * (x[..., 1] - cy) / fy + X_z = d + + X = torch.stack([X_x, X_y, X_z], dim=-1) + return X + + +def inv_pose(R, t): + Rwc = R.T + tw = -Rwc.dot(t) + return Rwc, tw + + +def transpose(R, t, X): + b, h, w, c = X.shape + X = rearrange(X, "b h w c -> b c (h w)") + + X_after_R = R @ X + t[:, :, None] + + X_after_R = rearrange(X_after_R, "b c (h w) -> b h w c", h=h) + return X_after_R + + +def back_projection(depth, pose, K, x_2d=None): + b, h, w = depth.shape + if x_2d is None: + x_2d = x_2d_coords(h, w, device=depth.device)[None, ...].repeat(b, 1, 1, 1) + + X_3d = pi_inv(K, x_2d, depth) + + Rwc, twc = pose[:, :3, :3], pose[:, :3, 3] + X_world = transpose(Rwc, twc, X_3d) + + X_world = X_world.reshape((-1, h, w, 3)) + return X_world + + +def get_x_2d(width, height): + x = np.arange(width) + y = np.arange(height) + x, y = np.meshgrid(x, y) + z = np.ones_like(x) + xyz = np.concatenate([x[..., None], y[..., None], z[..., None]], axis=-1).astype( + np.float32 + ) + return xyz + + +def x_2d_coords(h, w, device): + x_2d = torch.zeros((h, w, 2), device=device) + for y in range(0, h): + x_2d[y, :, 1] = y + for x in range(0, w): + x_2d[:, x, 0] = x + return x_2d diff --git a/loomnet/utils/pose.py b/loomnet/utils/pose.py new file mode 100644 index 0000000000000000000000000000000000000000..1f98ccac0ce1ce3d20d5f2336a4a5f29b9215a08 --- /dev/null +++ b/loomnet/utils/pose.py @@ -0,0 +1,102 @@ +# Adapted from https://github.com/liuyuan-pal/SyncDreamer/blob/main/ldm/base_utils.py +import numpy as np +import cv2 +import torch + + +def get_opencv_from_blender(c2w): + c2w[:, :, 1:3] *= -1 + return c2w + + +def get_3x4_RT_matrix_from_blender(c2w): + R, t = c2w[:, :3], c2w[:, 3] + + cam_rec = np.asarray([[1, 0, 0], [0, -1, 0], [0, 0, -1]], np.float32) + R = R.T + t = -R @ t + R_world2cv = cam_rec @ R + t_world2cv = cam_rec @ t + + RT = np.concatenate([R_world2cv, t_world2cv[:, None]], 1) + return RT + + +def pose_inverse(pose): + R = pose[:, :3].T + t = -R @ pose[:, 3:] + return np.concatenate([R, t], -1) + + +def project_points(pts, RT, K): + pts = np.matmul(pts, RT[:, :3].transpose()) + RT[:, 3:].transpose() + pts = np.matmul(pts, K.transpose()) + dpt = pts[:, 2] + mask0 = (np.abs(dpt) < 1e-4) & (np.abs(dpt) > 0) + if np.sum(mask0) > 0: + dpt[mask0] = 1e-4 + mask1 = (np.abs(dpt) > -1e-4) & (np.abs(dpt) < 0) + if np.sum(mask1) > 0: + dpt[mask1] = -1e-4 + pts2d = pts[:, :2] / dpt[:, None] + return pts2d, dpt + + +def draw_keypoints(img, kps, colors=None, radius=2): + out_img = img.copy() + for pi, pt in enumerate(kps): + pt = np.round(pt).astype(np.int32) + if colors is not None: + color = [int(c) for c in colors[pi]] + cv2.circle(out_img, tuple(pt), radius, color, -1) + else: + cv2.circle(out_img, tuple(pt), radius, (0, 255, 0), -1) + return out_img + + +def mask_depth_to_pts(mask, depth, K, rgb=None): + hs, ws = np.nonzero(mask) + depth = depth[hs, ws] + pts = np.asarray([ws, hs, depth], np.float32).transpose() + pts[:, :2] *= pts[:, 2:] + if rgb is not None: + return np.dot(pts, np.linalg.inv(K).transpose()), rgb[hs, ws] + else: + return np.dot(pts, np.linalg.inv(K).transpose()) + + +def transform_points_pose(pts, pose): + R, t = pose[:, :3], pose[:, 3] + if len(pts.shape) == 1: + return (R @ pts[:, None] + t[:, None])[:, 0] + return pts @ R.T + t[None, :] + + +def pose_apply(pose, pts): + return transform_points_pose(pts, pose) + + +def get_k_near_views( + elevations, + azimuths, + k_near_views, + num_views, + add_global_k=None, +): + k_near_views = k_near_views + add_global_k if add_global_k else k_near_views + views = torch.cat((elevations.unsqueeze(1), azimuths.unsqueeze(1)), dim=1) + distances = torch.cdist(views, views) + torch.fill_(distances.diagonal(), 0.0) + k_nearest_indices = torch.topk(distances, k_near_views, largest=False).indices + + if add_global_k is not None: + global_part = ( + torch.arange(num_views - add_global_k, num_views) + .unsqueeze(0) + .repeat(elevations.shape[0], 1) + ) + k_nearest_indices[:-add_global_k, -add_global_k:] = global_part[ + :-add_global_k, :add_global_k + ] + + return k_nearest_indices diff --git a/loomnet/utils/project.py b/loomnet/utils/project.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0da639e676fb4732f335829929be6745aa702d --- /dev/null +++ b/loomnet/utils/project.py @@ -0,0 +1,497 @@ +from einops import rearrange, repeat +import torch +import torch.nn.functional as F +import copy + + +def compute_rel_transform(c2w, ray_origins, ray_directions): + """ + c2w: (b x f) x 4 x 4 + ray_origins: (b x f) x (h x w) x 3 + ray_directions: (b x f) x (h x w) x 3 + return: + canonical_w2c: (b x f) x (h x w) x 3 x 4 + """ + upv = c2w[:, :3, 1] # (b x f) x 3 + upv = rearrange(upv, "bf i -> bf 1 i") # (b x f) x 1 x 3 + rdotup = (ray_directions * upv).sum(-1, keepdims=True) # (b x f) x (h x w) x 1 + orthoup = upv - rdotup * ray_directions # 史密斯正交化 + orthoup = F.normalize(orthoup, dim=-1) # (b x f) x (h x w) x 3 + vec0 = torch.cross(orthoup, ray_directions) # (b x f) x (h x w) x 3 + vec0 = F.normalize(vec0, dim=-1) # (b x f) x (h x w) x 3 + r_relatives = torch.stack( + (vec0, orthoup, ray_directions), dim=-1 + ) # (b x f) x (h x w) x 3 x 3 + r_relatives_T = r_relatives.transpose(-1, -2) # (b x f) x (h x w) x 3 x 3 + translation_relative = torch.einsum( + "... i j, ... j -> ... i", -r_relatives_T, ray_origins + ).unsqueeze( + -1 + ) # (b x f) x (h x w) x 3 + canonical_w2c = torch.cat( + (r_relatives_T, translation_relative), dim=-1 + ) # (b x f) x (h x w) x 3 x 4 + return canonical_w2c + + +def ray_sample(cam2world_matrix, intrinsics, resolution): + """ + Create batches of rays and return origins and directions. + + cam2world_matrix: (N, 4, 4) + intrinsics: (N, 3, 3) + resolution: int + + ray_origins: (N, M, 3) + ray_dirs: (N, M, 3) + """ + + N, M = cam2world_matrix.shape[0], resolution**2 + cam_locs_world = cam2world_matrix[:, :3, 3] + fx = intrinsics[:, 0, 0] + fy = intrinsics[:, 1, 1] + cx = intrinsics[:, 0, 2] + cy = intrinsics[:, 1, 2] + sk = intrinsics[:, 0, 1] + uv = torch.stack( + torch.meshgrid( + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + torch.arange( + resolution, dtype=torch.float32, device=cam2world_matrix.device + ), + indexing="ij", + ) + ) * (1.0 / resolution) + (0.5 / resolution) + uv = repeat(uv, "c h w -> b (h w) c", b=N) + x_cam = uv[:, :, 0].view(N, -1) + y_cam = uv[:, :, 1].view(N, -1) + z_cam = torch.ones((N, M), device=cam2world_matrix.device) + + x_lift = ( + ( + x_cam + - cx.unsqueeze(-1) + + cy.unsqueeze(-1) * sk.unsqueeze(-1) / fy.unsqueeze(-1) + - sk.unsqueeze(-1) * y_cam / fy.unsqueeze(-1) + ) + / fx.unsqueeze(-1) + * z_cam + ) + y_lift = (y_cam - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z_cam + + cam_rel_points = torch.stack( + (x_lift, y_lift, z_cam, torch.ones_like(z_cam)), dim=-1 + ) + + world_rel_points = torch.bmm( + cam2world_matrix, cam_rel_points.permute(0, 2, 1) + ).permute(0, 2, 1)[:, :, :3] + + ray_dirs = world_rel_points - cam_locs_world[:, None, :] + ray_dirs = torch.nn.functional.normalize(ray_dirs, dim=2) + + ray_origins = cam_locs_world.unsqueeze(1).repeat(1, ray_dirs.shape[1], 1) + + return ray_origins, ray_dirs + + +def linspace(start: torch.Tensor, stop: torch.Tensor, num: int): + """ + Creates a tensor of shape [num, *start.shape] whose values are evenly spaced from start to end, inclusive. + Replicates but the multi-dimensional bahaviour of numpy.linspace in PyTorch. + """ + # create a tensor of 'num' steps from 0 to 1 + steps = torch.arange(num, dtype=torch.float32, device=start.device) / (num - 1) + + # reshape the 'steps' tensor to [-1, *([1]*start.ndim)] to allow for broadcastings + # - using 'steps.reshape([-1, *([1]*start.ndim)])' would be nice here but torchscript + # "cannot statically infer the expected size of a list in this contex", hence the code below + for i in range(start.ndim): + steps = steps.unsqueeze(-1) + + # the output starts at 'start' and increments until 'stop' in each dimension + out = start[None] + steps * (stop - start)[None] + + return out + + +def sample_stratified( + ray_origins, + ray_start, + ray_end, + depth_resolution, + disparity_space_sampling=False, + return_depth=False, +): + """ + Return depths of approximately uniformly spaced samples along rays. + """ + N, M, _ = ray_origins.shape + if disparity_space_sampling: + depths_coarse = ( + torch.linspace(0, 1, depth_resolution, device=ray_origins.device) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = 1 / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + depths_coarse = 1.0 / ( + 1.0 / ray_start * (1.0 - depths_coarse) + 1.0 / ray_end * depths_coarse + ) + else: + if type(ray_start) == torch.Tensor: + depths_coarse = linspace(ray_start, ray_end, depth_resolution).permute( + 1, 2, 0, 3 + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta[..., None] + else: + depths_coarse = ( + torch.linspace( + ray_start, ray_end, depth_resolution, device=ray_origins.device + ) + .reshape(1, 1, depth_resolution, 1) + .repeat(N, M, 1, 1) + ) + if not return_depth: + depth_delta = (ray_end - ray_start) / (depth_resolution - 1) + depths_coarse += torch.rand_like(depths_coarse) * depth_delta + return depths_coarse + + +def get_ray_limits_box(rays_o: torch.Tensor, rays_d: torch.Tensor, box_side_length): + """ + Author: Petr Kellnhofer + Intersects rays with the [-1, 1] NDC volume. + Returns min and max distance of entry. + Returns -1 for no intersection. + https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection + """ + o_shape = rays_o.shape + rays_o = rays_o.detach().reshape(-1, 3) + rays_d = rays_d.detach().reshape(-1, 3) + + bb_min = [ + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + -1 * (box_side_length / 2), + ] + bb_max = [ + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + 1 * (box_side_length / 2), + ] + bounds = torch.tensor([bb_min, bb_max], dtype=rays_o.dtype, device=rays_o.device) + is_valid = torch.ones(rays_o.shape[:-1], dtype=bool, device=rays_o.device) + + # Precompute inverse for stability. + invdir = 1 / rays_d + sign = (invdir < 0).long() + + # Intersect with YZ plane. + tmin = (bounds.index_select(0, sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + tmax = (bounds.index_select(0, 1 - sign[..., 0])[..., 0] - rays_o[..., 0]) * invdir[ + ..., 0 + ] + + # Intersect with XZ plane. + tymin = (bounds.index_select(0, sign[..., 1])[..., 1] - rays_o[..., 1]) * invdir[ + ..., 1 + ] + tymax = ( + bounds.index_select(0, 1 - sign[..., 1])[..., 1] - rays_o[..., 1] + ) * invdir[..., 1] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tymax, tymin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tymin) + tmax = torch.min(tmax, tymax) + + # Intersect with XY plane. + tzmin = (bounds.index_select(0, sign[..., 2])[..., 2] - rays_o[..., 2]) * invdir[ + ..., 2 + ] + tzmax = ( + bounds.index_select(0, 1 - sign[..., 2])[..., 2] - rays_o[..., 2] + ) * invdir[..., 2] + + # Resolve parallel rays. + is_valid[torch.logical_or(tmin > tzmax, tzmin > tmax)] = False + + # Use the shortest intersection. + tmin = torch.max(tmin, tzmin) + tmax = torch.min(tmax, tzmax) + + # Mark invalid. + tmin[torch.logical_not(is_valid)] = -1 + tmax[torch.logical_not(is_valid)] = -2 + + return tmin.reshape(*o_shape[:-1], 1), tmax.reshape(*o_shape[:-1], 1) + + +def sample_points(ray_origins, ray_directions, rendering_options, return_depth=False): + if rendering_options["ray_start"] == rendering_options["ray_end"] == "auto": + ray_start, ray_end = get_ray_limits_box( + ray_origins, ray_directions, box_side_length=rendering_options["box_warp"] + ) + is_ray_valid = ray_end > ray_start + if torch.any(is_ray_valid).item(): + ray_start[~is_ray_valid] = ray_start[is_ray_valid].min() + ray_end[~is_ray_valid] = ray_start[is_ray_valid].max() + depths_coarse = sample_stratified( + ray_origins, + ray_start, + ray_end, + rendering_options["n_samples"], + rendering_options["disparity_space_sampling"], + return_depth=return_depth, + ) + else: + # Create stratified depth samples + depths_coarse = sample_stratified( + ray_origins, + rendering_options["ray_start"], + rendering_options["ray_end"], + rendering_options["n_samples"], + rendering_options["disparity_space_sampling"], + return_depth=return_depth, + ) + batch_size, num_rays, samples_per_ray, _ = depths_coarse.shape + # Coarse Pass + sample_coordinates = ray_origins.unsqueeze( + -2 + ) + depths_coarse * ray_directions.unsqueeze(-2) + sample_directions = ray_directions.unsqueeze(-2).expand(-1, -1, samples_per_ray, -1) + return sample_coordinates, sample_directions, depths_coarse + + +def compute_projections(points, k_nearest_cameras): + """ + points: (B, F, (H x W), N_samples, 3) + k_nearest_cameras: (B, F, K, 32) + return: + pixel_locations: (B, F, K, (H x W), N_samples, 2) + mask: (B, F, K, (H x W), N_samples) + """ + b, f, k, _ = k_nearest_cameras.shape + intrinsics = k_nearest_cameras[..., :16].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + c2w = k_nearest_cameras[..., 16:].reshape(b, f, k, 4, 4) # (B, F, K, 4, 4) + points_h = torch.cat( + [points, torch.ones_like(points[..., :1])], dim=-1 + ) # (B, F, (H x W), N_samples, 4) + + points_h = repeat(points_h, "b f n s c -> b f k n s c", k=k) + w2p = torch.matmul(intrinsics, torch.inverse(c2w)) # (B, F, K, 4, 4) + projections = torch.einsum("b f k i j, b f k n s j -> b f k n s i", w2p, points_h) + + # TODO: check is this correct + pixel_locations = projections[..., :2] / torch.clamp( + projections[..., 2:3], min=1e-8 + ) + pixel_locations = torch.clamp( + pixel_locations, min=-10, max=10 + ) # to avoid grid sample nan + mask = projections[..., 2] > 0 # opencv camera + inbound = ( + (pixel_locations[..., 0] <= 1.0) + & (pixel_locations[..., 0] >= 0) + & (pixel_locations[..., 1] <= 1.0) + & (pixel_locations[..., 1] >= 0) + ) + mask = mask & inbound + return pixel_locations, mask + + +class HarmonicEmbedding(torch.nn.Module): + def __init__( + self, + n_harmonic_functions: int = 6, + omega_0: float = 1.0, + logspace: bool = True, + append_input: bool = True, + ) -> None: + super().__init__() + + if logspace: + frequencies = 2.0 ** torch.arange( + n_harmonic_functions, + dtype=torch.float32, + ) + else: + frequencies = torch.linspace( + 1.0, + 2.0 ** (n_harmonic_functions - 1), + n_harmonic_functions, + dtype=torch.float32, + ) + + self.register_buffer("_frequencies", frequencies * omega_0, persistent=False) + self.append_input = append_input + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x: tensor of shape [..., dim] + Returns: + embedding: a harmonic embedding of `x` + of shape [..., (n_harmonic_functions * 2 + int(append_input)) * dim] + """ + embed = (x[..., None] * self._frequencies).view(*x.shape[:-1], -1) + embed = torch.cat( + (embed.sin(), embed.cos(), x) + if self.append_input + else (embed.sin(), embed.cos()), + dim=-1, + ) + return embed + + @staticmethod + def get_output_dim_static( + input_dims: int, + n_harmonic_functions: int, + append_input: bool, + ) -> int: + """ + Utility to help predict the shape of the output of `forward`. + Args: + input_dims: length of the last dimension of the input tensor + n_harmonic_functions: number of embedding frequencies + append_input: whether or not to concat the original + input to the harmonic embedding + Returns: + int: the length of the last dimension of the output tensor + """ + return input_dims * (2 * n_harmonic_functions + int(append_input)) + + def get_output_dim(self, input_dims: int = 3) -> int: + """ + Same as above. The default for input_dims is 3 for 3D applications + which use harmonic embedding for positional encoding, + so the input might be xyz. + """ + return self.get_output_dim_static( + input_dims, len(self._frequencies), self.append_input + ) + + +def encode_plucker(ray_origins, ray_dirs, harmonic_embedding=None): + """ + ray to plucker w/ pos encoding + """ + plucker = torch.cat((ray_dirs, torch.cross(ray_origins, ray_dirs, dim=-1)), dim=-1) + plucker = harmonic_embedding(plucker) + return plucker + + +def process_cameras( + cameras, select_ids=None, harmonic_embedding=None, rendering_options=None +): + """ + cameras: (B, F, 32) + select_ids: (B, F, K) + return: + sample_coordinates: (B, F, (H x W), N_samples, 3) + sample_directions: (B, F, (H x W), N_samples, 3) + query_plucker: (B, F, K, (H x W), 78), the plucker coordinates of the sampled rays + reference_plucker: (B, F, K, (H x W), N_samples, 78), the plucker coordinates of the sampled points + """ + _rendering_options = copy.deepcopy(rendering_options) + _rendering_options["n_samples"] = _rendering_options["n_samples"] # FIXME + resolution = _rendering_options["resolution"] + n_samples = _rendering_options["n_samples"] + b, f, c = cameras.shape + if select_ids is None: + select_ids = torch.arange(f, device=cameras.device) # (k) + select_ids = repeat(select_ids, "k -> b f k", b=b, f=f) + k_views = select_ids.shape[2] + + full_cameras = repeat(cameras, "b k c -> b f k c", f=f) + k_nearest_cameras = torch.zeros(b, f, k_views, c, device=cameras.device) + b_ids = torch.arange(b)[:, None, None].expand(-1, f, k_views).to(cameras.device) + f_ids = torch.arange(f)[None, :, None].expand(b, -1, k_views).to(cameras.device) + # Use advanced indexing to get k nearest cameras + k_nearest_cameras = full_cameras[b_ids, f_ids, select_ids] # (B, F, K, 32) + + instrinsics, c2w = cameras[:, :, :16], cameras[:, :, 16:] + c2w = rearrange(c2w, "b f (i j) -> (b f) i j", i=4, j=4) + instrinsics = rearrange(instrinsics, "b f (i j) -> (b f) i j", i=4, j=4)[:, :3, :3] + ray_origins, ray_directions = ray_sample(c2w, instrinsics, resolution) + + sample_coordinates, sample_directions, sample_depths = sample_points( + ray_origins, ray_directions, _rendering_options, return_depth=True + ) + sample_coordinates = rearrange( + sample_coordinates, "(b f) n s c -> b f n s c", f=f, n=resolution**2 + ) # c = 3 + sample_depths = rearrange( + sample_depths, "(b f) n s c -> b f n s c", f=f, n=resolution**2 + ) # c = 1 + sample_depths = (sample_depths - _rendering_options["ray_start"]) / ( + _rendering_options["ray_end"] - _rendering_options["ray_start"] + ) + projected_points, mask = compute_projections( + sample_coordinates, k_nearest_cameras + ) # compute the k views projection + + query_plucker = encode_plucker( + ray_origins, ray_directions, harmonic_embedding + ) # (B F) N 78 + + query_depth = harmonic_embedding(sample_depths) # B F N S 78 + + query_plucker = repeat( + query_plucker, "(b f) n d -> b f k n s d", f=f, k=k_views, s=n_samples + ) # B F K N 78 + query_depth = repeat(query_depth, "b f n s d -> b f k n s d", k=k_views) + + query_plucker = torch.cat( + (query_plucker, query_depth), dim=-1 + ) # B F K N S 156 # 在 i in F 帧下的深度 + + k_nearest_c2w = rearrange( + k_nearest_cameras[..., 16:], "b f k (i j) -> b f k i j", i=4, j=4 + ) + origins_cam = repeat( + k_nearest_c2w[..., :3, 3], + "b f k i -> b f k n s i", + n=resolution**2, + s=n_samples, + ) + sample_coordinates = repeat( + sample_coordinates, "b f n s c -> b f k n s c", k=k_views + ) + input_dirs = sample_coordinates - origins_cam # (B F K N S 3) + input_dirs = F.normalize(input_dirs, dim=-1) + + canonical_w2c = compute_rel_transform(c2w, ray_origins, ray_directions) + canonical_w2c = repeat( + canonical_w2c, "(b f) n i j -> b f k n s i j", f=f, s=n_samples, k=k_views + ) + origins_cam = torch.cat( + (origins_cam, torch.ones_like(origins_cam[..., :1])), dim=-1 + ) + cannonical_dirs = torch.einsum( + "... i j, ... j-> ... i", canonical_w2c[..., :3, :3], input_dirs + ) + cannonical_cam = torch.einsum("... i j, ... j -> ... i", canonical_w2c, origins_cam) + + reference_plucker = encode_plucker( + cannonical_cam, cannonical_dirs, harmonic_embedding + ) # depth of the s-th point in the k-th view + reference_depth = harmonic_embedding(sample_depths) # B F N S 78 + full_depth = repeat(reference_depth, "b k ... -> b f k ...", f=f) + k_nearest_depth = full_depth[b_ids, f_ids, select_ids] + reference_plucker = torch.cat( + (reference_plucker, k_nearest_depth), dim=-1 + ) # B F K N S 156 + projected_points = projected_points * 2 - 1 # to [-1, 1] + # return projected_points, mask, (ray_origins, ray_directions), (cannonical_cam, cannonical_dirs), sample_depths + return projected_points, mask, query_plucker, reference_plucker, sample_depths diff --git a/loomnet/utils/render_mesh.py b/loomnet/utils/render_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..90501aedb1ffbe71f892211faf937cba0b552882 --- /dev/null +++ b/loomnet/utils/render_mesh.py @@ -0,0 +1,235 @@ +import argparse +import os + +import imageio +import numpy as np +import pyrender +import trimesh +from tqdm import tqdm + + +# lookAt function implementation +def look_at(eye, target, up): + normalize = lambda v: v / np.linalg.norm(v) + lookat = normalize(target - eye) + right = normalize(np.cross(lookat, up)) + up = np.cross(right, lookat) + + # Construct a rotation matrix from the right, new_up, and forward vectors + c2w = np.eye(4) + c2w[:3, :3] = np.stack((right, up, -lookat)).T + c2w[:3, 3] = eye + + return c2w + + +def look_at_ndarray(eye, target, up): + normalize = lambda v: v / np.linalg.norm(v, axis=-1, keepdims=True) + lookat = normalize(target - eye) + right = normalize(np.cross(lookat, up)) + up = np.cross(right, lookat) + + # Construct a rotation matrix from the right, new_up, and forward vectors + c2w = np.eye(4).reshape(1, 4, 4).repeat(eye.shape[0], axis=0) + c2w[:, :3, :3] = np.stack((right, up, -lookat), axis=-1) + c2w[:, :3, 3] = eye + + return c2w + + +def prepare_mesh(mesh, normalize_mesh=False, radius=0.7, source="glb", **kwargs): + if normalize_mesh: + # Set the scene to be centered at the coordinate + mesh.apply_transform(trimesh.transformations.translation_matrix(-mesh.centroid)) + + # Normalize the scene into a sphere with radius of 0.7 + mesh.apply_scale(radius / mesh.bounding_sphere.primitive.radius) + + # Transform the coordinates of the scene + if source == "glb": + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi / 2, [1, 0, 0]) + ) + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi / 2, [0, 0, 1]) + ) + elif source == "meshlab": + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi / 2, [0, 1, 0]) + ) + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi / 2, [1, 0, 0]) + ) + + return mesh + + +def prepare_pyrender_scene( + mesh, light_intensity=4.0, bg_intensity=255, preprocess_mesh=True, **kwargs +): + if preprocess_mesh: + mesh = prepare_mesh(mesh, **kwargs) + + pyrender_scene = pyrender.Scene.from_trimesh_scene(mesh) + + # Create a Pyrender camera + camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0) + nc = pyrender.Node(camera=camera, matrix=np.eye(4)) + + # Create a full ambient lighting + light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=light_intensity) + nl = pyrender.Node(light=light, matrix=np.eye(4)) + + # Prepare the pyrender scene + pyrender_scene.bg_color = np.repeat(bg_intensity / 255, 3) + pyrender_scene.add_node(nc) + pyrender_scene.add_node(nl) + + return pyrender_scene, nc, nl + + +def prepare_test_camera_poses( + n_views, elevation_deg=15.0, fovy_deg=70.0, camera_dist=1.5 +): + elevation_deg = np.full(n_views, elevation_deg) + azimuth_deg = np.linspace(0, 360, n_views) + camera_dists = np.full(n_views, camera_dist) + fovy_deg = np.full(n_views, fovy_deg) + + # Convert to radian + elevation = np.deg2rad(elevation_deg) + azimuth = np.deg2rad(azimuth_deg) + fovy = np.deg2rad(fovy_deg) + + # Convert spherical coordinates to cartesian coordinates + camera_positions = np.stack( + [ + camera_dists * np.cos(elevation) * np.cos(azimuth), + camera_dists * np.cos(elevation) * np.sin(azimuth), + camera_dists * np.sin(elevation), + ], + axis=-1, + ) + light_positions = camera_positions + + # Default scene center at origin + center = np.zeros_like(camera_positions) + # Default camera up direction as +z + up = np.array([0, 0, 1], dtype=np.float32).reshape(1, 3).repeat(n_views, axis=0) + + # Create camera poses + camera_poses = look_at_ndarray(camera_positions, center, up) + + return camera_poses, fovy, light_positions + + +def render_scene( + pyrender_scene: pyrender.Scene, + nc: pyrender.Node, + nl: pyrender.Node, + c2w: np.ndarray, + fovy: float, + light_pose=None, + renderer=None, + width=768, + height=768, + **kwargs, +): + if renderer is None: + renderer = pyrender.OffscreenRenderer(width, height) + if light_pose is None: + light_pose = c2w + + # Set camera pose and light pose + nc.camera.yfov = fovy + pyrender_scene.set_pose(nc, pose=c2w) + + # Set light pose + pyrender_scene.set_pose(nl, pose=light_pose) + + # Render the scene + color, depth = renderer.render(pyrender_scene) + + return color, depth + + +def render_test_video( + obj_path, out_video, n_views=60, fps=15, width=768, height=768, **kwargs +): + # Prepare image list + images = [] + + # Load obj/glb file + scene = trimesh.load(obj_path, force="scene", merge_primitives=True) + print(f"Found {len(scene.geometry.values())} geometry") + + pyrender_scene, nc, nl = prepare_pyrender_scene( + scene, preprocess_mesh=True, **kwargs + ) + + # Prepare camera poses + camera_poses, fovy, _ = prepare_test_camera_poses(n_views) + + # Create a Pyrender offscreen renderer + renderer = pyrender.OffscreenRenderer(width, height) + + # For each perspective, rotate the object, render the scene and save the image + for i in tqdm(range(n_views)): + # Create a copy of the scene for rendering + c2w = camera_poses[i] + color, _ = render_scene( + pyrender_scene, nc, nl, c2w, fovy[i], c2w, renderer=renderer, **kwargs + ) + images.append(color) + + # Save the video + imageio.mimsave(out_video, images, fps=fps) + print(f"Saved to {out_video}") + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--pth_in", type=str, help="path to mesh file") + parser.add_argument("--pth_out", type=str, help="path to output render video") + parser.add_argument("--n_views", type=int, default=60, help="number of views") + parser.add_argument("--fps", type=int, default=15, help="fps of the video") + parser.add_argument("--normalize_mesh", action="store_true", help="normalize mesh") + parser.add_argument( + "--source", choices=["glb", "shape", "meshlab"], default="shape" + ) + parser.add_argument("--width", type=int, default=768, help="width of the video") + parser.add_argument("--height", type=int, default=768, help="height of the video") + parser.add_argument( + "--light_intensity", type=float, default=4.0, help="light intensity" + ) + parser.add_argument( + "--bg_intensity", type=int, default=255, help="background intensity" + ) + return parser.parse_args() + + +def main(cfg): + if os.path.isdir(cfg.pth_in): + os.makedirs(cfg.pth_out, exist_ok=True) + for f in os.listdir(cfg.pth_in): + if f.endswith(".obj") or f.endswith(".glb"): + obj_path = os.path.join(args.pth_in, f) + out_video = os.path.join(args.pth_out, f + ".mp4") + print(f"Rendering {obj_path}") + + try: + render_test_video( + obj_path=obj_path, out_video=out_video, **vars(args) + ) + except Exception as e: + print(f"Failed to render {obj_path}: {e}") + else: + if "/" in cfg.pth_out: + os.makedirs(os.path.dirname(cfg.pth_out), exist_ok=True) + + render_test_video(obj_path=args.pth_in, out_video=args.pth_out, **vars(args)) + + +if __name__ == "__main__": + args = parse_args() + main(args) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..de4d06d8ef9a65a1dc56de1b4dd1d700cfe19bb1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +torch +torchvision +torchaudio +torch_geometric +plotly +einops +torch-cluster +hydra-core +lightning +rootutils +diffusers[torch] +transformers +kornia +gradio \ No newline at end of file