Spaces:
Paused
Paused
upload files in wheels
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- dust3r/croco/LICENSEAdded+52
- dust3r/croco/NOTICEAdded+21
- dust3r/croco/README.MDAdded+124
- dust3r/croco/croco-stereo-flow-demo.ipynbAdded+191
- dust3r/croco/datasets/__init__.pyAdded
- dust3r/croco/datasets/crops/README.MDAdded+104
- dust3r/croco/datasets/crops/extract_crops_from_images.pyAdded+159
- dust3r/croco/datasets/habitat_sim/README.MDAdded+76
- dust3r/croco/datasets/habitat_sim/__init__.pyAdded
- dust3r/croco/datasets/habitat_sim/generate_from_metadata.pyAdded+92
- dust3r/croco/datasets/habitat_sim/generate_from_metadata_files.pyAdded+27
- dust3r/croco/datasets/habitat_sim/generate_multiview_images.pyAdded+177
- dust3r/croco/datasets/habitat_sim/multiview_habitat_sim_generator.pyAdded+390
- dust3r/croco/datasets/habitat_sim/pack_metadata_files.pyAdded+69
- dust3r/croco/datasets/habitat_sim/paths.pyAdded+129
- dust3r/croco/datasets/pairs_dataset.pyAdded+109
- dust3r/croco/datasets/transforms.pyAdded+95
- dust3r/croco/demo.pyAdded+55
- dust3r/croco/interactive_demo.ipynbAdded+271
- dust3r/croco/models/blocks.pyAdded+241
- dust3r/croco/models/criterion.pyAdded+37
- dust3r/croco/models/croco.pyAdded+249
- dust3r/croco/models/croco_downstream.pyAdded+122
- dust3r/croco/models/curope/__init__.pyAdded+4
- dust3r/croco/models/curope/curope.cppAdded+69
- dust3r/croco/models/curope/curope2d.pyAdded+40
- dust3r/croco/models/curope/kernels.cuAdded+108
- dust3r/croco/models/curope/setup.pyAdded+34
- dust3r/croco/models/dpt_block.pyAdded+450
- dust3r/croco/models/head_downstream.pyAdded+58
- dust3r/croco/models/masking.pyAdded+25
- dust3r/croco/models/pos_embed.pyAdded+159
- dust3r/croco/pretrain.pyAdded+254
- dust3r/croco/stereoflow/README.MDAdded+318
- dust3r/croco/stereoflow/augmentor.pyAdded+290
- dust3r/croco/stereoflow/criterion.pyAdded+251
- dust3r/croco/stereoflow/datasets_flow.pyAdded+630
- dust3r/croco/stereoflow/datasets_stereo.pyAdded+674
- dust3r/croco/stereoflow/download_model.shAdded+12
- dust3r/croco/stereoflow/engine.pyAdded+280
- dust3r/croco/stereoflow/test.pyAdded+216
- dust3r/croco/stereoflow/train.pyAdded+253
- dust3r/croco/utils/misc.pyAdded+463
- dust3r/datasets_preprocess/habitat/README.mdAdded+66
- dust3r/datasets_preprocess/habitat/find_scenes.pyAdded+78
- dust3r/datasets_preprocess/habitat/habitat_renderer/__init__.pyAdded+2
- dust3r/datasets_preprocess/habitat/habitat_renderer/habitat_sim_envmaps_renderer.pyAdded+170
- dust3r/datasets_preprocess/habitat/habitat_renderer/multiview_crop_generator.pyAdded+93
- dust3r/datasets_preprocess/habitat/habitat_renderer/projections.pyAdded+151
- dust3r/datasets_preprocess/habitat/habitat_renderer/projections_conversions.pyAdded+45
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152CroCo, Copyright (c) 2022-present Naver Corporation, is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license.
A summary of the CC BY-NC-SA 4.0 license is located here: https://creativecommons.org/licenses/by-nc-sa/4.0/
The CC BY-NC-SA 4.0 license is located here: https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode SEE NOTICE BELOW WITH RESPECT TO THE FILE: models/pos_embed.py, models/blocks.py
***************************
NOTICE WITH RESPECT TO THE FILE: models/pos_embed.py
This software is being redistributed in a modifiled form. The original form is available here:
https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
This software in this file incorporates parts of the following software available here:
Transformer: https://github.com/tensorflow/models/blob/master/official/legacy/transformer/model_utils.pyavailable under the following license: https://github.com/tensorflow/models/blob/master/LICENSE
MoCo v3: https://github.com/facebookresearch/moco-v3available under the following license: https://github.com/facebookresearch/moco-v3/blob/main/LICENSE
DeiT: https://github.com/facebookresearch/deitavailable under the following license: https://github.com/facebookresearch/deit/blob/main/LICENSE
ORIGINAL COPYRIGHT NOTICE AND PERMISSION NOTICE AVAILABLE HERE IS REPRODUCE BELOW:
https://github.com/facebookresearch/mae/blob/main/LICENSE
Attribution-NonCommercial 4.0 International
***************************
NOTICE WITH RESPECT TO THE FILE: models/blocks.py
This software is being redistributed in a modifiled form. The original form is available here:
https://github.com/rwightman/pytorch-image-models
ORIGINAL COPYRIGHT NOTICE AND PERMISSION NOTICE AVAILABLE HERE IS REPRODUCE BELOW:
https://github.com/rwightman/pytorch-image-models/blob/master/LICENSE
Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/123456789101112131415161718192021CroCoCopyright 2022-present NAVER Corp.
This project contains subcomponents with separate copyright notices and license terms. Your use of the source code for these subcomponents is subject to the terms and conditions of the following licenses.
====
facebookresearch/maehttps://github.com/facebookresearch/mae
Attribution-NonCommercial 4.0 International
====
rwightman/pytorch-image-modelshttps://github.com/rwightman/pytorch-image-models
Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# CroCo + CroCo v2 / CroCo-Stereo / CroCo-Flow
[[`CroCo arXiv`](https://arxiv.org/abs/2210.10716)] [[`CroCo v2 arXiv`](https://arxiv.org/abs/2211.10408)] [[`project page and demo`](https://croco.europe.naverlabs.com/)]
This repository contains the code for our CroCo model presented in our NeurIPS'22 paper [CroCo: Self-Supervised Pre-training for 3D Vision Tasks by Cross-View Completion](https://openreview.net/pdf?id=wZEfHUM5ri) and its follow-up extension published at ICCV'23 [Improved Cross-view Completion Pre-training for Stereo Matching and Optical Flow](https://openaccess.thecvf.com/content/ICCV2023/html/Weinzaepfel_CroCo_v2_Improved_Cross-view_Completion_Pre-training_for_Stereo_Matching_and_ICCV_2023_paper.html), refered to as CroCo v2:

```bibtex@inproceedings{croco, title={{CroCo: Self-Supervised Pre-training for 3D Vision Tasks by Cross-View Completion}}, author={{Weinzaepfel, Philippe and Leroy, Vincent and Lucas, Thomas and Br\'egier, Romain and Cabon, Yohann and Arora, Vaibhav and Antsfeld, Leonid and Chidlovskii, Boris and Csurka, Gabriela and Revaud J\'er\^ome}}, booktitle={{NeurIPS}}, year={2022}}
@inproceedings{croco_v2, title={{CroCo v2: Improved Cross-view Completion Pre-training for Stereo Matching and Optical Flow}}, author={Weinzaepfel, Philippe and Lucas, Thomas and Leroy, Vincent and Cabon, Yohann and Arora, Vaibhav and Br{\'e}gier, Romain and Csurka, Gabriela and Antsfeld, Leonid and Chidlovskii, Boris and Revaud, J{\'e}r{\^o}me}, booktitle={ICCV}, year={2023}}```
## License
The code is distributed under the CC BY-NC-SA 4.0 License. See [LICENSE](LICENSE) for more information.Some components are based on code from [MAE](https://github.com/facebookresearch/mae) released under the CC BY-NC-SA 4.0 License and [timm](https://github.com/rwightman/pytorch-image-models) released under the Apache 2.0 License.Some components for stereo matching and optical flow are based on code from [unimatch](https://github.com/autonomousvision/unimatch) released under the MIT license.
## Preparation
1. Install dependencies on a machine with a NVidia GPU using e.g. conda. Note that `habitat-sim` is required only for the interactive demo and the synthetic pre-training data generation. If you don't plan to use it, you can ignore the line installing it and use a more recent python version.
```bashconda create -n croco python=3.7 cmake=3.14.0conda activate crococonda install habitat-sim headless -c conda-forge -c aihabitatconda install pytorch torchvision -c pytorchconda install notebook ipykernel matplotlibconda install ipywidgets widgetsnbextensionconda install scikit-learn tqdm quaternion opencv # only for pretraining / habitat data generation
```
2. Compile cuda kernels for RoPE
CroCo v2 relies on RoPE positional embeddings for which you need to compile some cuda kernels.```bashcd models/curope/python setup.py build_ext --inplacecd ../../```
This can be a bit long as we compile for all cuda architectures, feel free to update L9 of `models/curope/setup.py` to compile for specific architectures only.You might also need to set the environment `CUDA_HOME` in case you use a custom cuda installation.
In case you cannot provide, we also provide a slow pytorch version, which will be automatically loaded.
3. Download pre-trained model
We provide several pre-trained models:
| modelname | pre-training data | pos. embed. | Encoder | Decoder ||------------------------------------------------------------------------------------------------------------------------------------|-------------------|-------------|---------|---------|| [`CroCo.pth`](https://download.europe.naverlabs.com/ComputerVision/CroCo/CroCo.pth) | Habitat | cosine | ViT-B | Small || [`CroCo_V2_ViTBase_SmallDecoder.pth`](https://download.europe.naverlabs.com/ComputerVision/CroCo/CroCo_V2_ViTBase_SmallDecoder.pth) | Habitat + real | RoPE | ViT-B | Small || [`CroCo_V2_ViTBase_BaseDecoder.pth`](https://download.europe.naverlabs.com/ComputerVision/CroCo/CroCo_V2_ViTBase_BaseDecoder.pth) | Habitat + real | RoPE | ViT-B | Base || [`CroCo_V2_ViTLarge_BaseDecoder.pth`](https://download.europe.naverlabs.com/ComputerVision/CroCo/CroCo_V2_ViTLarge_BaseDecoder.pth) | Habitat + real | RoPE | ViT-L | Base |
To download a specific model, i.e., the first one (`CroCo.pth`)```bashmkdir -p pretrained_models/wget https://download.europe.naverlabs.com/ComputerVision/CroCo/CroCo.pth -P pretrained_models/```
## Reconstruction example
Simply run after downloading the `CroCo_V2_ViTLarge_BaseDecoder` pretrained model (or update the corresponding line in `demo.py`)```bashpython demo.py```
## Interactive demonstration of cross-view completion reconstruction on the Habitat simulator
First download the test scene from Habitat:```bashpython -m habitat_sim.utils.datasets_download --uids habitat_test_scenes --data-path habitat-sim-data/```
Then, run the Notebook demo `interactive_demo.ipynb`.
In this demo, you should be able to sample a random reference viewpoint from an [Habitat](https://github.com/facebookresearch/habitat-sim) test scene. Use the sliders to change viewpoint and select a masked target view to reconstruct using CroCo.
## Pre-training
### CroCo
To pre-train CroCo, please first generate the pre-training data from the Habitat simulator, following the instructions in [datasets/habitat_sim/README.MD](datasets/habitat_sim/README.MD) and then run the following command:```torchrun --nproc_per_node=4 pretrain.py --output_dir ./output/pretraining/```
Our CroCo pre-training was launched on a single server with 4 GPUs.It should take around 10 days with A100 or 15 days with V100 to do the 400 pre-training epochs, but decent performances are obtained earlier in training.Note that, while the code contains the same scaling rule of the learning rate as MAE when changing the effective batch size, we did not experimented if it is valid in our case.The first run can take a few minutes to start, to parse all available pre-training pairs.
### CroCo v2
For CroCo v2 pre-training, in addition to the generation of the pre-training data from the Habitat simulator above, please pre-extract the crops from the real datasets following the instructions in [datasets/crops/README.MD](datasets/crops/README.MD).Then, run the following command for the largest model (ViT-L encoder, Base decoder):```torchrun --nproc_per_node=8 pretrain.py --model "CroCoNet(enc_embed_dim=1024, enc_depth=24, enc_num_heads=16, dec_embed_dim=768, dec_num_heads=12, dec_depth=12, pos_embed='RoPE100')" --dataset "habitat_release+ARKitScenes+MegaDepth+3DStreetView+IndoorVL" --warmup_epochs 12 --max_epoch 125 --epochs 250 --amp 0 --keep_freq 5 --output_dir ./output/pretraining_crocov2/```
Our CroCo v2 pre-training was launched on a single server with 8 GPUs for the largest model, and on a single server with 4 GPUs for the smaller ones, keeping a batch size of 64 per gpu in all cases.The largest model should take around 12 days on A100.Note that, while the code contains the same scaling rule of the learning rate as MAE when changing the effective batch size, we did not experimented if it is valid in our case.
## Stereo matching and Optical flow downstream tasks
For CroCo-Stereo and CroCo-Flow, please refer to [stereoflow/README.MD](stereoflow/README.MD).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191{ "cells": [ { "cell_type": "markdown", "id": "9bca0f41", "metadata": {}, "source": [ "# Simple inference example with CroCo-Stereo or CroCo-Flow" ] }, { "cell_type": "code", "execution_count": null, "id": "80653ef7", "metadata": {}, "outputs": [], "source": [ "# Copyright (C) 2022-present Naver Corporation. All rights reserved.\n", "# Licensed under CC BY-NC-SA 4.0 (non-commercial use only)." ] }, { "cell_type": "markdown", "id": "4f033862", "metadata": {}, "source": [ "First download the model(s) of your choice by running\n", "```\n", "bash stereoflow/download_model.sh crocostereo.pth\n", "bash stereoflow/download_model.sh crocoflow.pth\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "1fb2e392", "metadata": {}, "outputs": [], "source": [ "import torch\n", "use_gpu = torch.cuda.is_available() and torch.cuda.device_count()>0\n", "device = torch.device('cuda:0' if use_gpu else 'cpu')\n", "import matplotlib.pylab as plt" ] }, { "cell_type": "code", "execution_count": null, "id": "e0e25d77", "metadata": {}, "outputs": [], "source": [ "from stereoflow.test import _load_model_and_criterion\n", "from stereoflow.engine import tiled_pred\n", "from stereoflow.datasets_stereo import img_to_tensor, vis_disparity\n", "from stereoflow.datasets_flow import flowToColor\n", "tile_overlap=0.7 # recommended value, higher value can be slightly better but slower" ] }, { "cell_type": "markdown", "id": "86a921f5", "metadata": {}, "source": [ "### CroCo-Stereo example" ] }, { "cell_type": "code", "execution_count": null, "id": "64e483cb", "metadata": {}, "outputs": [], "source": [ "image1 = np.asarray(Image.open('<path_to_left_image>'))\n", "image2 = np.asarray(Image.open('<path_to_right_image>'))" ] }, { "cell_type": "code", "execution_count": null, "id": "f0d04303", "metadata": {}, "outputs": [], "source": [ "model, _, cropsize, with_conf, task, tile_conf_mode = _load_model_and_criterion('stereoflow_models/crocostereo.pth', None, device)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "47dc14b5", "metadata": {}, "outputs": [], "source": [ "im1 = img_to_tensor(image1).to(device).unsqueeze(0)\n", "im2 = img_to_tensor(image2).to(device).unsqueeze(0)\n", "with torch.inference_mode():\n", " pred, _, _ = tiled_pred(model, None, im1, im2, None, conf_mode=tile_conf_mode, overlap=tile_overlap, crop=cropsize, with_conf=with_conf, return_time=False)\n", "pred = pred.squeeze(0).squeeze(0).cpu().numpy()" ] }, { "cell_type": "code", "execution_count": null, "id": "583b9f16", "metadata": {}, "outputs": [], "source": [ "plt.imshow(vis_disparity(pred))\n", "plt.axis('off')" ] }, { "cell_type": "markdown", "id": "d2df5d70", "metadata": {}, "source": [ "### CroCo-Flow example" ] }, { "cell_type": "code", "execution_count": null, "id": "9ee257a7", "metadata": {}, "outputs": [], "source": [ "image1 = np.asarray(Image.open('<path_to_first_image>'))\n", "image2 = np.asarray(Image.open('<path_to_second_image>'))" ] }, { "cell_type": "code", "execution_count": null, "id": "d5edccf0", "metadata": {}, "outputs": [], "source": [ "model, _, cropsize, with_conf, task, tile_conf_mode = _load_model_and_criterion('stereoflow_models/crocoflow.pth', None, device)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b19692c3", "metadata": {}, "outputs": [], "source": [ "im1 = img_to_tensor(image1).to(device).unsqueeze(0)\n", "im2 = img_to_tensor(image2).to(device).unsqueeze(0)\n", "with torch.inference_mode():\n", " pred, _, _ = tiled_pred(model, None, im1, im2, None, conf_mode=tile_conf_mode, overlap=tile_overlap, crop=cropsize, with_conf=with_conf, return_time=False)\n", "pred = pred.squeeze(0).permute(1,2,0).cpu().numpy()" ] }, { "cell_type": "code", "execution_count": null, "id": "26f79db3", "metadata": {}, "outputs": [], "source": [ "plt.imshow(flowToColor(pred))\n", "plt.axis('off')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104## Generation of crops from the real datasets
The instructions below allow to generate the crops used for pre-training CroCo v2 from the following real-world datasets: ARKitScenes, MegaDepth, 3DStreetView and IndoorVL.
### Download the metadata of the crops to generate
First, download the metadata and put them in `./data/`:```mkdir -p datacd data/wget https://download.europe.naverlabs.com/ComputerVision/CroCo/data/crop_metadata.zipunzip crop_metadata.ziprm crop_metadata.zipcd ..```
### Prepare the original datasets
Second, download the original datasets in `./data/original_datasets/`.```mkdir -p data/original_datasets```
##### ARKitScenes
Download the `raw` dataset from https://github.com/apple/ARKitScenes/blob/main/DATA.md and put it in `./data/original_datasets/ARKitScenes/`.The resulting file structure should be like:```./data/original_datasets/ARKitScenes/└───Training └───40753679 │ │ ultrawide │ │ ... └───40753686 │ ...```
##### MegaDepth
Download `MegaDepth v1 Dataset` from https://www.cs.cornell.edu/projects/megadepth/ and put it in `./data/original_datasets/MegaDepth/`.The resulting file structure should be like:
```./data/original_datasets/MegaDepth/└───0000│ └───images│ │ │ 1000557903_87fa96b8a4_o.jpg│ │ └ ...│ └─── ...└───0001│ │ │ └ ...└─── ...```
##### 3DStreetView
Download `3D_Street_View` dataset from https://github.com/amir32002/3D_Street_View and put it in `./data/original_datasets/3DStreetView/`.The resulting file structure should be like:
``` ./data/original_datasets/3DStreetView/└───dataset_aligned│ └───0002│ │ │ 0000002_0000001_0000002_0000001.jpg│ │ └ ...│ └─── ...└───dataset_unaligned│ └───0003│ │ │ 0000003_0000001_0000002_0000001.jpg│ │ └ ...│ └─── ...```
##### IndoorVL
Download the `IndoorVL` datasets using [Kapture](https://github.com/naver/kapture).
```pip install kapturemkdir -p ./data/original_datasets/IndoorVLcd ./data/original_datasets/IndoorVLkapture_download_dataset.py updatekapture_download_dataset.py install "HyundaiDepartmentStore_*"kapture_download_dataset.py install "GangnamStation_*"cd -```
### Extract the crops
Now, extract the crops for each of the dataset:```for dataset in ARKitScenes MegaDepth 3DStreetView IndoorVL; do python3 datasets/crops/extract_crops_from_images.py --crops ./data/crop_metadata/${dataset}/crops_release.txt --root-dir ./data/original_datasets/${dataset}/ --output-dir ./data/${dataset}_crops/ --imsize 256 --nthread 8 --max-subdir-levels 5 --ideal-number-pairs-in-dir 500;done```
##### Note for IndoorVL
Due to some legal issues, we can only release 144,228 pairs out of the 1,593,689 pairs used in the paper.To account for it in terms of number of pre-training iterations, the pre-training command in this repository uses 125 training epochs including 12 warm-up epochs and learning rate cosine schedule of 250, instead of 100, 10 and 200 respectively.The impact on the performance is negligible.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).# # --------------------------------------------------------# Extracting crops for pre-training# --------------------------------------------------------
import osimport argparsefrom tqdm import tqdmfrom PIL import Imageimport functoolsfrom multiprocessing import Poolimport math
def arg_parser(): parser = argparse.ArgumentParser('Generate cropped image pairs from image crop list')
parser.add_argument('--crops', type=str, required=True, help='crop file') parser.add_argument('--root-dir', type=str, required=True, help='root directory') parser.add_argument('--output-dir', type=str, required=True, help='output directory') parser.add_argument('--imsize', type=int, default=256, help='size of the crops') parser.add_argument('--nthread', type=int, required=True, help='number of simultaneous threads') parser.add_argument('--max-subdir-levels', type=int, default=5, help='maximum number of subdirectories') parser.add_argument('--ideal-number-pairs-in-dir', type=int, default=500, help='number of pairs stored in a dir') return parser
def main(args): listing_path = os.path.join(args.output_dir, 'listing.txt')
print(f'Loading list of crops ... ({args.nthread} threads)') crops, num_crops_to_generate = load_crop_file(args.crops)
print(f'Preparing jobs ({len(crops)} candidate image pairs)...') num_levels = min(math.ceil(math.log(num_crops_to_generate, args.ideal_number_pairs_in_dir)), args.max_subdir_levels) num_pairs_in_dir = math.ceil(num_crops_to_generate ** (1/num_levels))
jobs = prepare_jobs(crops, num_levels, num_pairs_in_dir) del crops
os.makedirs(args.output_dir, exist_ok=True) mmap = Pool(args.nthread).imap_unordered if args.nthread > 1 else map call = functools.partial(save_image_crops, args)
print(f"Generating cropped images to {args.output_dir} ...") with open(listing_path, 'w') as listing: listing.write('# pair_path\n') for results in tqdm(mmap(call, jobs), total=len(jobs)): for path in results: listing.write(f'{path}\n') print('Finished writing listing to', listing_path)
def load_crop_file(path): data = open(path).read().splitlines() pairs = [] num_crops_to_generate = 0 for line in tqdm(data): if line.startswith('#'): continue line = line.split(', ') if len(line) < 8: img1, img2, rotation = line pairs.append((img1, img2, int(rotation), [])) else: l1, r1, t1, b1, l2, r2, t2, b2 = map(int, line) rect1, rect2 = (l1, t1, r1, b1), (l2, t2, r2, b2) pairs[-1][-1].append((rect1, rect2)) num_crops_to_generate += 1 return pairs, num_crops_to_generate
def prepare_jobs(pairs, num_levels, num_pairs_in_dir): jobs = [] powers = [num_pairs_in_dir**level for level in reversed(range(num_levels))]
def get_path(idx): idx_array = [] d = idx for level in range(num_levels - 1): idx_array.append(idx // powers[level]) idx = idx % powers[level] idx_array.append(d) return '/'.join(map(lambda x: hex(x)[2:], idx_array))
idx = 0 for pair_data in tqdm(pairs): img1, img2, rotation, crops = pair_data if -60 <= rotation and rotation <= 60: rotation = 0 # most likely not a true rotation paths = [get_path(idx + k) for k in range(len(crops))] idx += len(crops) jobs.append(((img1, img2), rotation, crops, paths)) return jobs
def load_image(path): try: return Image.open(path).convert('RGB') except Exception as e: print('skipping', path, e) raise OSError()
def save_image_crops(args, data): # load images img_pair, rot, crops, paths = data try: img1, img2 = [load_image(os.path.join(args.root_dir, impath)) for impath in img_pair] except OSError as e: return []
def area(sz): return sz[0] * sz[1]
tgt_size = (args.imsize, args.imsize)
def prepare_crop(img, rect, rot=0): # actual crop img = img.crop(rect)
# resize to desired size interp = Image.Resampling.LANCZOS if area(img.size) > 4*area(tgt_size) else Image.Resampling.BICUBIC img = img.resize(tgt_size, resample=interp)
# rotate the image rot90 = (round(rot/90) % 4) * 90 if rot90 == 90: img = img.transpose(Image.Transpose.ROTATE_90) elif rot90 == 180: img = img.transpose(Image.Transpose.ROTATE_180) elif rot90 == 270: img = img.transpose(Image.Transpose.ROTATE_270) return img
results = [] for (rect1, rect2), path in zip(crops, paths): crop1 = prepare_crop(img1, rect1) crop2 = prepare_crop(img2, rect2, rot)
fullpath1 = os.path.join(args.output_dir, path+'_1.jpg') fullpath2 = os.path.join(args.output_dir, path+'_2.jpg') os.makedirs(os.path.dirname(fullpath1), exist_ok=True)
assert not os.path.isfile(fullpath1), fullpath1 assert not os.path.isfile(fullpath2), fullpath2 crop1.save(fullpath1) crop2.save(fullpath2) results.append(path)
return results
if __name__ == '__main__': args = arg_parser().parse_args() main(args)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576## Generation of synthetic image pairs using Habitat-Sim
These instructions allow to generate pre-training pairs from the Habitat simulator.As we did not save metadata of the pairs used in the original paper, they are not strictly the same, but these data use the same setting and are equivalent.
### Download Habitat-Sim scenesDownload Habitat-Sim scenes:- Download links can be found here: https://github.com/facebookresearch/habitat-sim/blob/main/DATASETS.md- We used scenes from the HM3D, habitat-test-scenes, Replica, ReplicaCad and ScanNet datasets.- Please put the scenes under `./data/habitat-sim-data/scene_datasets/` following the structure below, or update manually paths in `paths.py`.```./data/└──habitat-sim-data/ └──scene_datasets/ ├──hm3d/ ├──gibson/ ├──habitat-test-scenes/ ├──replica_cad_baked_lighting/ ├──replica_cad/ ├──ReplicaDataset/ └──scannet/```
### Image pairs generationWe provide metadata to generate reproducible images pairs for pretraining and validation.Experiments described in the paper used similar data, but whose generation was not reproducible at the time.
Specifications:- 256x256 resolution images, with 60 degrees field of view .- Up to 1000 image pairs per scene.- Number of scenes considered/number of images pairs per dataset: - Scannet: 1097 scenes / 985 209 pairs - HM3D: - hm3d/train: 800 / 800k pairs - hm3d/val: 100 scenes / 100k pairs - hm3d/minival: 10 scenes / 10k pairs - habitat-test-scenes: 3 scenes / 3k pairs - replica_cad_baked_lighting: 13 scenes / 13k pairs
- Scenes from hm3d/val and hm3d/minival pairs were not used for the pre-training but kept for validation purposes.
Download metadata and extract it:```bashmkdir -p data/habitat_release_metadata/cd data/habitat_release_metadata/wget https://download.europe.naverlabs.com/ComputerVision/CroCo/data/habitat_release_metadata/multiview_habitat_metadata.tar.gztar -xvf multiview_habitat_metadata.tar.gzcd ../..# Location of the metadataMETADATA_DIR="./data/habitat_release_metadata/multiview_habitat_metadata"```
Generate image pairs from metadata:- The following command will print a list of commandlines to generate image pairs for each scene:```bash# Target output directoryPAIRS_DATASET_DIR="./data/habitat_release/"python datasets/habitat_sim/generate_from_metadata_files.py --input_dir=$METADATA_DIR --output_dir=$PAIRS_DATASET_DIR```- One can launch multiple of such commands in parallel e.g. using GNU Parallel:```bashpython datasets/habitat_sim/generate_from_metadata_files.py --input_dir=$METADATA_DIR --output_dir=$PAIRS_DATASET_DIR | parallel -j 16```
## Metadata generation
Image pairs were randomly sampled using the following commands, whose outputs contain randomness and are thus not exactly reproducible:```bash# Print commandlines to generate image pairs from the different scenes available.PAIRS_DATASET_DIR=MY_CUSTOM_PATHpython datasets/habitat_sim/generate_multiview_images.py --list_commands --output_dir=$PAIRS_DATASET_DIR
# Once a dataset is generated, pack metadata files for reproducibility.METADATA_DIR=MY_CUSTON_PATHpython datasets/habitat_sim/pack_metadata_files.py $PAIRS_DATASET_DIR $METADATA_DIR```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
"""Script to generate image pairs for a given scene reproducing poses provided in a metadata file."""import osfrom datasets.habitat_sim.multiview_habitat_sim_generator import MultiviewHabitatSimGeneratorfrom datasets.habitat_sim.paths import SCENES_DATASETimport argparseimport quaternionimport PIL.Imageimport cv2import jsonfrom tqdm import tqdm
def generate_multiview_images_from_metadata(metadata_filename, output_dir, overload_params = dict(), scene_datasets_paths=None, exist_ok=False): """ Generate images from a metadata file for reproducibility purposes. """ # Reorder paths by decreasing label length, to avoid collisions when testing if a string by such label if scene_datasets_paths is not None: scene_datasets_paths = dict(sorted(scene_datasets_paths.items(), key= lambda x: len(x[0]), reverse=True))
with open(metadata_filename, 'r') as f: input_metadata = json.load(f) metadata = dict() for key, value in input_metadata.items(): # Optionally replace some paths if key in ("scene_dataset_config_file", "scene", "navmesh") and value != "": if scene_datasets_paths is not None: for dataset_label, dataset_path in scene_datasets_paths.items(): if value.startswith(dataset_label): value = os.path.normpath(os.path.join(dataset_path, os.path.relpath(value, dataset_label))) break metadata[key] = value
# Overload some parameters for key, value in overload_params.items(): metadata[key] = value
generation_entries = dict([(key, value) for key, value in metadata.items() if not (key in ('multiviews', 'output_dir', 'generate_depth'))]) generate_depth = metadata["generate_depth"]
os.makedirs(output_dir, exist_ok=exist_ok) generator = MultiviewHabitatSimGenerator(**generation_entries)
# Generate views for idx_label, data in tqdm(metadata['multiviews'].items()): positions = data["positions"] orientations = data["orientations"] n = len(positions) for oidx in range(n): observation = generator.render_viewpoint(positions[oidx], quaternion.from_float_array(orientations[oidx])) observation_label = f"{oidx + 1}" # Leonid is indexing starting from 1 # Color image saved using PIL img = PIL.Image.fromarray(observation['color'][:,:,:3]) filename = os.path.join(output_dir, f"{idx_label}_{observation_label}.jpeg") img.save(filename) if generate_depth: # Depth image as EXR file filename = os.path.join(output_dir, f"{idx_label}_{observation_label}_depth.exr") cv2.imwrite(filename, observation['depth'], [cv2.IMWRITE_EXR_TYPE, cv2.IMWRITE_EXR_TYPE_HALF]) # Camera parameters camera_params = dict([(key, observation[key].tolist()) for key in ("camera_intrinsics", "R_cam2world", "t_cam2world")]) filename = os.path.join(output_dir, f"{idx_label}_{observation_label}_camera_params.json") with open(filename, "w") as f: json.dump(camera_params, f) # Save metadata with open(os.path.join(output_dir, "metadata.json"), "w") as f: json.dump(metadata, f)
generator.close()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--metadata_filename", required=True) parser.add_argument("--output_dir", required=True) args = parser.parse_args()
generate_multiview_images_from_metadata(metadata_filename=args.metadata_filename, output_dir=args.output_dir, scene_datasets_paths=SCENES_DATASET, overload_params=dict(), exist_ok=True)
123456789101112131415161718192021222324252627# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
"""Script generating commandlines to generate image pairs from metadata files."""import osimport globfrom tqdm import tqdmimport argparse
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--input_dir", required=True) parser.add_argument("--output_dir", required=True) parser.add_argument("--prefix", default="", help="Commanline prefix, useful e.g. to setup environment.") args = parser.parse_args()
input_metadata_filenames = glob.iglob(f"{args.input_dir}/**/metadata.json", recursive=True)
for metadata_filename in tqdm(input_metadata_filenames): output_dir = os.path.join(args.output_dir, os.path.relpath(os.path.dirname(metadata_filename), args.input_dir)) # Do not process the scene if the metadata file already exists if os.path.exists(os.path.join(output_dir, "metadata.json")): continue commandline = f"{args.prefix}python datasets/habitat_sim/generate_from_metadata.py --metadata_filename={metadata_filename} --output_dir={output_dir}" print(commandline)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
import osfrom tqdm import tqdmimport argparseimport PIL.Imageimport numpy as npimport jsonfrom datasets.habitat_sim.multiview_habitat_sim_generator import MultiviewHabitatSimGenerator, NoNaviguableSpaceErrorfrom datasets.habitat_sim.paths import list_scenes_availableimport cv2import quaternionimport shutil
def generate_multiview_images_for_scene(scene_dataset_config_file, scene, navmesh, output_dir, views_count, size, exist_ok=False, generate_depth=False, **kwargs): """ Generate tuples of overlapping views for a given scene. generate_depth: generate depth images and camera parameters. """ if os.path.exists(output_dir) and not exist_ok: print(f"Scene {scene}: data already generated. Ignoring generation.") return try: print(f"Scene {scene}: {size} multiview acquisitions to generate...") os.makedirs(output_dir, exist_ok=exist_ok)
metadata_filename = os.path.join(output_dir, "metadata.json")
metadata_template = dict(scene_dataset_config_file=scene_dataset_config_file, scene=scene, navmesh=navmesh, views_count=views_count, size=size, generate_depth=generate_depth, **kwargs) metadata_template["multiviews"] = dict()
if os.path.exists(metadata_filename): print("Metadata file already exists:", metadata_filename) print("Loading already generated metadata file...") with open(metadata_filename, "r") as f: metadata = json.load(f)
for key in metadata_template.keys(): if key != "multiviews": assert metadata_template[key] == metadata[key], f"existing file is inconsistent with the input parameters:\nKey: {key}\nmetadata: {metadata[key]}\ntemplate: {metadata_template[key]}." else: print("No temporary file found. Starting generation from scratch...") metadata = metadata_template
starting_id = len(metadata["multiviews"]) print(f"Starting generation from index {starting_id}/{size}...") if starting_id >= size: print("Generation already done.") return
generator = MultiviewHabitatSimGenerator(scene_dataset_config_file=scene_dataset_config_file, scene=scene, navmesh=navmesh, views_count = views_count, size = size, **kwargs)
for idx in tqdm(range(starting_id, size)): # Generate / re-generate the observations try: data = generator[idx] observations = data["observations"] positions = data["positions"] orientations = data["orientations"]
idx_label = f"{idx:08}" for oidx, observation in enumerate(observations): observation_label = f"{oidx + 1}" # Leonid is indexing starting from 1 # Color image saved using PIL img = PIL.Image.fromarray(observation['color'][:,:,:3]) filename = os.path.join(output_dir, f"{idx_label}_{observation_label}.jpeg") img.save(filename) if generate_depth: # Depth image as EXR file filename = os.path.join(output_dir, f"{idx_label}_{observation_label}_depth.exr") cv2.imwrite(filename, observation['depth'], [cv2.IMWRITE_EXR_TYPE, cv2.IMWRITE_EXR_TYPE_HALF]) # Camera parameters camera_params = dict([(key, observation[key].tolist()) for key in ("camera_intrinsics", "R_cam2world", "t_cam2world")]) filename = os.path.join(output_dir, f"{idx_label}_{observation_label}_camera_params.json") with open(filename, "w") as f: json.dump(camera_params, f) metadata["multiviews"][idx_label] = {"positions": positions.tolist(), "orientations": orientations.tolist(), "covisibility_ratios": data["covisibility_ratios"].tolist(), "valid_fractions": data["valid_fractions"].tolist(), "pairwise_visibility_ratios": data["pairwise_visibility_ratios"].tolist()} except RecursionError: print("Recursion error: unable to sample observations for this scene. We will stop there.") break
# Regularly save a temporary metadata file, in case we need to restart the generation if idx % 10 == 0: with open(metadata_filename, "w") as f: json.dump(metadata, f)
# Save metadata with open(metadata_filename, "w") as f: json.dump(metadata, f)
generator.close() except NoNaviguableSpaceError: pass
def create_commandline(scene_data, generate_depth, exist_ok=False): """ Create a commandline string to generate a scene. """ def my_formatting(val): if val is None or val == "": return '""' else: return val commandline = f"""python {__file__} --scene {my_formatting(scene_data.scene)} --scene_dataset_config_file {my_formatting(scene_data.scene_dataset_config_file)} --navmesh {my_formatting(scene_data.navmesh)} --output_dir {my_formatting(scene_data.output_dir)} --generate_depth {int(generate_depth)} --exist_ok {int(exist_ok)} """ commandline = " ".join(commandline.split()) return commandline
if __name__ == "__main__": os.umask(2)
parser = argparse.ArgumentParser(description="""Example of use -- listing commands to generate data for scenes available: > python datasets/habitat_sim/generate_multiview_habitat_images.py --list_commands """) parser.add_argument("--output_dir", type=str, required=True) parser.add_argument("--list_commands", action='store_true', help="list commandlines to run if true") parser.add_argument("--scene", type=str, default="") parser.add_argument("--scene_dataset_config_file", type=str, default="") parser.add_argument("--navmesh", type=str, default="") parser.add_argument("--generate_depth", type=int, default=1) parser.add_argument("--exist_ok", type=int, default=0)
kwargs = dict(resolution=(256,256), hfov=60, views_count = 2, size=1000)
args = parser.parse_args() generate_depth=bool(args.generate_depth) exist_ok = bool(args.exist_ok)
if args.list_commands: # Listing scenes available... scenes_data = list_scenes_available(base_output_dir=args.output_dir) for scene_data in scenes_data: print(create_commandline(scene_data, generate_depth=generate_depth, exist_ok=exist_ok)) else: if args.scene == "" or args.output_dir == "": print("Missing scene or output dir argument!") print(parser.format_help()) else: generate_multiview_images_for_scene(scene=args.scene, scene_dataset_config_file = args.scene_dataset_config_file, navmesh = args.navmesh, output_dir = args.output_dir, exist_ok=exist_ok, generate_depth=generate_depth, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
import osimport numpy as npimport quaternionimport habitat_simimport jsonfrom sklearn.neighbors import NearestNeighborsimport cv2
# OpenCV to habitat camera convention transformationR_OPENCV2HABITAT = np.stack((habitat_sim.geo.RIGHT, -habitat_sim.geo.UP, habitat_sim.geo.FRONT), axis=0)R_HABITAT2OPENCV = R_OPENCV2HABITAT.TDEG2RAD = np.pi / 180
def compute_camera_intrinsics(height, width, hfov): f = width/2 / np.tan(hfov/2 * np.pi/180) cu, cv = width/2, height/2 return f, cu, cv
def compute_camera_pose_opencv_convention(camera_position, camera_orientation): R_cam2world = quaternion.as_rotation_matrix(camera_orientation) @ R_OPENCV2HABITAT t_cam2world = np.asarray(camera_position) return R_cam2world, t_cam2world
def compute_pointmap(depthmap, hfov): """ Compute a HxWx3 pointmap in camera frame from a HxW depth map.""" height, width = depthmap.shape f, cu, cv = compute_camera_intrinsics(height, width, hfov) # Cast depth map to point z_cam = depthmap u, v = np.meshgrid(range(width), range(height)) x_cam = (u - cu) / f * z_cam y_cam = (v - cv) / f * z_cam X_cam = np.stack((x_cam, y_cam, z_cam), axis=-1) return X_cam
def compute_pointcloud(depthmap, hfov, camera_position, camera_rotation): """Return a 3D point cloud corresponding to valid pixels of the depth map""" R_cam2world, t_cam2world = compute_camera_pose_opencv_convention(camera_position, camera_rotation)
X_cam = compute_pointmap(depthmap=depthmap, hfov=hfov) valid_mask = (X_cam[:,:,2] != 0.0)
X_cam = X_cam.reshape(-1, 3)[valid_mask.flatten()] X_world = X_cam @ R_cam2world.T + t_cam2world.reshape(1, 3) return X_world
def compute_pointcloud_overlaps_scikit(pointcloud1, pointcloud2, distance_threshold, compute_symmetric=False): """ Compute 'overlapping' metrics based on a distance threshold between two point clouds. """ nbrs = NearestNeighbors(n_neighbors=1, algorithm = 'kd_tree').fit(pointcloud2) distances, indices = nbrs.kneighbors(pointcloud1) intersection1 = np.count_nonzero(distances.flatten() < distance_threshold)
data = {"intersection1": intersection1, "size1": len(pointcloud1)} if compute_symmetric: nbrs = NearestNeighbors(n_neighbors=1, algorithm = 'kd_tree').fit(pointcloud1) distances, indices = nbrs.kneighbors(pointcloud2) intersection2 = np.count_nonzero(distances.flatten() < distance_threshold) data["intersection2"] = intersection2 data["size2"] = len(pointcloud2)
return data
def _append_camera_parameters(observation, hfov, camera_location, camera_rotation): """ Add camera parameters to the observation dictionnary produced by Habitat-Sim In-place modifications. """ R_cam2world, t_cam2world = compute_camera_pose_opencv_convention(camera_location, camera_rotation) height, width = observation['depth'].shape f, cu, cv = compute_camera_intrinsics(height, width, hfov) K = np.asarray([[f, 0, cu], [0, f, cv], [0, 0, 1.0]]) observation["camera_intrinsics"] = K observation["t_cam2world"] = t_cam2world observation["R_cam2world"] = R_cam2world
def look_at(eye, center, up, return_cam2world=True): """ Return camera pose looking at a given center point. Analogous of gluLookAt function, using OpenCV camera convention. """ z = center - eye z /= np.linalg.norm(z, axis=-1, keepdims=True) y = -up y = y - np.sum(y * z, axis=-1, keepdims=True) * z y /= np.linalg.norm(y, axis=-1, keepdims=True) x = np.cross(y, z, axis=-1)
if return_cam2world: R = np.stack((x, y, z), axis=-1) t = eye else: # World to camera transformation # Transposed matrix R = np.stack((x, y, z), axis=-2) t = - np.einsum('...ij, ...j', R, eye) return R, t
def look_at_for_habitat(eye, center, up, return_cam2world=True): R, t = look_at(eye, center, up) orientation = quaternion.from_rotation_matrix(R @ R_OPENCV2HABITAT.T) return orientation, t
def generate_orientation_noise(pan_range, tilt_range, roll_range): return (quaternion.from_rotation_vector(np.random.uniform(*pan_range) * DEG2RAD * habitat_sim.geo.UP) * quaternion.from_rotation_vector(np.random.uniform(*tilt_range) * DEG2RAD * habitat_sim.geo.RIGHT) * quaternion.from_rotation_vector(np.random.uniform(*roll_range) * DEG2RAD * habitat_sim.geo.FRONT))
class NoNaviguableSpaceError(RuntimeError): def __init__(self, *args): super().__init__(*args)
class MultiviewHabitatSimGenerator: def __init__(self, scene, navmesh, scene_dataset_config_file, resolution = (240, 320), views_count=2, hfov = 60, gpu_id = 0, size = 10000, minimum_covisibility = 0.5, transform = None): self.scene = scene self.navmesh = navmesh self.scene_dataset_config_file = scene_dataset_config_file self.resolution = resolution self.views_count = views_count assert(self.views_count >= 1) self.hfov = hfov self.gpu_id = gpu_id self.size = size self.transform = transform
# Noise added to camera orientation self.pan_range = (-3, 3) self.tilt_range = (-10, 10) self.roll_range = (-5, 5)
# Height range to sample cameras self.height_range = (1.2, 1.8)
# Random steps between the camera views self.random_steps_count = 5 self.random_step_variance = 2.0
# Minimum fraction of the scene which should be valid (well defined depth) self.minimum_valid_fraction = 0.7
# Distance threshold to see to select pairs self.distance_threshold = 0.05 # Minimum IoU of a view point cloud with respect to the reference view to be kept. self.minimum_covisibility = minimum_covisibility
# Maximum number of retries. self.max_attempts_count = 100
self.seed = None self._lazy_initialization()
def _lazy_initialization(self): # Lazy random seeding and instantiation of the simulator to deal with multiprocessing properly if self.seed == None: # Re-seed numpy generator np.random.seed() self.seed = np.random.randint(2**32-1) sim_cfg = habitat_sim.SimulatorConfiguration() sim_cfg.scene_id = self.scene if self.scene_dataset_config_file is not None and self.scene_dataset_config_file != "": sim_cfg.scene_dataset_config_file = self.scene_dataset_config_file sim_cfg.random_seed = self.seed sim_cfg.load_semantic_mesh = False sim_cfg.gpu_device_id = self.gpu_id
depth_sensor_spec = habitat_sim.CameraSensorSpec() depth_sensor_spec.uuid = "depth" depth_sensor_spec.sensor_type = habitat_sim.SensorType.DEPTH depth_sensor_spec.resolution = self.resolution depth_sensor_spec.hfov = self.hfov depth_sensor_spec.position = [0.0, 0.0, 0] depth_sensor_spec.orientation
rgb_sensor_spec = habitat_sim.CameraSensorSpec() rgb_sensor_spec.uuid = "color" rgb_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR rgb_sensor_spec.resolution = self.resolution rgb_sensor_spec.hfov = self.hfov rgb_sensor_spec.position = [0.0, 0.0, 0] agent_cfg = habitat_sim.agent.AgentConfiguration(sensor_specifications=[rgb_sensor_spec, depth_sensor_spec])
cfg = habitat_sim.Configuration(sim_cfg, [agent_cfg]) self.sim = habitat_sim.Simulator(cfg) if self.navmesh is not None and self.navmesh != "": # Use pre-computed navmesh when available (usually better than those generated automatically) self.sim.pathfinder.load_nav_mesh(self.navmesh)
if not self.sim.pathfinder.is_loaded: # Try to compute a navmesh navmesh_settings = habitat_sim.NavMeshSettings() navmesh_settings.set_defaults() self.sim.recompute_navmesh(self.sim.pathfinder, navmesh_settings, True)
# Ensure that the navmesh is not empty if not self.sim.pathfinder.is_loaded: raise NoNaviguableSpaceError(f"No naviguable location (scene: {self.scene} -- navmesh: {self.navmesh})")
self.agent = self.sim.initialize_agent(agent_id=0)
def close(self): self.sim.close()
def __del__(self): self.sim.close()
def __len__(self): return self.size
def sample_random_viewpoint(self): """ Sample a random viewpoint using the navmesh """ nav_point = self.sim.pathfinder.get_random_navigable_point()
# Sample a random viewpoint height viewpoint_height = np.random.uniform(*self.height_range) viewpoint_position = nav_point + viewpoint_height * habitat_sim.geo.UP viewpoint_orientation = quaternion.from_rotation_vector(np.random.uniform(0, 2 * np.pi) * habitat_sim.geo.UP) * generate_orientation_noise(self.pan_range, self.tilt_range, self.roll_range) return viewpoint_position, viewpoint_orientation, nav_point
def sample_other_random_viewpoint(self, observed_point, nav_point): """ Sample a random viewpoint close to an existing one, using the navmesh and a reference observed point.""" other_nav_point = nav_point
walk_directions = self.random_step_variance * np.asarray([1,0,1]) for i in range(self.random_steps_count): temp = self.sim.pathfinder.snap_point(other_nav_point + walk_directions * np.random.normal(size=3)) # Snapping may return nan when it fails if not np.isnan(temp[0]): other_nav_point = temp
other_viewpoint_height = np.random.uniform(*self.height_range) other_viewpoint_position = other_nav_point + other_viewpoint_height * habitat_sim.geo.UP
# Set viewing direction towards the central point rotation, position = look_at_for_habitat(eye=other_viewpoint_position, center=observed_point, up=habitat_sim.geo.UP, return_cam2world=True) rotation = rotation * generate_orientation_noise(self.pan_range, self.tilt_range, self.roll_range) return position, rotation, other_nav_point
def is_other_pointcloud_overlapping(self, ref_pointcloud, other_pointcloud): """ Check if a viewpoint is valid and overlaps significantly with a reference one. """ # Observation pixels_count = self.resolution[0] * self.resolution[1] valid_fraction = len(other_pointcloud) / pixels_count assert valid_fraction <= 1.0 and valid_fraction >= 0.0 overlap = compute_pointcloud_overlaps_scikit(ref_pointcloud, other_pointcloud, self.distance_threshold, compute_symmetric=True) covisibility = min(overlap["intersection1"] / pixels_count, overlap["intersection2"] / pixels_count) is_valid = (valid_fraction >= self.minimum_valid_fraction) and (covisibility >= self.minimum_covisibility) return is_valid, valid_fraction, covisibility
def is_other_viewpoint_overlapping(self, ref_pointcloud, observation, position, rotation): """ Check if a viewpoint is valid and overlaps significantly with a reference one. """ # Observation other_pointcloud = compute_pointcloud(observation['depth'], self.hfov, position, rotation) return self.is_other_pointcloud_overlapping(ref_pointcloud, other_pointcloud)
def render_viewpoint(self, viewpoint_position, viewpoint_orientation): agent_state = habitat_sim.AgentState() agent_state.position = viewpoint_position agent_state.rotation = viewpoint_orientation self.agent.set_state(agent_state) viewpoint_observations = self.sim.get_sensor_observations(agent_ids=0) _append_camera_parameters(viewpoint_observations, self.hfov, viewpoint_position, viewpoint_orientation) return viewpoint_observations
def __getitem__(self, useless_idx): ref_position, ref_orientation, nav_point = self.sample_random_viewpoint() ref_observations = self.render_viewpoint(ref_position, ref_orientation) # Extract point cloud ref_pointcloud = compute_pointcloud(depthmap=ref_observations['depth'], hfov=self.hfov, camera_position=ref_position, camera_rotation=ref_orientation)
pixels_count = self.resolution[0] * self.resolution[1] ref_valid_fraction = len(ref_pointcloud) / pixels_count assert ref_valid_fraction <= 1.0 and ref_valid_fraction >= 0.0 if ref_valid_fraction < self.minimum_valid_fraction: # This should produce a recursion error at some point when something is very wrong. return self[0] # Pick an reference observed point in the point cloud observed_point = np.mean(ref_pointcloud, axis=0)
# Add the first image as reference viewpoints_observations = [ref_observations] viewpoints_covisibility = [ref_valid_fraction] viewpoints_positions = [ref_position] viewpoints_orientations = [quaternion.as_float_array(ref_orientation)] viewpoints_clouds = [ref_pointcloud] viewpoints_valid_fractions = [ref_valid_fraction]
for _ in range(self.views_count - 1): # Generate an other viewpoint using some dummy random walk successful_sampling = False for sampling_attempt in range(self.max_attempts_count): position, rotation, _ = self.sample_other_random_viewpoint(observed_point, nav_point) # Observation other_viewpoint_observations = self.render_viewpoint(position, rotation) other_pointcloud = compute_pointcloud(other_viewpoint_observations['depth'], self.hfov, position, rotation)
is_valid, valid_fraction, covisibility = self.is_other_pointcloud_overlapping(ref_pointcloud, other_pointcloud) if is_valid: successful_sampling = True break if not successful_sampling: print("WARNING: Maximum number of attempts reached.") # Dirty hack, try using a novel original viewpoint return self[0] viewpoints_observations.append(other_viewpoint_observations) viewpoints_covisibility.append(covisibility) viewpoints_positions.append(position) viewpoints_orientations.append(quaternion.as_float_array(rotation)) # WXYZ convention for the quaternion encoding. viewpoints_clouds.append(other_pointcloud) viewpoints_valid_fractions.append(valid_fraction)
# Estimate relations between all pairs of images pairwise_visibility_ratios = np.ones((len(viewpoints_observations), len(viewpoints_observations))) for i in range(len(viewpoints_observations)): pairwise_visibility_ratios[i,i] = viewpoints_valid_fractions[i] for j in range(i+1, len(viewpoints_observations)): overlap = compute_pointcloud_overlaps_scikit(viewpoints_clouds[i], viewpoints_clouds[j], self.distance_threshold, compute_symmetric=True) pairwise_visibility_ratios[i,j] = overlap['intersection1'] / pixels_count pairwise_visibility_ratios[j,i] = overlap['intersection2'] / pixels_count
# IoU is relative to the image 0 data = {"observations": viewpoints_observations, "positions": np.asarray(viewpoints_positions), "orientations": np.asarray(viewpoints_orientations), "covisibility_ratios": np.asarray(viewpoints_covisibility), "valid_fractions": np.asarray(viewpoints_valid_fractions, dtype=float), "pairwise_visibility_ratios": np.asarray(pairwise_visibility_ratios, dtype=float), }
if self.transform is not None: data = self.transform(data) return data
def generate_random_spiral_trajectory(self, images_count = 100, max_radius=0.5, half_turns=5, use_constant_orientation=False): """ Return a list of images corresponding to a spiral trajectory from a random starting point. Useful to generate nice visualisations. Use an even number of half turns to get a nice "C1-continuous" loop effect """ ref_position, ref_orientation, navpoint = self.sample_random_viewpoint() ref_observations = self.render_viewpoint(ref_position, ref_orientation) ref_pointcloud = compute_pointcloud(depthmap=ref_observations['depth'], hfov=self.hfov, camera_position=ref_position, camera_rotation=ref_orientation) pixels_count = self.resolution[0] * self.resolution[1] if len(ref_pointcloud) / pixels_count < self.minimum_valid_fraction: # Dirty hack: ensure that the valid part of the image is significant return self.generate_random_spiral_trajectory(images_count, max_radius, half_turns, use_constant_orientation)
# Pick an observed point in the point cloud observed_point = np.mean(ref_pointcloud, axis=0) ref_R, ref_t = compute_camera_pose_opencv_convention(ref_position, ref_orientation)
images = [] is_valid = [] # Spiral trajectory, use_constant orientation for i, alpha in enumerate(np.linspace(0, 1, images_count)): r = max_radius * np.abs(np.sin(alpha * np.pi)) # Increase then decrease the radius theta = alpha * half_turns * np.pi x = r * np.cos(theta) y = r * np.sin(theta) z = 0.0 position = ref_position + (ref_R @ np.asarray([x, y, z]).reshape(3,1)).flatten() if use_constant_orientation: orientation = ref_orientation else: # trajectory looking at a mean point in front of the ref observation orientation, position = look_at_for_habitat(eye=position, center=observed_point, up=habitat_sim.geo.UP) observations = self.render_viewpoint(position, orientation) images.append(observations['color'][...,:3]) _is_valid, valid_fraction, iou = self.is_other_viewpoint_overlapping(ref_pointcloud, observations, position, orientation) is_valid.append(_is_valid) return images, np.all(is_valid)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only)."""Utility script to pack metadata files of the dataset in order to be able to re-generate it elsewhere."""import osimport globfrom tqdm import tqdmimport shutilimport jsonfrom datasets.habitat_sim.paths import *import argparseimport collections
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("input_dir") parser.add_argument("output_dir") args = parser.parse_args()
input_dirname = args.input_dir output_dirname = args.output_dir
input_metadata_filenames = glob.iglob(f"{input_dirname}/**/metadata.json", recursive=True)
images_count = collections.defaultdict(lambda : 0) os.makedirs(output_dirname) for input_filename in tqdm(input_metadata_filenames): # Ignore empty files with open(input_filename, "r") as f: original_metadata = json.load(f) if "multiviews" not in original_metadata or len(original_metadata["multiviews"]) == 0: print("No views in", input_filename) continue
relpath = os.path.relpath(input_filename, input_dirname) print(relpath)
# Copy metadata, while replacing scene paths by generic keys depending on the dataset, for portability. # Data paths are sorted by decreasing length to avoid potential bugs due to paths starting by the same string pattern. scenes_dataset_paths = dict(sorted(SCENES_DATASET.items(), key=lambda x: len(x[1]), reverse=True)) metadata = dict() for key, value in original_metadata.items(): if key in ("scene_dataset_config_file", "scene", "navmesh") and value != "": known_path = False for dataset, dataset_path in scenes_dataset_paths.items(): if value.startswith(dataset_path): value = os.path.join(dataset, os.path.relpath(value, dataset_path)) known_path = True break if not known_path: raise KeyError("Unknown path:" + value) metadata[key] = value
# Compile some general statistics while packing data scene_split = metadata["scene"].split("/") upper_level = "/".join(scene_split[:2]) if scene_split[0] == "hm3d" else scene_split[0] images_count[upper_level] += len(metadata["multiviews"]) output_filename = os.path.join(output_dirname, relpath) os.makedirs(os.path.dirname(output_filename), exist_ok=True) with open(output_filename, "w") as f: json.dump(metadata, f)
# Print statistics print("Images count:") for upper_level, count in images_count.items(): print(f"- {upper_level}: {count}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
"""Paths to Habitat-Sim scenes"""
import osimport jsonimport collectionsfrom tqdm import tqdm
# Hardcoded path to the different scene datasetsSCENES_DATASET = { "hm3d": "./data/habitat-sim-data/scene_datasets/hm3d/", "gibson": "./data/habitat-sim-data/scene_datasets/gibson/", "habitat-test-scenes": "./data/habitat-sim/scene_datasets/habitat-test-scenes/", "replica_cad_baked_lighting": "./data/habitat-sim/scene_datasets/replica_cad_baked_lighting/", "replica_cad": "./data/habitat-sim/scene_datasets/replica_cad/", "replica": "./data/habitat-sim/scene_datasets/ReplicaDataset/", "scannet": "./data/habitat-sim/scene_datasets/scannet/"}
SceneData = collections.namedtuple("SceneData", ["scene_dataset_config_file", "scene", "navmesh", "output_dir"])
def list_replicacad_scenes(base_output_dir, base_path=SCENES_DATASET["replica_cad"]): scene_dataset_config_file = os.path.join(base_path, "replicaCAD.scene_dataset_config.json") scenes = [f"apt_{i}" for i in range(6)] + ["empty_stage"] navmeshes = [f"navmeshes/apt_{i}_static_furniture.navmesh" for i in range(6)] + ["empty_stage.navmesh"] scenes_data = [] for idx in range(len(scenes)): output_dir = os.path.join(base_output_dir, "ReplicaCAD", scenes[idx]) # Add scene data = SceneData(scene_dataset_config_file=scene_dataset_config_file, scene = scenes[idx] + ".scene_instance.json", navmesh = os.path.join(base_path, navmeshes[idx]), output_dir = output_dir) scenes_data.append(data) return scenes_data
def list_replica_cad_baked_lighting_scenes(base_output_dir, base_path=SCENES_DATASET["replica_cad_baked_lighting"]): scene_dataset_config_file = os.path.join(base_path, "replicaCAD_baked.scene_dataset_config.json") scenes = sum([[f"Baked_sc{i}_staging_{j:02}" for i in range(5)] for j in range(21)], []) navmeshes = ""#[f"navmeshes/apt_{i}_static_furniture.navmesh" for i in range(6)] + ["empty_stage.navmesh"] scenes_data = [] for idx in range(len(scenes)): output_dir = os.path.join(base_output_dir, "replica_cad_baked_lighting", scenes[idx]) data = SceneData(scene_dataset_config_file=scene_dataset_config_file, scene = scenes[idx], navmesh = "", output_dir = output_dir) scenes_data.append(data) return scenes_data
def list_replica_scenes(base_output_dir, base_path): scenes_data = [] for scene_id in os.listdir(base_path): scene = os.path.join(base_path, scene_id, "mesh.ply") navmesh = os.path.join(base_path, scene_id, "habitat/mesh_preseg_semantic.navmesh") # Not sure if I should use it scene_dataset_config_file = "" output_dir = os.path.join(base_output_dir, scene_id) # Add scene only if it does not exist already, or if exist_ok data = SceneData(scene_dataset_config_file = scene_dataset_config_file, scene = scene, navmesh = navmesh, output_dir = output_dir) scenes_data.append(data) return scenes_data
def list_scenes(base_output_dir, base_path): """ Generic method iterating through a base_path folder to find scenes. """ scenes_data = [] for root, dirs, files in os.walk(base_path, followlinks=True): folder_scenes_data = [] for file in files: name, ext = os.path.splitext(file) if ext == ".glb": scene = os.path.join(root, name + ".glb") navmesh = os.path.join(root, name + ".navmesh") if not os.path.exists(navmesh): navmesh = "" relpath = os.path.relpath(root, base_path) output_dir = os.path.abspath(os.path.join(base_output_dir, relpath, name)) data = SceneData(scene_dataset_config_file="", scene = scene, navmesh = navmesh, output_dir = output_dir) folder_scenes_data.append(data)
# Specific check for HM3D: # When two meshesxxxx.basis.glb and xxxx.glb are present, use the 'basis' version. basis_scenes = [data.scene[:-len(".basis.glb")] for data in folder_scenes_data if data.scene.endswith(".basis.glb")] if len(basis_scenes) != 0: folder_scenes_data = [data for data in folder_scenes_data if not (data.scene[:-len(".glb")] in basis_scenes)]
scenes_data.extend(folder_scenes_data) return scenes_data
def list_scenes_available(base_output_dir, scenes_dataset_paths=SCENES_DATASET): scenes_data = []
# HM3D for split in ("minival", "train", "val", "examples"): scenes_data += list_scenes(base_output_dir=os.path.join(base_output_dir, f"hm3d/{split}/"), base_path=f"{scenes_dataset_paths['hm3d']}/{split}")
# Gibson scenes_data += list_scenes(base_output_dir=os.path.join(base_output_dir, "gibson"), base_path=scenes_dataset_paths["gibson"])
# Habitat test scenes (just a few) scenes_data += list_scenes(base_output_dir=os.path.join(base_output_dir, "habitat-test-scenes"), base_path=scenes_dataset_paths["habitat-test-scenes"])
# ReplicaCAD (baked lightning) scenes_data += list_replica_cad_baked_lighting_scenes(base_output_dir=base_output_dir)
# ScanNet scenes_data += list_scenes(base_output_dir=os.path.join(base_output_dir, "scannet"), base_path=scenes_dataset_paths["scannet"]) # Replica list_replica_scenes(base_output_dir=os.path.join(base_output_dir, "replica"), base_path=scenes_dataset_paths["replica"]) return scenes_data 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
import osfrom torch.utils.data import Datasetfrom PIL import Image
from datasets.transforms import get_pair_transforms
def load_image(impath): return Image.open(impath)
def load_pairs_from_cache_file(fname, root=''): assert os.path.isfile(fname), "cannot parse pairs from {:s}, file does not exist".format(fname) with open(fname, 'r') as fid: lines = fid.read().strip().splitlines() pairs = [ (os.path.join(root,l.split()[0]), os.path.join(root,l.split()[1])) for l in lines] return pairs def load_pairs_from_list_file(fname, root=''): assert os.path.isfile(fname), "cannot parse pairs from {:s}, file does not exist".format(fname) with open(fname, 'r') as fid: lines = fid.read().strip().splitlines() pairs = [ (os.path.join(root,l+'_1.jpg'), os.path.join(root,l+'_2.jpg')) for l in lines if not l.startswith('#')] return pairs def write_cache_file(fname, pairs, root=''): if len(root)>0: if not root.endswith('/'): root+='/' assert os.path.isdir(root) s = '' for im1, im2 in pairs: if len(root)>0: assert im1.startswith(root), im1 assert im2.startswith(root), im2 s += '{:s} {:s}\n'.format(im1[len(root):], im2[len(root):]) with open(fname, 'w') as fid: fid.write(s[:-1]) def parse_and_cache_all_pairs(dname, data_dir='./data/'): if dname=='habitat_release': dirname = os.path.join(data_dir, 'habitat_release') assert os.path.isdir(dirname), "cannot find folder for habitat_release pairs: "+dirname cache_file = os.path.join(dirname, 'pairs.txt') assert not os.path.isfile(cache_file), "cache file already exists: "+cache_file print('Parsing pairs for dataset: '+dname) pairs = [] for root, dirs, files in os.walk(dirname): if 'val' in root: continue dirs.sort() pairs += [ (os.path.join(root,f), os.path.join(root,f[:-len('_1.jpeg')]+'_2.jpeg')) for f in sorted(files) if f.endswith('_1.jpeg')] print('Found {:,} pairs'.format(len(pairs))) print('Writing cache to: '+cache_file) write_cache_file(cache_file, pairs, root=dirname)
else: raise NotImplementedError('Unknown dataset: '+dname) def dnames_to_image_pairs(dnames, data_dir='./data/'): """ dnames: list of datasets with image pairs, separated by + """ all_pairs = [] for dname in dnames.split('+'): if dname=='habitat_release': dirname = os.path.join(data_dir, 'habitat_release') assert os.path.isdir(dirname), "cannot find folder for habitat_release pairs: "+dirname cache_file = os.path.join(dirname, 'pairs.txt') assert os.path.isfile(cache_file), "cannot find cache file for habitat_release pairs, please first create the cache file, see instructions. "+cache_file pairs = load_pairs_from_cache_file(cache_file, root=dirname) elif dname in ['ARKitScenes', 'MegaDepth', '3DStreetView', 'IndoorVL']: dirname = os.path.join(data_dir, dname+'_crops') assert os.path.isdir(dirname), "cannot find folder for {:s} pairs: {:s}".format(dname, dirname) list_file = os.path.join(dirname, 'listing.txt') assert os.path.isfile(list_file), "cannot find list file for {:s} pairs, see instructions. {:s}".format(dname, list_file) pairs = load_pairs_from_list_file(list_file, root=dirname) print(' {:s}: {:,} pairs'.format(dname, len(pairs))) all_pairs += pairs if '+' in dnames: print(' Total: {:,} pairs'.format(len(all_pairs))) return all_pairs
class PairsDataset(Dataset):
def __init__(self, dnames, trfs='', totensor=True, normalize=True, data_dir='./data/'): super().__init__() self.image_pairs = dnames_to_image_pairs(dnames, data_dir=data_dir) self.transforms = get_pair_transforms(transform_str=trfs, totensor=totensor, normalize=normalize) def __len__(self): return len(self.image_pairs) def __getitem__(self, index): im1path, im2path = self.image_pairs[index] im1 = load_image(im1path) im2 = load_image(im2path) if self.transforms is not None: im1, im2 = self.transforms(im1, im2) return im1, im2
if __name__=="__main__": import argparse parser = argparse.ArgumentParser(prog="Computing and caching list of pairs for a given dataset") parser.add_argument('--data_dir', default='./data/', type=str, help="path where data are stored") parser.add_argument('--dataset', default='habitat_release', type=str, help="name of the dataset") args = parser.parse_args() parse_and_cache_all_pairs(dname=args.dataset, data_dir=args.data_dir)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
import torchimport torchvision.transformsimport torchvision.transforms.functional as F
# "Pair": apply a transform on a pair# "Both": apply the exact same transform to both images
class ComposePair(torchvision.transforms.Compose): def __call__(self, img1, img2): for t in self.transforms: img1, img2 = t(img1, img2) return img1, img2
class NormalizeBoth(torchvision.transforms.Normalize): def forward(self, img1, img2): img1 = super().forward(img1) img2 = super().forward(img2) return img1, img2
class ToTensorBoth(torchvision.transforms.ToTensor): def __call__(self, img1, img2): img1 = super().__call__(img1) img2 = super().__call__(img2) return img1, img2 class RandomCropPair(torchvision.transforms.RandomCrop): # the crop will be intentionally different for the two images with this class def forward(self, img1, img2): img1 = super().forward(img1) img2 = super().forward(img2) return img1, img2
class ColorJitterPair(torchvision.transforms.ColorJitter): # can be symmetric (same for both images) or assymetric (different jitter params for each image) depending on assymetric_prob def __init__(self, assymetric_prob, **kwargs): super().__init__(**kwargs) self.assymetric_prob = assymetric_prob def jitter_one(self, img, fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor): for fn_id in fn_idx: if fn_id == 0 and brightness_factor is not None: img = F.adjust_brightness(img, brightness_factor) elif fn_id == 1 and contrast_factor is not None: img = F.adjust_contrast(img, contrast_factor) elif fn_id == 2 and saturation_factor is not None: img = F.adjust_saturation(img, saturation_factor) elif fn_id == 3 and hue_factor is not None: img = F.adjust_hue(img, hue_factor) return img def forward(self, img1, img2):
fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params( self.brightness, self.contrast, self.saturation, self.hue ) img1 = self.jitter_one(img1, fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor) if torch.rand(1) < self.assymetric_prob: # assymetric: fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params( self.brightness, self.contrast, self.saturation, self.hue ) img2 = self.jitter_one(img2, fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor) return img1, img2
def get_pair_transforms(transform_str, totensor=True, normalize=True): # transform_str is eg crop224+color trfs = [] for s in transform_str.split('+'): if s.startswith('crop'): size = int(s[len('crop'):]) trfs.append(RandomCropPair(size)) elif s=='acolor': trfs.append(ColorJitterPair(assymetric_prob=1.0, brightness=(0.6, 1.4), contrast=(0.6, 1.4), saturation=(0.6, 1.4), hue=0.0)) elif s=='': # if transform_str was "" pass else: raise NotImplementedError('Unknown augmentation: '+s) if totensor: trfs.append( ToTensorBoth() ) if normalize: trfs.append( NormalizeBoth(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) )
if len(trfs)==0: return None elif len(trfs)==1: return trfs else: return ComposePair(trfs) 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
import torchfrom models.croco import CroCoNetfrom PIL import Imageimport torchvision.transformsfrom torchvision.transforms import ToTensor, Normalize, Compose
def main(): device = torch.device('cuda:0' if torch.cuda.is_available() and torch.cuda.device_count()>0 else 'cpu') # load 224x224 images and transform them to tensor imagenet_mean = [0.485, 0.456, 0.406] imagenet_mean_tensor = torch.tensor(imagenet_mean).view(1,3,1,1).to(device, non_blocking=True) imagenet_std = [0.229, 0.224, 0.225] imagenet_std_tensor = torch.tensor(imagenet_std).view(1,3,1,1).to(device, non_blocking=True) trfs = Compose([ToTensor(), Normalize(mean=imagenet_mean, std=imagenet_std)]) image1 = trfs(Image.open('assets/Chateau1.png').convert('RGB')).to(device, non_blocking=True).unsqueeze(0) image2 = trfs(Image.open('assets/Chateau2.png').convert('RGB')).to(device, non_blocking=True).unsqueeze(0) # load model ckpt = torch.load('pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth', 'cpu') model = CroCoNet( **ckpt.get('croco_kwargs',{})).to(device) model.eval() msg = model.load_state_dict(ckpt['model'], strict=True) # forward with torch.inference_mode(): out, mask, target = model(image1, image2) # the output is normalized, thus use the mean/std of the actual image to go back to RGB space patchified = model.patchify(image1) mean = patchified.mean(dim=-1, keepdim=True) var = patchified.var(dim=-1, keepdim=True) decoded_image = model.unpatchify(out * (var + 1.e-6)**.5 + mean) # undo imagenet normalization, prepare masked image decoded_image = decoded_image * imagenet_std_tensor + imagenet_mean_tensor input_image = image1 * imagenet_std_tensor + imagenet_mean_tensor ref_image = image2 * imagenet_std_tensor + imagenet_mean_tensor image_masks = model.unpatchify(model.patchify(torch.ones_like(ref_image)) * mask[:,:,None]) masked_input_image = ((1 - image_masks) * input_image)
# make visualization visualization = torch.cat((ref_image, masked_input_image, decoded_image, input_image), dim=3) # 4*(B, 3, H, W) -> B, 3, H, W*4 B, C, H, W = visualization.shape visualization = visualization.permute(1, 0, 2, 3).reshape(C, B*H, W) visualization = torchvision.transforms.functional.to_pil_image(torch.clamp(visualization, 0, 1)) fname = "demo_output.png" visualization.save(fname) print('Visualization save in '+fname)
if __name__=="__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Interactive demo of Cross-view Completion." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copyright (C) 2022-present Naver Corporation. All rights reserved.\n", "# Licensed under CC BY-NC-SA 4.0 (non-commercial use only)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import numpy as np\n", "from models.croco import CroCoNet\n", "from ipywidgets import interact, interactive, fixed, interact_manual\n", "import ipywidgets as widgets\n", "import matplotlib.pyplot as plt\n", "import quaternion\n", "import models.masking" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load CroCo model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ckpt = torch.load('pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth', 'cpu')\n", "model = CroCoNet( **ckpt.get('croco_kwargs',{}))\n", "msg = model.load_state_dict(ckpt['model'], strict=True)\n", "use_gpu = torch.cuda.is_available() and torch.cuda.device_count()>0\n", "device = torch.device('cuda:0' if use_gpu else 'cpu')\n", "model = model.eval()\n", "model = model.to(device=device)\n", "print(msg)\n", "\n", "def process_images(ref_image, target_image, masking_ratio, reconstruct_unmasked_patches=False):\n", " \"\"\"\n", " Perform Cross-View completion using two input images, specified using Numpy arrays.\n", " \"\"\"\n", " # Replace the mask generator\n", " model.mask_generator = models.masking.RandomMask(model.patch_embed.num_patches, masking_ratio)\n", "\n", " # ImageNet-1k color normalization\n", " imagenet_mean = torch.as_tensor([0.485, 0.456, 0.406]).reshape(1,3,1,1).to(device)\n", " imagenet_std = torch.as_tensor([0.229, 0.224, 0.225]).reshape(1,3,1,1).to(device)\n", "\n", " normalize_input_colors = True\n", " is_output_normalized = True\n", " with torch.no_grad():\n", " # Cast data to torch\n", " target_image = (torch.as_tensor(target_image, dtype=torch.float, device=device).permute(2,0,1) / 255)[None]\n", " ref_image = (torch.as_tensor(ref_image, dtype=torch.float, device=device).permute(2,0,1) / 255)[None]\n", "\n", " if normalize_input_colors:\n", " ref_image = (ref_image - imagenet_mean) / imagenet_std\n", " target_image = (target_image - imagenet_mean) / imagenet_std\n", "\n", " out, mask, _ = model(target_image, ref_image)\n", " # # get target\n", " if not is_output_normalized:\n", " predicted_image = model.unpatchify(out)\n", " else:\n", " # The output only contains higher order information,\n", " # we retrieve mean and standard deviation from the actual target image\n", " patchified = model.patchify(target_image)\n", " mean = patchified.mean(dim=-1, keepdim=True)\n", " var = patchified.var(dim=-1, keepdim=True)\n", " pred_renorm = out * (var + 1.e-6)**.5 + mean\n", " predicted_image = model.unpatchify(pred_renorm)\n", "\n", " image_masks = model.unpatchify(model.patchify(torch.ones_like(ref_image)) * mask[:,:,None])\n", " masked_target_image = (1 - image_masks) * target_image\n", " \n", " if not reconstruct_unmasked_patches:\n", " # Replace unmasked patches by their actual values\n", " predicted_image = predicted_image * image_masks + masked_target_image\n", "\n", " # Unapply color normalization\n", " if normalize_input_colors:\n", " predicted_image = predicted_image * imagenet_std + imagenet_mean\n", " masked_target_image = masked_target_image * imagenet_std + imagenet_mean\n", " \n", " # Cast to Numpy\n", " masked_target_image = np.asarray(torch.clamp(masked_target_image.squeeze(0).permute(1,2,0) * 255, 0, 255).cpu().numpy(), dtype=np.uint8)\n", " predicted_image = np.asarray(torch.clamp(predicted_image.squeeze(0).permute(1,2,0) * 255, 0, 255).cpu().numpy(), dtype=np.uint8)\n", " return masked_target_image, predicted_image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Use the Habitat simulator to render images from arbitrary viewpoints (requires habitat_sim to be installed)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "os.environ[\"MAGNUM_LOG\"]=\"quiet\"\n", "os.environ[\"HABITAT_SIM_LOG\"]=\"quiet\"\n", "import habitat_sim\n", "\n", "scene = \"habitat-sim-data/scene_datasets/habitat-test-scenes/skokloster-castle.glb\"\n", "navmesh = \"habitat-sim-data/scene_datasets/habitat-test-scenes/skokloster-castle.navmesh\"\n", "\n", "sim_cfg = habitat_sim.SimulatorConfiguration()\n", "if use_gpu: sim_cfg.gpu_device_id = 0\n", "sim_cfg.scene_id = scene\n", "sim_cfg.load_semantic_mesh = False\n", "rgb_sensor_spec = habitat_sim.CameraSensorSpec()\n", "rgb_sensor_spec.uuid = \"color\"\n", "rgb_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR\n", "rgb_sensor_spec.resolution = (224,224)\n", "rgb_sensor_spec.hfov = 56.56\n", "rgb_sensor_spec.position = [0.0, 0.0, 0.0]\n", "rgb_sensor_spec.orientation = [0, 0, 0]\n", "agent_cfg = habitat_sim.agent.AgentConfiguration(sensor_specifications=[rgb_sensor_spec])\n", "\n", "\n", "cfg = habitat_sim.Configuration(sim_cfg, [agent_cfg])\n", "sim = habitat_sim.Simulator(cfg)\n", "if navmesh is not None:\n", " sim.pathfinder.load_nav_mesh(navmesh)\n", "agent = sim.initialize_agent(agent_id=0)\n", "\n", "def sample_random_viewpoint():\n", " \"\"\" Sample a random viewpoint using the navmesh \"\"\"\n", " nav_point = sim.pathfinder.get_random_navigable_point()\n", " # Sample a random viewpoint height\n", " viewpoint_height = np.random.uniform(1.0, 1.6)\n", " viewpoint_position = nav_point + viewpoint_height * habitat_sim.geo.UP\n", " viewpoint_orientation = quaternion.from_rotation_vector(np.random.uniform(-np.pi, np.pi) * habitat_sim.geo.UP)\n", " return viewpoint_position, viewpoint_orientation\n", "\n", "def render_viewpoint(position, orientation):\n", " agent_state = habitat_sim.AgentState()\n", " agent_state.position = position\n", " agent_state.rotation = orientation\n", " agent.set_state(agent_state)\n", " viewpoint_observations = sim.get_sensor_observations(agent_ids=0)\n", " image = viewpoint_observations['color'][:,:,:3]\n", " image = np.asarray(np.clip(1.5 * np.asarray(image, dtype=float), 0, 255), dtype=np.uint8)\n", " return image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sample a random reference view" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ref_position, ref_orientation = sample_random_viewpoint()\n", "ref_image = render_viewpoint(ref_position, ref_orientation)\n", "plt.clf()\n", "fig, axes = plt.subplots(1,1, squeeze=False, num=1)\n", "axes[0,0].imshow(ref_image)\n", "for ax in axes.flatten():\n", " ax.set_xticks([])\n", " ax.set_yticks([])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interactive cross-view completion using CroCo" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "reconstruct_unmasked_patches = False\n", "\n", "def show_demo(masking_ratio, x, y, z, panorama, elevation):\n", " R = quaternion.as_rotation_matrix(ref_orientation)\n", " target_position = ref_position + x * R[:,0] + y * R[:,1] + z * R[:,2]\n", " target_orientation = (ref_orientation\n", " * quaternion.from_rotation_vector(-elevation * np.pi/180 * habitat_sim.geo.LEFT) \n", " * quaternion.from_rotation_vector(-panorama * np.pi/180 * habitat_sim.geo.UP))\n", " \n", " ref_image = render_viewpoint(ref_position, ref_orientation)\n", " target_image = render_viewpoint(target_position, target_orientation)\n", "\n", " masked_target_image, predicted_image = process_images(ref_image, target_image, masking_ratio, reconstruct_unmasked_patches)\n", "\n", " fig, axes = plt.subplots(1,4, squeeze=True, dpi=300)\n", " axes[0].imshow(ref_image)\n", " axes[0].set_xlabel(\"Reference\")\n", " axes[1].imshow(masked_target_image)\n", " axes[1].set_xlabel(\"Masked target\")\n", " axes[2].imshow(predicted_image)\n", " axes[2].set_xlabel(\"Reconstruction\") \n", " axes[3].imshow(target_image)\n", " axes[3].set_xlabel(\"Target\")\n", " for ax in axes.flatten():\n", " ax.set_xticks([])\n", " ax.set_yticks([])\n", "\n", "interact(show_demo,\n", " masking_ratio=widgets.FloatSlider(description='masking', value=0.9, min=0.0, max=1.0),\n", " x=widgets.FloatSlider(value=0.0, min=-0.5, max=0.5, step=0.05),\n", " y=widgets.FloatSlider(value=0.0, min=-0.5, max=0.5, step=0.05),\n", " z=widgets.FloatSlider(value=0.0, min=-0.5, max=0.5, step=0.05),\n", " panorama=widgets.FloatSlider(value=0.0, min=-20, max=20, step=0.5),\n", " elevation=widgets.FloatSlider(value=0.0, min=-20, max=20, step=0.5));" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.13" }, "vscode": { "interpreter": { "hash": "f9237820cd248d7e07cb4fb9f0e4508a85d642f19d831560c0a4b61f3e907e67" } } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Main encoder/decoder blocks# --------------------------------------------------------# References: # timm# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/helpers.py# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/mlp.py# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/patch_embed.py
import torchimport torch.nn as nn
from itertools import repeatimport collections.abc
def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): return x return tuple(repeat(x, n)) return parseto_2tuple = _ntuple(2)
def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ if drop_prob == 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 and scale_by_keep: random_tensor.div_(keep_prob) return x * random_tensor
class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True): super(DropPath, self).__init__() self.drop_prob = drop_prob self.scale_by_keep = scale_by_keep
def forward(self, x): return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
def extra_repr(self): return f'drop_prob={round(self.drop_prob,3):0.3f}'
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, bias=True, drop=0.): 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)
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0]) self.act = act_layer() self.drop1 = nn.Dropout(drop_probs[0]) self.fc2 = nn.Linear(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 Attention(nn.Module):
def __init__(self, dim, rope=None, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.rope = rope
def forward(self, x, xpos): B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).transpose(1,3) q, k, v = [qkv[:,:,i] for i in range(3)] # q,k,v = qkv.unbind(2) # make torchscript happy (cannot use tensor as tuple) if self.rope is not None: q = self.rope(q, xpos) k = self.rope(k, xpos) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, rope=None): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
def forward(self, x, xpos): x = x + self.drop_path(self.attn(self.norm1(x), xpos)) x = x + self.drop_path(self.mlp(self.norm2(x))) return x
class CrossAttention(nn.Module): def __init__(self, dim, rope=None, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5
self.projq = nn.Linear(dim, dim, bias=qkv_bias) self.projk = nn.Linear(dim, dim, bias=qkv_bias) self.projv = nn.Linear(dim, dim, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.rope = rope def forward(self, query, key, value, qpos, kpos): B, Nq, C = query.shape Nk = key.shape[1] Nv = value.shape[1] q = self.projq(query).reshape(B,Nq,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3) k = self.projk(key).reshape(B,Nk,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3) v = self.projv(value).reshape(B,Nv,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3) if self.rope is not None: q = self.rope(q, qpos) k = self.rope(k, kpos) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, Nq, C) x = self.proj(x) x = self.proj_drop(x) return x
class DecoderBlock(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, norm_mem=True, rope=None): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) self.cross_attn = CrossAttention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) self.norm3 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) self.norm_y = norm_layer(dim) if norm_mem else nn.Identity()
def forward(self, x, y, xpos, ypos): x = x + self.drop_path(self.attn(self.norm1(x), xpos)) y_ = self.norm_y(y) x = x + self.drop_path(self.cross_attn(self.norm2(x), y_, y_, xpos, ypos)) x = x + self.drop_path(self.mlp(self.norm3(x))) return x, y # patch embeddingclass PositionGetter(object): """ return positions of patches """
def __init__(self): self.cache_positions = {} def __call__(self, b, h, w, device): if not (h,w) in self.cache_positions: x = torch.arange(w, device=device) y = torch.arange(h, device=device) self.cache_positions[h,w] = torch.cartesian_prod(y, x) # (h, w, 2) pos = self.cache_positions[h,w].view(1, h*w, 2).expand(b, -1, 2).clone() return pos
class PatchEmbed(nn.Module): """ just adding _init_weights + position getter compared to timm.models.layers.patch_embed.PatchEmbed"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) self.img_size = img_size self.patch_size = patch_size self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) self.num_patches = self.grid_size[0] * self.grid_size[1] self.flatten = flatten
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() self.position_getter = PositionGetter() def forward(self, x): B, C, H, W = x.shape torch._assert(H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).") torch._assert(W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).") x = self.proj(x) pos = self.position_getter(B, x.size(2), x.size(3), x.device) if self.flatten: x = x.flatten(2).transpose(1, 2) # BCHW -> BNC x = self.norm(x) return x, pos def _init_weights(self): w = self.proj.weight.data torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
12345678910111213141516171819202122232425262728293031323334353637# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).# # --------------------------------------------------------# Criterion to train CroCo# --------------------------------------------------------# References:# MAE: https://github.com/facebookresearch/mae# --------------------------------------------------------
import torch
class MaskedMSE(torch.nn.Module):
def __init__(self, norm_pix_loss=False, masked=True): """ norm_pix_loss: normalize each patch by their pixel mean and variance masked: compute loss over the masked patches only """ super().__init__() self.norm_pix_loss = norm_pix_loss self.masked = masked def forward(self, pred, mask, target): if self.norm_pix_loss: mean = target.mean(dim=-1, keepdim=True) var = target.var(dim=-1, keepdim=True) target = (target - mean) / (var + 1.e-6)**.5 loss = (pred - target) ** 2 loss = loss.mean(dim=-1) # [N, L], mean loss per patch if self.masked: loss = (loss * mask).sum() / mask.sum() # mean loss on masked patches else: loss = loss.mean() # mean loss return loss123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# CroCo model during pretraining# --------------------------------------------------------
import torchimport torch.nn as nntorch.backends.cuda.matmul.allow_tf32 = True # for gpu >= Ampere and pytorch >= 1.12from functools import partial
from models.blocks import Block, DecoderBlock, PatchEmbedfrom models.pos_embed import get_2d_sincos_pos_embed, RoPE2D from models.masking import RandomMask
class CroCoNet(nn.Module):
def __init__(self, img_size=224, # input image size patch_size=16, # patch_size mask_ratio=0.9, # ratios of masked tokens enc_embed_dim=768, # encoder feature dimension enc_depth=12, # encoder depth enc_num_heads=12, # encoder number of heads in the transformer block dec_embed_dim=512, # decoder feature dimension dec_depth=8, # decoder depth dec_num_heads=16, # decoder number of heads in the transformer block mlp_ratio=4, norm_layer=partial(nn.LayerNorm, eps=1e-6), norm_im2_in_dec=True, # whether to apply normalization of the 'memory' = (second image) in the decoder pos_embed='cosine', # positional embedding (either cosine or RoPE100) ): super(CroCoNet, self).__init__() # patch embeddings (with initialization done as in MAE) self._set_patch_embed(img_size, patch_size, enc_embed_dim)
# mask generations self._set_mask_generator(self.patch_embed.num_patches, mask_ratio)
self.pos_embed = pos_embed if pos_embed=='cosine': # positional embedding of the encoder enc_pos_embed = get_2d_sincos_pos_embed(enc_embed_dim, int(self.patch_embed.num_patches**.5), n_cls_token=0) self.register_buffer('enc_pos_embed', torch.from_numpy(enc_pos_embed).float()) # positional embedding of the decoder dec_pos_embed = get_2d_sincos_pos_embed(dec_embed_dim, int(self.patch_embed.num_patches**.5), n_cls_token=0) self.register_buffer('dec_pos_embed', torch.from_numpy(dec_pos_embed).float()) # pos embedding in each block self.rope = None # nothing for cosine elif pos_embed.startswith('RoPE'): # eg RoPE100 self.enc_pos_embed = None # nothing to add in the encoder with RoPE self.dec_pos_embed = None # nothing to add in the decoder with RoPE if RoPE2D is None: raise ImportError("Cannot find cuRoPE2D, please install it following the README instructions") freq = float(pos_embed[len('RoPE'):]) self.rope = RoPE2D(freq=freq) else: raise NotImplementedError('Unknown pos_embed '+pos_embed)
# transformer for the encoder self.enc_depth = enc_depth self.enc_embed_dim = enc_embed_dim self.enc_blocks = nn.ModuleList([ Block(enc_embed_dim, enc_num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer, rope=self.rope) for i in range(enc_depth)]) self.enc_norm = norm_layer(enc_embed_dim) # masked tokens self._set_mask_token(dec_embed_dim)
# decoder self._set_decoder(enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec) # prediction head self._set_prediction_head(dec_embed_dim, patch_size) # initializer weights self.initialize_weights()
def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768): self.patch_embed = PatchEmbed(img_size, patch_size, 3, enc_embed_dim)
def _set_mask_generator(self, num_patches, mask_ratio): self.mask_generator = RandomMask(num_patches, mask_ratio) def _set_mask_token(self, dec_embed_dim): self.mask_token = nn.Parameter(torch.zeros(1, 1, dec_embed_dim)) def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec): self.dec_depth = dec_depth self.dec_embed_dim = dec_embed_dim # transfer from encoder to decoder self.decoder_embed = nn.Linear(enc_embed_dim, dec_embed_dim, bias=True) # transformer for the decoder self.dec_blocks = nn.ModuleList([ DecoderBlock(dec_embed_dim, dec_num_heads, mlp_ratio=mlp_ratio, qkv_bias=True, norm_layer=norm_layer, norm_mem=norm_im2_in_dec, rope=self.rope) for i in range(dec_depth)]) # final norm layer self.dec_norm = norm_layer(dec_embed_dim) def _set_prediction_head(self, dec_embed_dim, patch_size): self.prediction_head = nn.Linear(dec_embed_dim, patch_size**2 * 3, bias=True) def initialize_weights(self): # patch embed self.patch_embed._init_weights() # mask tokens if self.mask_token is not None: torch.nn.init.normal_(self.mask_token, std=.02) # linears and layer norms self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): # we use xavier_uniform following official JAX ViT: torch.nn.init.xavier_uniform_(m.weight) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def _encode_image(self, image, do_mask=False, return_all_blocks=False): """ image has B x 3 x img_size x img_size do_mask: whether to perform masking or not return_all_blocks: if True, return the features at the end of every block instead of just the features from the last block (eg for some prediction heads) """ # embed the image into patches (x has size B x Npatches x C) # and get position if each return patch (pos has size B x Npatches x 2) x, pos = self.patch_embed(image) # add positional embedding without cls token if self.enc_pos_embed is not None: x = x + self.enc_pos_embed[None,...] # apply masking B,N,C = x.size() if do_mask: masks = self.mask_generator(x) x = x[~masks].view(B, -1, C) posvis = pos[~masks].view(B, -1, 2) else: B,N,C = x.size() masks = torch.zeros((B,N), dtype=bool) posvis = pos # now apply the transformer encoder and normalization if return_all_blocks: out = [] for blk in self.enc_blocks: x = blk(x, posvis) out.append(x) out[-1] = self.enc_norm(out[-1]) return out, pos, masks else: for blk in self.enc_blocks: x = blk(x, posvis) x = self.enc_norm(x) return x, pos, masks def _decoder(self, feat1, pos1, masks1, feat2, pos2, return_all_blocks=False): """ return_all_blocks: if True, return the features at the end of every block instead of just the features from the last block (eg for some prediction heads) masks1 can be None => assume image1 fully visible """ # encoder to decoder layer visf1 = self.decoder_embed(feat1) f2 = self.decoder_embed(feat2) # append masked tokens to the sequence B,Nenc,C = visf1.size() if masks1 is None: # downstreams f1_ = visf1 else: # pretraining Ntotal = masks1.size(1) f1_ = self.mask_token.repeat(B, Ntotal, 1).to(dtype=visf1.dtype) f1_[~masks1] = visf1.view(B * Nenc, C) # add positional embedding if self.dec_pos_embed is not None: f1_ = f1_ + self.dec_pos_embed f2 = f2 + self.dec_pos_embed # apply Transformer blocks out = f1_ out2 = f2 if return_all_blocks: _out, out = out, [] for blk in self.dec_blocks: _out, out2 = blk(_out, out2, pos1, pos2) out.append(_out) out[-1] = self.dec_norm(out[-1]) else: for blk in self.dec_blocks: out, out2 = blk(out, out2, pos1, pos2) out = self.dec_norm(out) return out
def patchify(self, imgs): """ imgs: (B, 3, H, W) x: (B, L, patch_size**2 *3) """ p = self.patch_embed.patch_size[0] assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0
h = w = imgs.shape[2] // p x = imgs.reshape(shape=(imgs.shape[0], 3, h, p, w, p)) x = torch.einsum('nchpwq->nhwpqc', x) x = x.reshape(shape=(imgs.shape[0], h * w, p**2 * 3)) return x
def unpatchify(self, x, channels=3): """ x: (N, L, patch_size**2 *channels) imgs: (N, 3, H, W) """ patch_size = self.patch_embed.patch_size[0] h = w = int(x.shape[1]**.5) assert h * w == x.shape[1] x = x.reshape(shape=(x.shape[0], h, w, patch_size, patch_size, channels)) x = torch.einsum('nhwpqc->nchpwq', x) imgs = x.reshape(shape=(x.shape[0], channels, h * patch_size, h * patch_size)) return imgs
def forward(self, img1, img2): """ img1: tensor of size B x 3 x img_size x img_size img2: tensor of size B x 3 x img_size x img_size out will be B x N x (3*patch_size*patch_size) masks are also returned as B x N just in case """ # encoder of the masked first image feat1, pos1, mask1 = self._encode_image(img1, do_mask=True) # encoder of the second image feat2, pos2, _ = self._encode_image(img2, do_mask=False) # decoder decfeat = self._decoder(feat1, pos1, mask1, feat2, pos2) # prediction head out = self.prediction_head(decfeat) # get target target = self.patchify(img1) return out, mask1, target123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# CroCo model for downstream tasks# --------------------------------------------------------
import torch
from .croco import CroCoNet
def croco_args_from_ckpt(ckpt): if 'croco_kwargs' in ckpt: # CroCo v2 released models return ckpt['croco_kwargs'] elif 'args' in ckpt and hasattr(ckpt['args'], 'model'): # pretrained using the official code release s = ckpt['args'].model # eg "CroCoNet(enc_embed_dim=1024, enc_num_heads=16, enc_depth=24)" assert s.startswith('CroCoNet(') return eval('dict'+s[len('CroCoNet'):]) # transform it into the string of a dictionary and evaluate it else: # CroCo v1 released models return dict()
class CroCoDownstreamMonocularEncoder(CroCoNet):
def __init__(self, head, **kwargs): """ Build network for monocular downstream task, only using the encoder. It takes an extra argument head, that is called with the features and a dictionary img_info containing 'width' and 'height' keys The head is setup with the croconet arguments in this init function NOTE: It works by *calling super().__init__() but with redefined setters """ super(CroCoDownstreamMonocularEncoder, self).__init__(**kwargs) head.setup(self) self.head = head
def _set_mask_generator(self, *args, **kwargs): """ No mask generator """ return
def _set_mask_token(self, *args, **kwargs): """ No mask token """ self.mask_token = None return
def _set_decoder(self, *args, **kwargs): """ No decoder """ return
def _set_prediction_head(self, *args, **kwargs): """ No 'prediction head' for downstream tasks.""" return
def forward(self, img): """ img if of size batch_size x 3 x h x w """ B, C, H, W = img.size() img_info = {'height': H, 'width': W} need_all_layers = hasattr(self.head, 'return_all_blocks') and self.head.return_all_blocks out, _, _ = self._encode_image(img, do_mask=False, return_all_blocks=need_all_layers) return self.head(out, img_info) class CroCoDownstreamBinocular(CroCoNet):
def __init__(self, head, **kwargs): """ Build network for binocular downstream task It takes an extra argument head, that is called with the features and a dictionary img_info containing 'width' and 'height' keys The head is setup with the croconet arguments in this init function """ super(CroCoDownstreamBinocular, self).__init__(**kwargs) head.setup(self) self.head = head
def _set_mask_generator(self, *args, **kwargs): """ No mask generator """ return
def _set_mask_token(self, *args, **kwargs): """ No mask token """ self.mask_token = None return
def _set_prediction_head(self, *args, **kwargs): """ No prediction head for downstream tasks, define your own head """ return def encode_image_pairs(self, img1, img2, return_all_blocks=False): """ run encoder for a pair of images it is actually ~5% faster to concatenate the images along the batch dimension than to encode them separately """ ## the two commented lines below is the naive version with separate encoding #out, pos, _ = self._encode_image(img1, do_mask=False, return_all_blocks=return_all_blocks) #out2, pos2, _ = self._encode_image(img2, do_mask=False, return_all_blocks=False) ## and now the faster version out, pos, _ = self._encode_image( torch.cat( (img1,img2), dim=0), do_mask=False, return_all_blocks=return_all_blocks ) if return_all_blocks: out,out2 = list(map(list, zip(*[o.chunk(2, dim=0) for o in out]))) out2 = out2[-1] else: out,out2 = out.chunk(2, dim=0) pos,pos2 = pos.chunk(2, dim=0) return out, out2, pos, pos2
def forward(self, img1, img2): B, C, H, W = img1.size() img_info = {'height': H, 'width': W} return_all_blocks = hasattr(self.head, 'return_all_blocks') and self.head.return_all_blocks out, out2, pos, pos2 = self.encode_image_pairs(img1, img2, return_all_blocks=return_all_blocks) if return_all_blocks: decout = self._decoder(out[-1], pos, None, out2, pos2, return_all_blocks=return_all_blocks) decout = out+decout else: decout = self._decoder(out, pos, None, out2, pos2, return_all_blocks=return_all_blocks) return self.head(decout, img_info)1234# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
from .curope2d import cuRoPE2D123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869/* Copyright (C) 2022-present Naver Corporation. All rights reserved. Licensed under CC BY-NC-SA 4.0 (non-commercial use only).*/
#include <torch/extension.h>
// forward declarationvoid rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd );
void rope_2d_cpu( torch::Tensor tokens, const torch::Tensor positions, const float base, const float fwd ){ const int B = tokens.size(0); const int N = tokens.size(1); const int H = tokens.size(2); const int D = tokens.size(3) / 4;
auto tok = tokens.accessor<float, 4>(); auto pos = positions.accessor<int64_t, 3>();
for (int b = 0; b < B; b++) { for (int x = 0; x < 2; x++) { // y and then x (2d) for (int n = 0; n < N; n++) { // grab the token position const int p = pos[b][n][x];
for (int h = 0; h < H; h++) { for (int d = 0; d < D; d++) { // grab the two values float u = tok[b][n][h][d+0+x*2*D]; float v = tok[b][n][h][d+D+x*2*D];
// grab the cos,sin const float inv_freq = fwd * p / powf(base, d/float(D)); float c = cosf(inv_freq); float s = sinf(inv_freq);
// write the result tok[b][n][h][d+0+x*2*D] = u*c - v*s; tok[b][n][h][d+D+x*2*D] = v*c + u*s; } } } } }}
void rope_2d( torch::Tensor tokens, // B,N,H,D const torch::Tensor positions, // B,N,2 const float base, const float fwd ){ TORCH_CHECK(tokens.dim() == 4, "tokens must have 4 dimensions"); TORCH_CHECK(positions.dim() == 3, "positions must have 3 dimensions"); TORCH_CHECK(tokens.size(0) == positions.size(0), "batch size differs between tokens & positions"); TORCH_CHECK(tokens.size(1) == positions.size(1), "seq_length differs between tokens & positions"); TORCH_CHECK(positions.size(2) == 2, "positions.shape[2] must be equal to 2"); TORCH_CHECK(tokens.is_cuda() == positions.is_cuda(), "tokens and positions are not on the same device" );
if (tokens.is_cuda()) rope_2d_cuda( tokens, positions, base, fwd ); else rope_2d_cpu( tokens, positions, base, fwd );}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("rope_2d", &rope_2d, "RoPE 2d forward/backward");}12345678910111213141516171819202122232425262728293031323334353637383940# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
import torch
try: import curope as _kernels # run `python setup.py install`except ModuleNotFoundError: from . import curope as _kernels # run `python setup.py build_ext --inplace`
class cuRoPE2D_func (torch.autograd.Function):
@staticmethod def forward(ctx, tokens, positions, base, F0=1): ctx.save_for_backward(positions) ctx.saved_base = base ctx.saved_F0 = F0 # tokens = tokens.clone() # uncomment this if inplace doesn't work _kernels.rope_2d( tokens, positions, base, F0 ) ctx.mark_dirty(tokens) return tokens
@staticmethod def backward(ctx, grad_res): positions, base, F0 = ctx.saved_tensors[0], ctx.saved_base, ctx.saved_F0 _kernels.rope_2d( grad_res, positions, base, -F0 ) ctx.mark_dirty(grad_res) return grad_res, None, None, None
class cuRoPE2D(torch.nn.Module): def __init__(self, freq=100.0, F0=1.0): super().__init__() self.base = freq self.F0 = F0
def forward(self, tokens, positions): cuRoPE2D_func.apply( tokens.transpose(1,2), positions, self.base, self.F0 ) return tokens123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/* Copyright (C) 2022-present Naver Corporation. All rights reserved. Licensed under CC BY-NC-SA 4.0 (non-commercial use only).*/
#include <torch/extension.h>#include <cuda.h>#include <cuda_runtime.h>#include <vector>
#define CHECK_CUDA(tensor) {\ TORCH_CHECK((tensor).is_cuda(), #tensor " is not in cuda memory"); \ TORCH_CHECK((tensor).is_contiguous(), #tensor " is not contiguous"); }void CHECK_KERNEL() {auto error = cudaGetLastError(); TORCH_CHECK( error == cudaSuccess, cudaGetErrorString(error));}
template < typename scalar_t >__global__ void rope_2d_cuda_kernel( //scalar_t* __restrict__ tokens, torch::PackedTensorAccessor32<scalar_t,4,torch::RestrictPtrTraits> tokens, const int64_t* __restrict__ pos, const float base, const float fwd ) // const int N, const int H, const int D ){ // tokens shape = (B, N, H, D) const int N = tokens.size(1); const int H = tokens.size(2); const int D = tokens.size(3); // each block update a single token, for all heads // each thread takes care of a single output extern __shared__ float shared[]; float* shared_inv_freq = shared + D;
const int b = blockIdx.x / N; const int n = blockIdx.x % N;
const int Q = D / 4; // one token = [0..Q : Q..2Q : 2Q..3Q : 3Q..D] // u_Y v_Y u_X v_X
// shared memory: first, compute inv_freq if (threadIdx.x < Q) shared_inv_freq[threadIdx.x] = fwd / powf(base, threadIdx.x/float(Q)); __syncthreads();
// start of X or Y part const int X = threadIdx.x < D/2 ? 0 : 1; const int m = (X*D/2) + (threadIdx.x % Q); // index of u_Y or u_X
// grab the cos,sin appropriate for me const float freq = pos[blockIdx.x*2+X] * shared_inv_freq[threadIdx.x % Q]; const float cos = cosf(freq); const float sin = sinf(freq); /* float* shared_cos_sin = shared + D + D/4; if ((threadIdx.x % (D/2)) < Q) shared_cos_sin[m+0] = cosf(freq); else shared_cos_sin[m+Q] = sinf(freq); __syncthreads(); const float cos = shared_cos_sin[m+0]; const float sin = shared_cos_sin[m+Q]; */
for (int h = 0; h < H; h++) { // then, load all the token for this head in shared memory shared[threadIdx.x] = tokens[b][n][h][threadIdx.x]; __syncthreads();
const float u = shared[m]; const float v = shared[m+Q]; // write output if ((threadIdx.x % (D/2)) < Q) tokens[b][n][h][threadIdx.x] = u*cos - v*sin; else tokens[b][n][h][threadIdx.x] = v*cos + u*sin; }}
void rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd ) { const int B = tokens.size(0); // batch size const int N = tokens.size(1); // sequence length const int H = tokens.size(2); // number of heads const int D = tokens.size(3); // dimension per head
TORCH_CHECK(tokens.stride(3) == 1 && tokens.stride(2) == D, "tokens are not contiguous"); TORCH_CHECK(pos.is_contiguous(), "positions are not contiguous"); TORCH_CHECK(pos.size(0) == B && pos.size(1) == N && pos.size(2) == 2, "bad pos.shape"); TORCH_CHECK(D % 4 == 0, "token dim must be multiple of 4");
// one block for each layer, one thread per local-max const int THREADS_PER_BLOCK = D; const int N_BLOCKS = B * N; // each block takes care of H*D values const int SHARED_MEM = sizeof(float) * (D + D/4);
AT_DISPATCH_FLOATING_TYPES_AND_HALF(tokens.type(), "rope_2d_cuda", ([&] { rope_2d_cuda_kernel<scalar_t> <<<N_BLOCKS, THREADS_PER_BLOCK, SHARED_MEM>>> ( //tokens.data_ptr<scalar_t>(), tokens.packed_accessor32<scalar_t,4,torch::RestrictPtrTraits>(), pos.data_ptr<int64_t>(), base, fwd); //, N, H, D ); }));}12345678910111213141516171819202122232425262728293031323334# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
from setuptools import setupfrom torch import cudafrom torch.utils.cpp_extension import BuildExtension, CUDAExtension
# compile for all possible CUDA architecturesall_cuda_archs = cuda.get_gencode_flags().replace('compute=','arch=').split()# alternatively, you can list cuda archs that you want, eg:# all_cuda_archs = [ # '-gencode', 'arch=compute_70,code=sm_70', # '-gencode', 'arch=compute_75,code=sm_75', # '-gencode', 'arch=compute_80,code=sm_80', # '-gencode', 'arch=compute_86,code=sm_86'# ]
setup( name = 'curope', ext_modules = [ CUDAExtension( name='curope', sources=[ "curope.cpp", "kernels.cu", ], extra_compile_args = dict( nvcc=['-O3','--ptxas-options=-v',"--use_fast_math"]+all_cuda_archs, cxx=['-O3']) ) ], cmdclass = { 'build_ext': BuildExtension })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# DPT head for ViTs# --------------------------------------------------------# References: # https://github.com/isl-org/DPT# https://github.com/EPFL-VILAB/MultiMAE/blob/main/multimae/output_adapters.py
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom einops import rearrange, repeatfrom typing import Union, Tuple, Iterable, List, Optional, Dict
def pair(t): return t if isinstance(t, tuple) else (t, t)
def make_scratch(in_shape, out_shape, groups=1, expand=False): scratch = nn.Module()
out_shape1 = out_shape out_shape2 = out_shape out_shape3 = out_shape out_shape4 = out_shape if expand == True: out_shape1 = out_shape out_shape2 = out_shape * 2 out_shape3 = out_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, ) scratch.layer4_rn = nn.Conv2d( in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups, )
scratch.layer_rn = nn.ModuleList([ scratch.layer1_rn, scratch.layer2_rn, scratch.layer3_rn, scratch.layer4_rn, ])
return scratch
class ResidualConvUnit_custom(nn.Module): """Residual convolution module."""
def __init__(self, features, activation, bn): """Init. Args: features (int): number of features """ super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d( features, features, kernel_size=3, stride=1, padding=1, bias=not self.bn, groups=self.groups, )
self.conv2 = nn.Conv2d( features, features, kernel_size=3, stride=1, padding=1, bias=not self.bn, groups=self.groups, )
if self.bn == True: self.bn1 = nn.BatchNorm2d(features) self.bn2 = nn.BatchNorm2d(features)
self.activation = activation
self.skip_add = nn.quantized.FloatFunctional()
def forward(self, x): """Forward pass. Args: x (tensor): input Returns: tensor: output """
out = self.activation(x) out = self.conv1(out) if self.bn == True: out = self.bn1(out)
out = self.activation(out) out = self.conv2(out) if self.bn == True: out = self.bn2(out)
if self.groups > 1: out = self.conv_merge(out)
return self.skip_add.add(out, x)
class FeatureFusionBlock_custom(nn.Module): """Feature fusion block."""
def __init__( self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, width_ratio=1, ): """Init. Args: features (int): number of features """ super(FeatureFusionBlock_custom, self).__init__() self.width_ratio = width_ratio
self.deconv = deconv self.align_corners = align_corners
self.groups = 1
self.expand = expand out_features = features if self.expand == True: out_features = features // 2
self.out_conv = nn.Conv2d( features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1, )
self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn) self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn)
self.skip_add = nn.quantized.FloatFunctional()
def forward(self, *xs): """Forward pass. Returns: tensor: output """ output = xs[0]
if len(xs) == 2: res = self.resConfUnit1(xs[1]) if self.width_ratio != 1: res = F.interpolate(res, size=(output.shape[2], output.shape[3]), mode='bilinear')
output = self.skip_add.add(output, res) # output += res
output = self.resConfUnit2(output)
if self.width_ratio != 1: # and output.shape[3] < self.width_ratio * output.shape[2] #size=(image.shape[]) if (output.shape[3] / output.shape[2]) < (2 / 3) * self.width_ratio: shape = 3 * output.shape[3] else: shape = int(self.width_ratio * 2 * output.shape[2]) output = F.interpolate(output, size=(2* output.shape[2], shape), mode='bilinear') else: output = nn.functional.interpolate(output, scale_factor=2, mode="bilinear", align_corners=self.align_corners) output = self.out_conv(output) return output
def make_fusion_block(features, use_bn, width_ratio=1): return FeatureFusionBlock_custom( features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=True, width_ratio=width_ratio, )
class Interpolate(nn.Module): """Interpolation module."""
def __init__(self, scale_factor, mode, align_corners=False): """Init. Args: scale_factor (float): scaling mode (str): interpolation mode """ super(Interpolate, self).__init__()
self.interp = nn.functional.interpolate self.scale_factor = scale_factor self.mode = mode self.align_corners = align_corners
def forward(self, x): """Forward pass. Args: x (tensor): input Returns: tensor: interpolated data """
x = self.interp( x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners, )
return x
class DPTOutputAdapter(nn.Module): """DPT output adapter.
:param num_cahnnels: Number of output channels :param stride_level: tride level compared to the full-sized image. E.g. 4 for 1/4th the size of the image. :param patch_size_full: Int or tuple of the patch size over the full image size. Patch size for smaller inputs will be computed accordingly. :param hooks: Index of intermediate layers :param layer_dims: Dimension of intermediate layers :param feature_dim: Feature dimension :param last_dim: out_channels/in_channels for the last two Conv2d when head_type == regression :param use_bn: If set to True, activates batch norm :param dim_tokens_enc: Dimension of tokens coming from encoder """
def __init__(self, num_channels: int = 1, stride_level: int = 1, patch_size: Union[int, Tuple[int, int]] = 16, main_tasks: Iterable[str] = ('rgb',), hooks: List[int] = [2, 5, 8, 11], layer_dims: List[int] = [96, 192, 384, 768], feature_dim: int = 256, last_dim: int = 32, use_bn: bool = False, dim_tokens_enc: Optional[int] = None, head_type: str = 'regression', output_width_ratio=1, **kwargs): super().__init__() self.num_channels = num_channels self.stride_level = stride_level self.patch_size = pair(patch_size) self.main_tasks = main_tasks self.hooks = hooks self.layer_dims = layer_dims self.feature_dim = feature_dim self.dim_tokens_enc = dim_tokens_enc * len(self.main_tasks) if dim_tokens_enc is not None else None self.head_type = head_type
# Actual patch height and width, taking into account stride of input self.P_H = max(1, self.patch_size[0] // stride_level) self.P_W = max(1, self.patch_size[1] // stride_level)
self.scratch = make_scratch(layer_dims, feature_dim, groups=1, expand=False)
self.scratch.refinenet1 = make_fusion_block(feature_dim, use_bn, output_width_ratio) self.scratch.refinenet2 = make_fusion_block(feature_dim, use_bn, output_width_ratio) self.scratch.refinenet3 = make_fusion_block(feature_dim, use_bn, output_width_ratio) self.scratch.refinenet4 = make_fusion_block(feature_dim, use_bn, output_width_ratio)
if self.head_type == 'regression': # The "DPTDepthModel" head self.head = nn.Sequential( nn.Conv2d(feature_dim, feature_dim // 2, kernel_size=3, stride=1, padding=1), Interpolate(scale_factor=2, mode="bilinear", align_corners=True), nn.Conv2d(feature_dim // 2, last_dim, kernel_size=3, stride=1, padding=1), nn.ReLU(True), nn.Conv2d(last_dim, self.num_channels, kernel_size=1, stride=1, padding=0) ) elif self.head_type == 'semseg': # The "DPTSegmentationModel" head self.head = nn.Sequential( nn.Conv2d(feature_dim, feature_dim, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(feature_dim) if use_bn else nn.Identity(), nn.ReLU(True), nn.Dropout(0.1, False), nn.Conv2d(feature_dim, self.num_channels, kernel_size=1), Interpolate(scale_factor=2, mode="bilinear", align_corners=True), ) else: raise ValueError('DPT head_type must be "regression" or "semseg".')
if self.dim_tokens_enc is not None: self.init(dim_tokens_enc=dim_tokens_enc)
def init(self, dim_tokens_enc=768): """ Initialize parts of decoder that are dependent on dimension of encoder tokens. Should be called when setting up MultiMAE.
:param dim_tokens_enc: Dimension of tokens coming from encoder """ #print(dim_tokens_enc)
# Set up activation postprocessing layers if isinstance(dim_tokens_enc, int): dim_tokens_enc = 4 * [dim_tokens_enc]
self.dim_tokens_enc = [dt * len(self.main_tasks) for dt in dim_tokens_enc]
self.act_1_postprocess = nn.Sequential( nn.Conv2d( in_channels=self.dim_tokens_enc[0], out_channels=self.layer_dims[0], kernel_size=1, stride=1, padding=0, ), nn.ConvTranspose2d( in_channels=self.layer_dims[0], out_channels=self.layer_dims[0], kernel_size=4, stride=4, padding=0, bias=True, dilation=1, groups=1, ) )
self.act_2_postprocess = nn.Sequential( nn.Conv2d( in_channels=self.dim_tokens_enc[1], out_channels=self.layer_dims[1], kernel_size=1, stride=1, padding=0, ), nn.ConvTranspose2d( in_channels=self.layer_dims[1], out_channels=self.layer_dims[1], kernel_size=2, stride=2, padding=0, bias=True, dilation=1, groups=1, ) )
self.act_3_postprocess = nn.Sequential( nn.Conv2d( in_channels=self.dim_tokens_enc[2], out_channels=self.layer_dims[2], kernel_size=1, stride=1, padding=0, ) )
self.act_4_postprocess = nn.Sequential( nn.Conv2d( in_channels=self.dim_tokens_enc[3], out_channels=self.layer_dims[3], kernel_size=1, stride=1, padding=0, ), nn.Conv2d( in_channels=self.layer_dims[3], out_channels=self.layer_dims[3], kernel_size=3, stride=2, padding=1, ) )
self.act_postprocess = nn.ModuleList([ self.act_1_postprocess, self.act_2_postprocess, self.act_3_postprocess, self.act_4_postprocess ])
def adapt_tokens(self, encoder_tokens): # Adapt tokens x = [] x.append(encoder_tokens[:, :]) x = torch.cat(x, dim=-1) return x
def forward(self, encoder_tokens: List[torch.Tensor], image_size): #input_info: Dict): assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' H, W = image_size # Number of patches in height and width N_H = H // (self.stride_level * self.P_H) N_W = W // (self.stride_level * self.P_W)
# Hook decoder onto 4 layers from specified ViT layers layers = [encoder_tokens[hook] for hook in self.hooks]
# Extract only task-relevant tokens and ignore global tokens. layers = [self.adapt_tokens(l) for l in layers]
# Reshape tokens to spatial representation layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] # Project layers to chosen feature dim layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
# Fuse layers using refinement stages path_4 = self.scratch.refinenet4(layers[3]) path_3 = self.scratch.refinenet3(path_4, layers[2]) path_2 = self.scratch.refinenet2(path_3, layers[1]) path_1 = self.scratch.refinenet1(path_2, layers[0])
# Output head out = self.head(path_1)
return out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Heads for downstream tasks# --------------------------------------------------------
"""A head is a module where the __init__ defines only the head hyperparameters.A method setup(croconet) takes a CroCoNet and set all layers according to the head and croconet attributes.The forward takes the features as well as a dictionary img_info containing the keys 'width' and 'height'"""
import torchimport torch.nn as nnfrom .dpt_block import DPTOutputAdapter
class PixelwiseTaskWithDPT(nn.Module): """ DPT module for CroCo. by default, hooks_idx will be equal to: * for encoder-only: 4 equally spread layers * for encoder+decoder: last encoder + 3 equally spread layers of the decoder """
def __init__(self, *, hooks_idx=None, layer_dims=[96,192,384,768], output_width_ratio=1, num_channels=1, postprocess=None, **kwargs): super(PixelwiseTaskWithDPT, self).__init__() self.return_all_blocks = True # backbone needs to return all layers self.postprocess = postprocess self.output_width_ratio = output_width_ratio self.num_channels = num_channels self.hooks_idx = hooks_idx self.layer_dims = layer_dims def setup(self, croconet): dpt_args = {'output_width_ratio': self.output_width_ratio, 'num_channels': self.num_channels} if self.hooks_idx is None: if hasattr(croconet, 'dec_blocks'): # encoder + decoder step = {8: 3, 12: 4, 24: 8}[croconet.dec_depth] hooks_idx = [croconet.dec_depth+croconet.enc_depth-1-i*step for i in range(3,-1,-1)] else: # encoder only step = croconet.enc_depth//4 hooks_idx = [croconet.enc_depth-1-i*step for i in range(3,-1,-1)] self.hooks_idx = hooks_idx print(f' PixelwiseTaskWithDPT: automatically setting hook_idxs={self.hooks_idx}') dpt_args['hooks'] = self.hooks_idx dpt_args['layer_dims'] = self.layer_dims self.dpt = DPTOutputAdapter(**dpt_args) dim_tokens = [croconet.enc_embed_dim if hook<croconet.enc_depth else croconet.dec_embed_dim for hook in self.hooks_idx] dpt_init_args = {'dim_tokens_enc': dim_tokens} self.dpt.init(**dpt_init_args)
def forward(self, x, img_info): out = self.dpt(x, image_size=(img_info['height'],img_info['width'])) if self.postprocess: out = self.postprocess(out) return out12345678910111213141516171819202122232425# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Masking utils# --------------------------------------------------------
import torchimport torch.nn as nn class RandomMask(nn.Module): """ random masking """
def __init__(self, num_patches, mask_ratio): super().__init__() self.num_patches = num_patches self.num_mask = int(mask_ratio * self.num_patches) def __call__(self, x): noise = torch.rand(x.size(0), self.num_patches, device=x.device) argsort = torch.argsort(noise, dim=1) return argsort < self.num_mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Position embedding utils# --------------------------------------------------------
import numpy as np
import torch
# --------------------------------------------------------# 2D sine-cosine position embedding# References:# MAE: https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py# Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py# MoCo v3: https://github.com/facebookresearch/moco-v3# --------------------------------------------------------def get_2d_sincos_pos_embed(embed_dim, grid_size, n_cls_token=0): """ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [n_cls_token+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) """ grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0)
grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if n_cls_token>0: pos_embed = np.concatenate([np.zeros([n_cls_token, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): 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 = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) """ assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=float) omega /= embed_dim / 2. omega = 1. / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2) emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) return emb
# --------------------------------------------------------# Interpolate position embeddings for high-resolution# References:# MAE: https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py# DeiT: https://github.com/facebookresearch/deit# --------------------------------------------------------def interpolate_pos_embed(model, checkpoint_model): if 'pos_embed' in checkpoint_model: pos_embed_checkpoint = checkpoint_model['pos_embed'] embedding_size = pos_embed_checkpoint.shape[-1] num_patches = model.patch_embed.num_patches num_extra_tokens = model.pos_embed.shape[-2] - num_patches # height (== width) for the checkpoint position embedding orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) # height (== width) for the new position embedding new_size = int(num_patches ** 0.5) # class_token and dist_token are kept unchanged if orig_size != new_size: print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] # only the position tokens are interpolated pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) pos_tokens = torch.nn.functional.interpolate( pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) checkpoint_model['pos_embed'] = new_pos_embed
#----------------------------------------------------------# RoPE2D: RoPE implementation in 2D#----------------------------------------------------------
try: from models.curope import cuRoPE2D RoPE2D = cuRoPE2Dexcept ImportError: print('Warning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead')
class RoPE2D(torch.nn.Module): def __init__(self, freq=100.0, F0=1.0): super().__init__() self.base = freq self.F0 = F0 self.cache = {}
def get_cos_sin(self, D, seq_len, device, dtype): if (D,seq_len,device,dtype) not in self.cache: inv_freq = 1.0 / (self.base ** (torch.arange(0, D, 2).float().to(device) / D)) t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) freqs = torch.einsum("i,j->ij", t, inv_freq).to(dtype) freqs = torch.cat((freqs, freqs), dim=-1) cos = freqs.cos() # (Seq, Dim) sin = freqs.sin() self.cache[D,seq_len,device,dtype] = (cos,sin) return self.cache[D,seq_len,device,dtype] @staticmethod def rotate_half(x): x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rope1d(self, tokens, pos1d, cos, sin): assert pos1d.ndim==2 cos = torch.nn.functional.embedding(pos1d, cos)[:, None, :, :] sin = torch.nn.functional.embedding(pos1d, sin)[:, None, :, :] return (tokens * cos) + (self.rotate_half(tokens) * sin) def forward(self, tokens, positions): """ input: * tokens: batch_size x nheads x ntokens x dim * positions: batch_size x ntokens x 2 (y and x position of each token) output: * tokens after appplying RoPE2D (batch_size x nheads x ntokens x dim) """ assert tokens.size(3)%2==0, "number of dimensions should be a multiple of two" D = tokens.size(3) // 2 assert positions.ndim==3 and positions.shape[-1] == 2 # Batch, Seq, 2 cos, sin = self.get_cos_sin(D, int(positions.max())+1, tokens.device, tokens.dtype) # split features into two along the feature dimension, and apply rope1d on each half y, x = tokens.chunk(2, dim=-1) y = self.apply_rope1d(y, positions[:,:,0], cos, sin) x = self.apply_rope1d(x, positions[:,:,1], cos, sin) tokens = torch.cat((y, x), dim=-1) return tokens123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).# # --------------------------------------------------------# Pre-training CroCo # --------------------------------------------------------# References:# MAE: https://github.com/facebookresearch/mae# DeiT: https://github.com/facebookresearch/deit# BEiT: https://github.com/microsoft/unilm/tree/master/beit# --------------------------------------------------------import argparseimport datetimeimport jsonimport numpy as npimport osimport sysimport timeimport math from pathlib import Pathfrom typing import Iterable
import torchimport torch.distributed as distimport torch.backends.cudnn as cudnnfrom torch.utils.tensorboard import SummaryWriterimport torchvision.transforms as transformsimport torchvision.datasets as datasets
import utils.misc as miscfrom utils.misc import NativeScalerWithGradNormCount as NativeScalerfrom models.croco import CroCoNetfrom models.criterion import MaskedMSEfrom datasets.pairs_dataset import PairsDataset
def get_args_parser(): parser = argparse.ArgumentParser('CroCo pre-training', add_help=False) # model and criterion parser.add_argument('--model', default='CroCoNet()', type=str, help="string containing the model to build") parser.add_argument('--norm_pix_loss', default=1, choices=[0,1], help="apply per-patch mean/std normalization before applying the loss") # dataset parser.add_argument('--dataset', default='habitat_release', type=str, help="training set") parser.add_argument('--transforms', default='crop224+acolor', type=str, help="transforms to apply") # in the paper, we also use some homography and rotation, but find later that they were not useful or even harmful # training parser.add_argument('--seed', default=0, type=int, help="Random seed") parser.add_argument('--batch_size', default=64, type=int, help="Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus") parser.add_argument('--epochs', default=800, type=int, help="Maximum number of epochs for the scheduler") parser.add_argument('--max_epoch', default=400, type=int, help="Stop training at this epoch") parser.add_argument('--accum_iter', default=1, type=int, help="Accumulate gradient iterations (for increasing the effective batch size under memory constraints)") parser.add_argument('--weight_decay', type=float, default=0.05, help="weight decay (default: 0.05)") parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=1.5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--min_lr', type=float, default=0., metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=40, metavar='N', help='epochs to warmup LR') parser.add_argument('--amp', type=int, default=1, choices=[0,1], help="Use Automatic Mixed Precision for pretraining") # others parser.add_argument('--num_workers', default=8, type=int) parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') parser.add_argument('--save_freq', default=1, type=int, help='frequence (number of epochs) to save checkpoint in checkpoint-last.pth') parser.add_argument('--keep_freq', default=20, type=int, help='frequence (number of epochs) to save checkpoint in checkpoint-%d.pth') parser.add_argument('--print_freq', default=20, type=int, help='frequence (number of iterations) to print infos while training') # paths parser.add_argument('--output_dir', default='./output/', type=str, help="path where to save the output") parser.add_argument('--data_dir', default='./data/', type=str, help="path where data are stored") return parser
def main(args): misc.init_distributed_mode(args) global_rank = misc.get_rank() world_size = misc.get_world_size() print("output_dir: "+args.output_dir) if args.output_dir: Path(args.output_dir).mkdir(parents=True, exist_ok=True)
# auto resume last_ckpt_fname = os.path.join(args.output_dir, f'checkpoint-last.pth') args.resume = last_ckpt_fname if os.path.isfile(last_ckpt_fname) else None
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n'))
device = "cuda" if torch.cuda.is_available() else "cpu" device = torch.device(device)
# fix the seed seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed)
cudnn.benchmark = True
## training dataset and loader print('Building dataset for {:s} with transforms {:s}'.format(args.dataset, args.transforms)) dataset = PairsDataset(args.dataset, trfs=args.transforms, data_dir=args.data_dir) if world_size>1: sampler_train = torch.utils.data.DistributedSampler( dataset, num_replicas=world_size, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) else: sampler_train = torch.utils.data.RandomSampler(dataset) data_loader_train = torch.utils.data.DataLoader( dataset, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=True, drop_last=True, ) ## model print('Loading model: {:s}'.format(args.model)) model = eval(args.model) print('Loading criterion: MaskedMSE(norm_pix_loss={:s})'.format(str(bool(args.norm_pix_loss)))) criterion = MaskedMSE(norm_pix_loss=bool(args.norm_pix_loss)) model.to(device) model_without_ddp = model print("Model = %s" % str(model_without_ddp))
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size)
if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True, static_graph=True) model_without_ddp = model.module param_groups = misc.get_parameter_groups(model_without_ddp, args.weight_decay) # following timm: set wd as 0 for bias and norm layers optimizer = torch.optim.AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95)) print(optimizer) loss_scaler = NativeScaler()
misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
if global_rank == 0 and args.output_dir is not None: log_writer = SummaryWriter(log_dir=args.output_dir) else: log_writer = None
print(f"Start training until {args.max_epoch} epochs") start_time = time.time() for epoch in range(args.start_epoch, args.max_epoch): if world_size>1: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, log_writer=log_writer, args=args ) if args.output_dir and epoch % args.save_freq == 0 : misc.save_model( args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch, fname='last') if args.output_dir and (epoch % args.keep_freq == 0 or epoch + 1 == args.max_epoch) and (epoch>0 or args.max_epoch==1): misc.save_model( args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch)
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch,}
if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n")
total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str))
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, log_writer=None, args=None): model.train(True) metric_logger = misc.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}')) header = 'Epoch: [{}]'.format(epoch) accum_iter = args.accum_iter
optimizer.zero_grad()
if log_writer is not None: print('log_dir: {}'.format(log_writer.log_dir))
for data_iter_step, (image1, image2) in enumerate(metric_logger.log_every(data_loader, args.print_freq, header)):
# we use a per iteration lr scheduler if data_iter_step % accum_iter == 0: misc.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
image1 = image1.to(device, non_blocking=True) image2 = image2.to(device, non_blocking=True) with torch.cuda.amp.autocast(enabled=bool(args.amp)): out, mask, target = model(image1, image2) loss = criterion(out, mask, target)
loss_value = loss.item()
if not math.isfinite(loss_value): print("Loss is {}, stopping training".format(loss_value)) sys.exit(1)
loss /= accum_iter loss_scaler(loss, optimizer, parameters=model.parameters(), update_grad=(data_iter_step + 1) % accum_iter == 0) if (data_iter_step + 1) % accum_iter == 0: optimizer.zero_grad()
torch.cuda.synchronize()
metric_logger.update(loss=loss_value)
lr = optimizer.param_groups[0]["lr"] metric_logger.update(lr=lr)
loss_value_reduce = misc.all_reduce_mean(loss_value) if log_writer is not None and ((data_iter_step + 1) % (accum_iter*args.print_freq)) == 0: # x-axis is based on epoch_1000x in the tensorboard, calibrating differences curves when batch size changes epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000) log_writer.add_scalar('train_loss', loss_value_reduce, epoch_1000x) log_writer.add_scalar('lr', lr, epoch_1000x)
# gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
if __name__ == '__main__': args = get_args_parser() args = args.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318## CroCo-Stereo and CroCo-Flow
This README explains how to use CroCo-Stereo and CroCo-Flow as well as how they were trained.All commands should be launched from the root directory.
### Simple inference example
We provide a simple inference exemple for CroCo-Stereo and CroCo-Flow in the Totebook `croco-stereo-flow-demo.ipynb`.Before running it, please download the trained models with:```bash stereoflow/download_model.sh crocostereo.pthbash stereoflow/download_model.sh crocoflow.pth```
### Prepare data for training or evaluation
Put the datasets used for training/evaluation in `./data/stereoflow` (or update the paths at the top of `stereoflow/datasets_stereo.py` and `stereoflow/datasets_flow.py`).Please find below on the file structure should look for each dataset:<details><summary>FlyingChairs</summary>
```./data/stereoflow/FlyingChairs/└───chairs_split.txt└───data/ └─── ...```</details>
<details><summary>MPI-Sintel</summary>
```./data/stereoflow/MPI-Sintel/└───training/│ └───clean/│ └───final/│ └───flow/└───test/ └───clean/ └───final/```</details>
<details><summary>SceneFlow (including FlyingThings)</summary>
```./data/stereoflow/SceneFlow/└───Driving/│ └───disparity/│ └───frames_cleanpass/│ └───frames_finalpass/└───FlyingThings/│ └───disparity/│ └───frames_cleanpass/│ └───frames_finalpass/│ └───optical_flow/└───Monkaa/ └───disparity/ └───frames_cleanpass/ └───frames_finalpass/```</details>
<details><summary>TartanAir</summary>
```./data/stereoflow/TartanAir/└───abandonedfactory/│ └───.../└───abandonedfactory_night/│ └───.../└───.../```</details>
<details><summary>Booster</summary>
```./data/stereoflow/booster_gt/└───train/ └───balanced/ └───Bathroom/ └───Bedroom/ └───...```</details>
<details><summary>CREStereo</summary>
```./data/stereoflow/crenet_stereo_trainset/└───stereo_trainset/ └───crestereo/ └───hole/ └───reflective/ └───shapenet/ └───tree/```</details>
<details><summary>ETH3D Two-view Low-res</summary>
```./data/stereoflow/eth3d_lowres/└───test/│ └───lakeside_1l/│ └───...└───train/│ └───delivery_area_1l/│ └───...└───train_gt/ └───delivery_area_1l/ └───...```</details>
<details><summary>KITTI 2012</summary>
```./data/stereoflow/kitti-stereo-2012/└───testing/│ └───colored_0/│ └───colored_1/└───training/ └───colored_0/ └───colored_1/ └───disp_occ/ └───flow_occ/```</details>
<details><summary>KITTI 2015</summary>
```./data/stereoflow/kitti-stereo-2015/└───testing/│ └───image_2/│ └───image_3/└───training/ └───image_2/ └───image_3/ └───disp_occ_0/ └───flow_occ/```</details>
<details><summary>Middlebury</summary>
```./data/stereoflow/middlebury└───2005/│ └───train/│ └───Art/│ └───...└───2006/│ └───Aloe/│ └───Baby1/│ └───...└───2014/│ └───Adirondack-imperfect/│ └───Adirondack-perfect/│ └───...└───2021/│ └───data/│ └───artroom1/│ └───artroom2/│ └───...└───MiddEval3_F/ └───test/ │ └───Australia/ │ └───... └───train/ └───Adirondack/ └───...```</details>
<details><summary>Spring</summary>
```./data/stereoflow/spring/└───test/│ └───0003/│ └───...└───train/ └───0001/ └───...```</details>
### CroCo-Stereo
##### Main model
The main training of CroCo-Stereo was performed on a series of datasets, and it was used as it for Middlebury v3 benchmark.
```# Download the modelbash stereoflow/download_model.sh crocostereo.pth# Middlebury v3 submissionpython stereoflow/test.py --model stereoflow_models/crocostereo.pth --dataset "MdEval3('all_full')" --save submission --tile_overlap 0.9# Training command that was used, using checkpoint-last.pthpython -u stereoflow/train.py stereo --criterion "LaplacianLossBounded2()" --dataset "CREStereo('train')+SceneFlow('train_allpass')+30*ETH3DLowRes('train')+50*Md05('train')+50*Md06('train')+50*Md14('train')+50*Md21('train')+50*MdEval3('train_full')+Booster('train_balanced')" --val_dataset "SceneFlow('test1of100_finalpass')+SceneFlow('test1of100_cleanpass')+ETH3DLowRes('subval')+Md05('subval')+Md06('subval')+Md14('subval')+Md21('subval')+MdEval3('subval_full')+Booster('subval_balanced')" --lr 3e-5 --batch_size 6 --epochs 32 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --output_dir xps/crocostereo/main/# or it can be launched on multiple gpus (while maintaining the effective batch size), e.g. on 3 gpus:torchrun --nproc_per_node 3 stereoflow/train.py stereo --criterion "LaplacianLossBounded2()" --dataset "CREStereo('train')+SceneFlow('train_allpass')+30*ETH3DLowRes('train')+50*Md05('train')+50*Md06('train')+50*Md14('train')+50*Md21('train')+50*MdEval3('train_full')+Booster('train_balanced')" --val_dataset "SceneFlow('test1of100_finalpass')+SceneFlow('test1of100_cleanpass')+ETH3DLowRes('subval')+Md05('subval')+Md06('subval')+Md14('subval')+Md21('subval')+MdEval3('subval_full')+Booster('subval_balanced')" --lr 3e-5 --batch_size 2 --epochs 32 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --output_dir xps/crocostereo/main/```
For evaluation of validation set, we also provide the model trained on the `subtrain` subset of the training sets.
```# Download the modelbash stereoflow/download_model.sh crocostereo_subtrain.pth# Evaluation on validation sets python stereoflow/test.py --model stereoflow_models/crocostereo_subtrain.pth --dataset "MdEval3('subval_full')+ETH3DLowRes('subval')+SceneFlow('test_finalpass')+SceneFlow('test_cleanpass')" --save metrics --tile_overlap 0.9# Training command that was used (same as above but on subtrain, using checkpoint-best.pth), can also be launched on multiple gpuspython -u stereoflow/train.py stereo --criterion "LaplacianLossBounded2()" --dataset "CREStereo('train')+SceneFlow('train_allpass')+30*ETH3DLowRes('subtrain')+50*Md05('subtrain')+50*Md06('subtrain')+50*Md14('subtrain')+50*Md21('subtrain')+50*MdEval3('subtrain_full')+Booster('subtrain_balanced')" --val_dataset "SceneFlow('test1of100_finalpass')+SceneFlow('test1of100_cleanpass')+ETH3DLowRes('subval')+Md05('subval')+Md06('subval')+Md14('subval')+Md21('subval')+MdEval3('subval_full')+Booster('subval_balanced')" --lr 3e-5 --batch_size 6 --epochs 32 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --output_dir xps/crocostereo/main_subtrain/```
##### Other models
<details> <summary>Model for ETH3D</summary> The model used for the submission on ETH3D is trained with the same command but using an unbounded Laplacian loss. # Download the model bash stereoflow/download_model.sh crocostereo_eth3d.pth # ETH3D submission python stereoflow/test.py --model stereoflow_models/crocostereo_eth3d.pth --dataset "ETH3DLowRes('all')" --save submission --tile_overlap 0.9 # Training command that was used python -u stereoflow/train.py stereo --criterion "LaplacianLoss()" --tile_conf_mode conf_expbeta3 --dataset "CREStereo('train')+SceneFlow('train_allpass')+30*ETH3DLowRes('train')+50*Md05('train')+50*Md06('train')+50*Md14('train')+50*Md21('train')+50*MdEval3('train_full')+Booster('train_balanced')" --val_dataset "SceneFlow('test1of100_finalpass')+SceneFlow('test1of100_cleanpass')+ETH3DLowRes('subval')+Md05('subval')+Md06('subval')+Md14('subval')+Md21('subval')+MdEval3('subval_full')+Booster('subval_balanced')" --lr 3e-5 --batch_size 6 --epochs 32 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --output_dir xps/crocostereo/main_eth3d/ </details>
<details> <summary>Main model finetuned on Kitti</summary> # Download the model bash stereoflow/download_model.sh crocostereo_finetune_kitti.pth # Kitti submission python stereoflow/test.py --model stereoflow_models/crocostereo_finetune_kitti.pth --dataset "Kitti15('test')" --save submission --tile_overlap 0.9 # Training that was used python -u stereoflow/train.py stereo --crop 352 1216 --criterion "LaplacianLossBounded2()" --dataset "Kitti12('train')+Kitti15('train')" --lr 3e-5 --batch_size 1 --accum_iter 6 --epochs 20 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --start_from stereoflow_models/crocostereo.pth --output_dir xps/crocostereo/finetune_kitti/ --save_every 5</details>
<details> <summary>Main model finetuned on Spring</summary> # Download the model bash stereoflow/download_model.sh crocostereo_finetune_spring.pth # Spring submission python stereoflow/test.py --model stereoflow_models/crocostereo_finetune_spring.pth --dataset "Spring('test')" --save submission --tile_overlap 0.9 # Training command that was used python -u stereoflow/train.py stereo --criterion "LaplacianLossBounded2()" --dataset "Spring('train')" --lr 3e-5 --batch_size 6 --epochs 8 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --start_from stereoflow_models/crocostereo.pth --output_dir xps/crocostereo/finetune_spring/</details>
<details> <summary>Smaller models</summary> To train CroCo-Stereo with smaller CroCo pretrained models, simply replace the <code>--pretrained</code> argument. To download the smaller CroCo-Stereo models based on CroCo v2 pretraining with ViT-Base encoder and Small encoder, use <code>bash stereoflow/download_model.sh crocostereo_subtrain_vitb_smalldecoder.pth</code>, and for the model with a ViT-Base encoder and a Base decoder, use <code>bash stereoflow/download_model.sh crocostereo_subtrain_vitb_basedecoder.pth</code>.</details>
### CroCo-Flow
##### Main model
The main training of CroCo-Flow was performed on the FlyingThings, FlyingChairs, MPI-Sintel and TartanAir datasets.It was used for our submission to the MPI-Sintel benchmark.
```# Download the model bash stereoflow/download_model.sh crocoflow.pth# Evaluation python stereoflow/test.py --model stereoflow_models/crocoflow.pth --dataset "MPISintel('subval_cleanpass')+MPISintel('subval_finalpass')" --save metrics --tile_overlap 0.9# Sintel submissionpython stereoflow/test.py --model stereoflow_models/crocoflow.pth --dataset "MPISintel('test_allpass')" --save submission --tile_overlap 0.9# Training command that was used, with checkpoint-best.pthpython -u stereoflow/train.py flow --criterion "LaplacianLossBounded()" --dataset "40*MPISintel('subtrain_cleanpass')+40*MPISintel('subtrain_finalpass')+4*FlyingThings('train_allpass')+4*FlyingChairs('train')+TartanAir('train')" --val_dataset "MPISintel('subval_cleanpass')+MPISintel('subval_finalpass')" --lr 2e-5 --batch_size 8 --epochs 240 --img_per_epoch 30000 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --output_dir xps/crocoflow/main/```
##### Other models
<details> <summary>Main model finetuned on Kitti</summary> # Download the model bash stereoflow/download_model.sh crocoflow_finetune_kitti.pth # Kitti submission python stereoflow/test.py --model stereoflow_models/crocoflow_finetune_kitti.pth --dataset "Kitti15('test')" --save submission --tile_overlap 0.99 # Training that was used, with checkpoint-last.pth python -u stereoflow/train.py flow --crop 352 1216 --criterion "LaplacianLossBounded()" --dataset "Kitti15('train')+Kitti12('train')" --lr 2e-5 --batch_size 1 --accum_iter 8 --epochs 150 --save_every 5 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --start_from stereoflow_models/crocoflow.pth --output_dir xps/crocoflow/finetune_kitti/</details>
<details> <summary>Main model finetuned on Spring</summary> # Download the model bash stereoflow/download_model.sh crocoflow_finetune_spring.pth # Spring submission python stereoflow/test.py --model stereoflow_models/crocoflow_finetune_spring.pth --dataset "Spring('test')" --save submission --tile_overlap 0.9 # Training command that was used, with checkpoint-last.pth python -u stereoflow/train.py flow --criterion "LaplacianLossBounded()" --dataset "Spring('train')" --lr 2e-5 --batch_size 8 --epochs 12 --pretrained pretrained_models/CroCo_V2_ViTLarge_BaseDecoder.pth --start_from stereoflow_models/crocoflow.pth --output_dir xps/crocoflow/finetune_spring/</details>
<details> <summary>Smaller models</summary> To train CroCo-Flow with smaller CroCo pretrained models, simply replace the <code>--pretrained</code> argument. To download the smaller CroCo-Flow models based on CroCo v2 pretraining with ViT-Base encoder and Small encoder, use <code>bash stereoflow/download_model.sh crocoflow_vitb_smalldecoder.pth</code>, and for the model with a ViT-Base encoder and a Base decoder, use <code>bash stereoflow/download_model.sh crocoflow_vitb_basedecoder.pth</code>.</details>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Data augmentation for training stereo and flow# --------------------------------------------------------
# References# https://github.com/autonomousvision/unimatch/blob/master/dataloader/stereo/transforms.py# https://github.com/autonomousvision/unimatch/blob/master/dataloader/flow/transforms.py
import numpy as npimport randomfrom PIL import Image
import cv2cv2.setNumThreads(0)cv2.ocl.setUseOpenCL(False)
import torchfrom torchvision.transforms import ColorJitterimport torchvision.transforms.functional as FF
class StereoAugmentor(object):
def __init__(self, crop_size, scale_prob=0.5, scale_xonly=True, lhth=800., lminscale=0.0, lmaxscale=1.0, hminscale=-0.2, hmaxscale=0.4, scale_interp_nearest=True, rightjitterprob=0.5, v_flip_prob=0.5, color_aug_asym=True, color_choice_prob=0.5): self.crop_size = crop_size self.scale_prob = scale_prob self.scale_xonly = scale_xonly self.lhth = lhth self.lminscale = lminscale self.lmaxscale = lmaxscale self.hminscale = hminscale self.hmaxscale = hmaxscale self.scale_interp_nearest = scale_interp_nearest self.rightjitterprob = rightjitterprob self.v_flip_prob = v_flip_prob self.color_aug_asym = color_aug_asym self.color_choice_prob = color_choice_prob def _random_scale(self, img1, img2, disp): ch,cw = self.crop_size h,w = img1.shape[:2] if self.scale_prob>0. and np.random.rand()<self.scale_prob: min_scale, max_scale = (self.lminscale,self.lmaxscale) if min(h,w) < self.lhth else (self.hminscale,self.hmaxscale) scale_x = 2. ** np.random.uniform(min_scale, max_scale) scale_x = np.clip(scale_x, (cw+8) / float(w), None) scale_y = 1. if not self.scale_xonly: scale_y = scale_x scale_y = np.clip(scale_y, (ch+8) / float(h), None) img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) disp = cv2.resize(disp, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR if not self.scale_interp_nearest else cv2.INTER_NEAREST) * scale_x else: # check if we need to resize to be able to crop h,w = img1.shape[:2] clip_scale = (cw+8) / float(w) if clip_scale>1.: scale_x = clip_scale scale_y = scale_x if not self.scale_xonly else 1.0 img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) disp = cv2.resize(disp, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR if not self.scale_interp_nearest else cv2.INTER_NEAREST) * scale_x return img1, img2, disp def _random_crop(self, img1, img2, disp): h,w = img1.shape[:2] ch,cw = self.crop_size assert ch<=h and cw<=w, (img1.shape, h,w,ch,cw) offset_x = np.random.randint(w - cw + 1) offset_y = np.random.randint(h - ch + 1) img1 = img1[offset_y:offset_y+ch,offset_x:offset_x+cw] img2 = img2[offset_y:offset_y+ch,offset_x:offset_x+cw] disp = disp[offset_y:offset_y+ch,offset_x:offset_x+cw] return img1, img2, disp def _random_vflip(self, img1, img2, disp): # vertical flip if self.v_flip_prob>0 and np.random.rand() < self.v_flip_prob: img1 = np.copy(np.flipud(img1)) img2 = np.copy(np.flipud(img2)) disp = np.copy(np.flipud(disp)) return img1, img2, disp def _random_rotate_shift_right(self, img2): if self.rightjitterprob>0. and np.random.rand()<self.rightjitterprob: angle, pixel = 0.1, 2 px = np.random.uniform(-pixel, pixel) ag = np.random.uniform(-angle, angle) image_center = (np.random.uniform(0, img2.shape[0]), np.random.uniform(0, img2.shape[1]) ) rot_mat = cv2.getRotationMatrix2D(image_center, ag, 1.0) img2 = cv2.warpAffine(img2, rot_mat, img2.shape[1::-1], flags=cv2.INTER_LINEAR) trans_mat = np.float32([[1, 0, 0], [0, 1, px]]) img2 = cv2.warpAffine(img2, trans_mat, img2.shape[1::-1], flags=cv2.INTER_LINEAR) return img2 def _random_color_contrast(self, img1, img2): if np.random.random() < 0.5: contrast_factor = np.random.uniform(0.8, 1.2) img1 = FF.adjust_contrast(img1, contrast_factor) if self.color_aug_asym and np.random.random() < 0.5: contrast_factor = np.random.uniform(0.8, 1.2) img2 = FF.adjust_contrast(img2, contrast_factor) return img1, img2 def _random_color_gamma(self, img1, img2): if np.random.random() < 0.5: gamma = np.random.uniform(0.7, 1.5) img1 = FF.adjust_gamma(img1, gamma) if self.color_aug_asym and np.random.random() < 0.5: gamma = np.random.uniform(0.7, 1.5) img2 = FF.adjust_gamma(img2, gamma) return img1, img2 def _random_color_brightness(self, img1, img2): if np.random.random() < 0.5: brightness = np.random.uniform(0.5, 2.0) img1 = FF.adjust_brightness(img1, brightness) if self.color_aug_asym and np.random.random() < 0.5: brightness = np.random.uniform(0.5, 2.0) img2 = FF.adjust_brightness(img2, brightness) return img1, img2 def _random_color_hue(self, img1, img2): if np.random.random() < 0.5: hue = np.random.uniform(-0.1, 0.1) img1 = FF.adjust_hue(img1, hue) if self.color_aug_asym and np.random.random() < 0.5: hue = np.random.uniform(-0.1, 0.1) img2 = FF.adjust_hue(img2, hue) return img1, img2 def _random_color_saturation(self, img1, img2): if np.random.random() < 0.5: saturation = np.random.uniform(0.8, 1.2) img1 = FF.adjust_saturation(img1, saturation) if self.color_aug_asym and np.random.random() < 0.5: saturation = np.random.uniform(-0.8,1.2) img2 = FF.adjust_saturation(img2, saturation) return img1, img2 def _random_color(self, img1, img2): trfs = [self._random_color_contrast,self._random_color_gamma,self._random_color_brightness,self._random_color_hue,self._random_color_saturation] img1 = Image.fromarray(img1.astype('uint8')) img2 = Image.fromarray(img2.astype('uint8')) if np.random.random() < self.color_choice_prob: # A single transform t = random.choice(trfs) img1, img2 = t(img1, img2) else: # Combination of trfs # Random order random.shuffle(trfs) for t in trfs: img1, img2 = t(img1, img2) img1 = np.array(img1).astype(np.float32) img2 = np.array(img2).astype(np.float32) return img1, img2 def __call__(self, img1, img2, disp, dataset_name): img1, img2, disp = self._random_scale(img1, img2, disp) img1, img2, disp = self._random_crop(img1, img2, disp) img1, img2, disp = self._random_vflip(img1, img2, disp) img2 = self._random_rotate_shift_right(img2) img1, img2 = self._random_color(img1, img2) return img1, img2, disp
class FlowAugmentor:
def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, spatial_aug_prob=0.8, stretch_prob=0.8, max_stretch=0.2, h_flip_prob=0.5, v_flip_prob=0.1, asymmetric_color_aug_prob=0.2): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = spatial_aug_prob self.stretch_prob = stretch_prob self.max_stretch = max_stretch
# flip augmentation params self.h_flip_prob = h_flip_prob self.v_flip_prob = v_flip_prob
# photometric augmentation params self.photo_aug = ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.5 / 3.14)
self.asymmetric_color_aug_prob = asymmetric_color_aug_prob def color_transform(self, img1, img2): """ Photometric augmentation """
# asymmetric if np.random.rand() < self.asymmetric_color_aug_prob: img1 = np.array(self.photo_aug(Image.fromarray(img1)), dtype=np.uint8) img2 = np.array(self.photo_aug(Image.fromarray(img2)), dtype=np.uint8)
# symmetric else: image_stack = np.concatenate([img1, img2], axis=0) image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8) img1, img2 = np.split(image_stack, 2, axis=0)
return img1, img2
def _resize_flow(self, flow, scale_x, scale_y, factor=1.0): if np.all(np.isfinite(flow)): flow = cv2.resize(flow, None, fx=scale_x/factor, fy=scale_y/factor, interpolation=cv2.INTER_LINEAR) flow = flow * [scale_x, scale_y] else: # sparse version fx, fy = scale_x, scale_y ht, wd = flow.shape[:2] coords = np.meshgrid(np.arange(wd), np.arange(ht)) coords = np.stack(coords, axis=-1)
coords = coords.reshape(-1, 2).astype(np.float32) flow = flow.reshape(-1, 2).astype(np.float32) valid = np.isfinite(flow[:,0])
coords0 = coords[valid] flow0 = flow[valid]
ht1 = int(round(ht * fy/factor)) wd1 = int(round(wd * fx/factor)) rescale = np.expand_dims(np.array([fx, fy]), axis=0) coords1 = coords0 * rescale / factor flow1 = flow0 * rescale
xx = np.round(coords1[:, 0]).astype(np.int32) yy = np.round(coords1[:, 1]).astype(np.int32)
v = (xx > 0) & (xx < wd1) & (yy > 0) & (yy < ht1) xx = xx[v] yy = yy[v] flow1 = flow1[v]
flow = np.inf * np.ones([ht1, wd1, 2], dtype=np.float32) # invalid value every where, before we fill it with the correct ones flow[yy, xx] = flow1 return flow def spatial_transform(self, img1, img2, flow, dname): if np.random.rand() < self.spatial_aug_prob: # randomly sample scale ht, wd = img1.shape[:2] clip_min_scale = np.maximum( (self.crop_size[0] + 8) / float(ht), (self.crop_size[1] + 8) / float(wd)) min_scale, max_scale = self.min_scale, self.max_scale scale = 2 ** np.random.uniform(self.min_scale, self.max_scale) scale_x = scale scale_y = scale if np.random.rand() < self.stretch_prob: scale_x *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch) scale_y *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch) scale_x = np.clip(scale_x, clip_min_scale, None) scale_y = np.clip(scale_y, clip_min_scale, None) # rescale the images img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR) flow = self._resize_flow(flow, scale_x, scale_y, factor=2.0 if dname=='Spring' else 1.0) elif dname=="Spring": flow = self._resize_flow(flow, 1.0, 1.0, factor=2.0)
if self.h_flip_prob>0. and np.random.rand() < self.h_flip_prob: # h-flip img1 = img1[:, ::-1] img2 = img2[:, ::-1] flow = flow[:, ::-1] * [-1.0, 1.0]
if self.v_flip_prob>0. and np.random.rand() < self.v_flip_prob: # v-flip img1 = img1[::-1, :] img2 = img2[::-1, :] flow = flow[::-1, :] * [1.0, -1.0] # In case no cropping if img1.shape[0] - self.crop_size[0] > 0: y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0]) else: y0 = 0 if img1.shape[1] - self.crop_size[1] > 0: x0 = np.random.randint(0, img1.shape[1] - self.crop_size[1]) else: x0 = 0
img1 = img1[y0:y0 + self.crop_size[0], x0:x0 + self.crop_size[1]] img2 = img2[y0:y0 + self.crop_size[0], x0:x0 + self.crop_size[1]] flow = flow[y0:y0 + self.crop_size[0], x0:x0 + self.crop_size[1]]
return img1, img2, flow
def __call__(self, img1, img2, flow, dname): img1, img2, flow = self.spatial_transform(img1, img2, flow, dname) img1, img2 = self.color_transform(img1, img2) img1 = np.ascontiguousarray(img1) img2 = np.ascontiguousarray(img2) flow = np.ascontiguousarray(flow) return img1, img2, flow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Losses, metrics per batch, metrics per dataset # --------------------------------------------------------
import torchfrom torch import nnimport torch.nn.functional as F
def _get_gtnorm(gt): if gt.size(1)==1: # stereo return gt # flow return torch.sqrt(torch.sum(gt**2, dim=1, keepdims=True)) # Bx1xHxW
############ losses without confidence
class L1Loss(nn.Module): def __init__(self, max_gtnorm=None): super().__init__() self.max_gtnorm = max_gtnorm self.with_conf = False def _error(self, gt, predictions): return torch.abs(gt-predictions) def forward(self, predictions, gt, inspect=False): mask = torch.isfinite(gt) if self.max_gtnorm is not None: mask *= _get_gtnorm(gt).expand(-1,gt.size(1),-1,-1)<self.max_gtnorm if inspect: return self._error(gt, predictions) return self._error(gt[mask],predictions[mask]).mean()
############## losses with confience## there are several parametrizations
class LaplacianLoss(nn.Module): # used for CroCo-Stereo on ETH3D, d'=exp(d) def __init__(self, max_gtnorm=None): super().__init__() self.max_gtnorm = max_gtnorm self.with_conf = True def forward(self, predictions, gt, conf): mask = torch.isfinite(gt) mask = mask[:,0,:,:] if self.max_gtnorm is not None: mask *= _get_gtnorm(gt)[:,0,:,:]<self.max_gtnorm conf = conf.squeeze(1) return ( torch.abs(gt-predictions).sum(dim=1)[mask] / torch.exp(conf[mask]) + conf[mask] ).mean()# + torch.log(2) => which is a constant
class LaplacianLossBounded(nn.Module): # used for CroCo-Flow ; in the equation of the paper, we have a=1/b def __init__(self, max_gtnorm=10000., a=0.25, b=4.): super().__init__() self.max_gtnorm = max_gtnorm self.with_conf = True self.a, self.b = a, b def forward(self, predictions, gt, conf): mask = torch.isfinite(gt) mask = mask[:,0,:,:] if self.max_gtnorm is not None: mask *= _get_gtnorm(gt)[:,0,:,:]<self.max_gtnorm conf = conf.squeeze(1) conf = (self.b - self.a) * torch.sigmoid(conf) + self.a return ( torch.abs(gt-predictions).sum(dim=1)[mask] / conf[mask] + torch.log(conf)[mask] ).mean()# + torch.log(2) => which is a constant
class LaplacianLossBounded2(nn.Module): # used for CroCo-Stereo (except for ETH3D) ; in the equation of the paper, we have a=b def __init__(self, max_gtnorm=None, a=3.0, b=3.0): super().__init__() self.max_gtnorm = max_gtnorm self.with_conf = True self.a, self.b = a, b def forward(self, predictions, gt, conf): mask = torch.isfinite(gt) mask = mask[:,0,:,:] if self.max_gtnorm is not None: mask *= _get_gtnorm(gt)[:,0,:,:]<self.max_gtnorm conf = conf.squeeze(1) conf = 2 * self.a * (torch.sigmoid(conf / self.b) - 0.5 ) return ( torch.abs(gt-predictions).sum(dim=1)[mask] / torch.exp(conf[mask]) + conf[mask] ).mean()# + torch.log(2) => which is a constant ############## metrics per batch
class StereoMetrics(nn.Module):
def __init__(self, do_quantile=False): super().__init__() self.bad_ths = [0.5,1,2,3] self.do_quantile = do_quantile def forward(self, predictions, gt): B = predictions.size(0) metrics = {} gtcopy = gt.clone() mask = torch.isfinite(gtcopy) gtcopy[~mask] = 999999.0 # we make a copy and put a non-infinite value, such that it does not become nan once multiplied by the mask value 0 Npx = mask.view(B,-1).sum(dim=1) L1error = (torch.abs(gtcopy-predictions)*mask).view(B,-1) L2error = (torch.square(gtcopy-predictions)*mask).view(B,-1) # avgerr metrics['avgerr'] = torch.mean(L1error.sum(dim=1)/Npx ) # rmse metrics['rmse'] = torch.sqrt(L2error.sum(dim=1)/Npx).mean(dim=0) # err > t for t in [0.5,1,2,3] for ths in self.bad_ths: metrics['bad@{:.1f}'.format(ths)] = (((L1error>ths)* mask.view(B,-1)).sum(dim=1)/Npx).mean(dim=0) * 100 return metrics class FlowMetrics(nn.Module): def __init__(self): super().__init__() self.bad_ths = [1,3,5] def forward(self, predictions, gt): B = predictions.size(0) metrics = {} mask = torch.isfinite(gt[:,0,:,:]) # both x and y would be infinite Npx = mask.view(B,-1).sum(dim=1) gtcopy = gt.clone() # to compute L1/L2 error, we need to have non-infinite value, the error computed at this locations will be ignored gtcopy[:,0,:,:][~mask] = 999999.0 gtcopy[:,1,:,:][~mask] = 999999.0 L1error = (torch.abs(gtcopy-predictions).sum(dim=1)*mask).view(B,-1) L2error = (torch.sqrt(torch.sum(torch.square(gtcopy-predictions),dim=1))*mask).view(B,-1) metrics['L1err'] = torch.mean(L1error.sum(dim=1)/Npx ) metrics['EPE'] = torch.mean(L2error.sum(dim=1)/Npx ) for ths in self.bad_ths: metrics['bad@{:.1f}'.format(ths)] = (((L2error>ths)* mask.view(B,-1)).sum(dim=1)/Npx).mean(dim=0) * 100 return metrics ############## metrics per dataset## we update the average and maintain the number of pixels while adding data batch per batch ## at the beggining, call reset()## after each batch, call add_batch(...)## at the end: call get_results()
class StereoDatasetMetrics(nn.Module):
def __init__(self): super().__init__() self.bad_ths = [0.5,1,2,3] def reset(self): self.agg_N = 0 # number of pixels so far self.agg_L1err = torch.tensor(0.0) # L1 error so far self.agg_Nbad = [0 for _ in self.bad_ths] # counter of bad pixels self._metrics = None def add_batch(self, predictions, gt): assert predictions.size(1)==1, predictions.size() assert gt.size(1)==1, gt.size() if gt.size(2)==predictions.size(2)*2 and gt.size(3)==predictions.size(3)*2: # special case for Spring ... L1err = torch.minimum( torch.minimum( torch.minimum( torch.sum(torch.abs(gt[:,:,0::2,0::2]-predictions),dim=1), torch.sum(torch.abs(gt[:,:,1::2,0::2]-predictions),dim=1)), torch.sum(torch.abs(gt[:,:,0::2,1::2]-predictions),dim=1)), torch.sum(torch.abs(gt[:,:,1::2,1::2]-predictions),dim=1)) valid = torch.isfinite(L1err) else: valid = torch.isfinite(gt[:,0,:,:]) # both x and y would be infinite L1err = torch.sum(torch.abs(gt-predictions),dim=1) N = valid.sum() Nnew = self.agg_N + N self.agg_L1err = float(self.agg_N)/Nnew * self.agg_L1err + L1err[valid].mean().cpu() * float(N)/Nnew self.agg_N = Nnew for i,th in enumerate(self.bad_ths): self.agg_Nbad[i] += (L1err[valid]>th).sum().cpu() def _compute_metrics(self): if self._metrics is not None: return out = {} out['L1err'] = self.agg_L1err.item() for i,th in enumerate(self.bad_ths): out['bad@{:.1f}'.format(th)] = (float(self.agg_Nbad[i]) / self.agg_N).item() * 100.0 self._metrics = out def get_results(self): self._compute_metrics() # to avoid recompute them multiple times return self._metrics
class FlowDatasetMetrics(nn.Module): def __init__(self): super().__init__() self.bad_ths = [0.5,1,3,5] self.speed_ths = [(0,10),(10,40),(40,torch.inf)] def reset(self): self.agg_N = 0 # number of pixels so far self.agg_L1err = torch.tensor(0.0) # L1 error so far self.agg_L2err = torch.tensor(0.0) # L2 (=EPE) error so far self.agg_Nbad = [0 for _ in self.bad_ths] # counter of bad pixels self.agg_EPEspeed = [torch.tensor(0.0) for _ in self.speed_ths] # EPE per speed bin so far self.agg_Nspeed = [0 for _ in self.speed_ths] # N pixels per speed bin so far self._metrics = None self.pairname_results = {}
def add_batch(self, predictions, gt): assert predictions.size(1)==2, predictions.size() assert gt.size(1)==2, gt.size() if gt.size(2)==predictions.size(2)*2 and gt.size(3)==predictions.size(3)*2: # special case for Spring ... L1err = torch.minimum( torch.minimum( torch.minimum( torch.sum(torch.abs(gt[:,:,0::2,0::2]-predictions),dim=1), torch.sum(torch.abs(gt[:,:,1::2,0::2]-predictions),dim=1)), torch.sum(torch.abs(gt[:,:,0::2,1::2]-predictions),dim=1)), torch.sum(torch.abs(gt[:,:,1::2,1::2]-predictions),dim=1)) L2err = torch.minimum( torch.minimum( torch.minimum( torch.sqrt(torch.sum(torch.square(gt[:,:,0::2,0::2]-predictions),dim=1)), torch.sqrt(torch.sum(torch.square(gt[:,:,1::2,0::2]-predictions),dim=1))), torch.sqrt(torch.sum(torch.square(gt[:,:,0::2,1::2]-predictions),dim=1))), torch.sqrt(torch.sum(torch.square(gt[:,:,1::2,1::2]-predictions),dim=1))) valid = torch.isfinite(L1err) gtspeed = (torch.sqrt(torch.sum(torch.square(gt[:,:,0::2,0::2]),dim=1)) + torch.sqrt(torch.sum(torch.square(gt[:,:,0::2,1::2]),dim=1)) +\ torch.sqrt(torch.sum(torch.square(gt[:,:,1::2,0::2]),dim=1)) + torch.sqrt(torch.sum(torch.square(gt[:,:,1::2,1::2]),dim=1)) ) / 4.0 # let's just average them else: valid = torch.isfinite(gt[:,0,:,:]) # both x and y would be infinite L1err = torch.sum(torch.abs(gt-predictions),dim=1) L2err = torch.sqrt(torch.sum(torch.square(gt-predictions),dim=1)) gtspeed = torch.sqrt(torch.sum(torch.square(gt),dim=1)) N = valid.sum() Nnew = self.agg_N + N self.agg_L1err = float(self.agg_N)/Nnew * self.agg_L1err + L1err[valid].mean().cpu() * float(N)/Nnew self.agg_L2err = float(self.agg_N)/Nnew * self.agg_L2err + L2err[valid].mean().cpu() * float(N)/Nnew self.agg_N = Nnew for i,th in enumerate(self.bad_ths): self.agg_Nbad[i] += (L2err[valid]>th).sum().cpu() for i,(th1,th2) in enumerate(self.speed_ths): vv = (gtspeed[valid]>=th1) * (gtspeed[valid]<th2) iNspeed = vv.sum() if iNspeed==0: continue iNnew = self.agg_Nspeed[i] + iNspeed self.agg_EPEspeed[i] = float(self.agg_Nspeed[i]) / iNnew * self.agg_EPEspeed[i] + float(iNspeed) / iNnew * L2err[valid][vv].mean().cpu() self.agg_Nspeed[i] = iNnew
def _compute_metrics(self): if self._metrics is not None: return out = {} out['L1err'] = self.agg_L1err.item() out['EPE'] = self.agg_L2err.item() for i,th in enumerate(self.bad_ths): out['bad@{:.1f}'.format(th)] = (float(self.agg_Nbad[i]) / self.agg_N).item() * 100.0 for i,(th1,th2) in enumerate(self.speed_ths): out['s{:d}{:s}'.format(th1, '-'+str(th2) if th2<torch.inf else '+')] = self.agg_EPEspeed[i].item() self._metrics = out def get_results(self): self._compute_metrics() # to avoid recompute them multiple times return self._metrics123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Dataset structure for flow# --------------------------------------------------------
import osimport os.path as ospimport pickleimport numpy as npimport structfrom PIL import Image import jsonimport h5pyimport torchfrom torch.utils import data
from .augmentor import FlowAugmentorfrom .datasets_stereo import _read_img, img_to_tensor, dataset_to_root, _read_pfmfrom copy import deepcopydataset_to_root = deepcopy(dataset_to_root)
dataset_to_root.update(**{ 'TartanAir': './data/stereoflow/TartanAir', 'FlyingChairs': './data/stereoflow/FlyingChairs/', 'FlyingThings': osp.join(dataset_to_root['SceneFlow'],'FlyingThings')+'/', 'MPISintel': './data/stereoflow//MPI-Sintel/'+'/',})cache_dir = "./data/stereoflow/datasets_flow_cache/"
def flow_to_tensor(disp): return torch.from_numpy(disp).float().permute(2, 0, 1)
class FlowDataset(data.Dataset): def __init__(self, split, augmentor=False, crop_size=None, totensor=True): self.split = split if not augmentor: assert crop_size is None if crop_size is not None: assert augmentor self.crop_size = crop_size self.augmentor_str = augmentor self.augmentor = FlowAugmentor(crop_size) if augmentor else None self.totensor = totensor self.rmul = 1 # keep track of rmul self.has_constant_resolution = True # whether the dataset has constant resolution or not (=> don't use batch_size>1 at test time) self._prepare_data() self._load_or_build_cache() def prepare_data(self): """ to be defined for each dataset """ raise NotImplementedError def __len__(self): return len(self.pairnames) # each pairname is typically of the form (str, int1, int2) def __getitem__(self, index): pairname = self.pairnames[index] # get filenames img1name = self.pairname_to_img1name(pairname) img2name = self.pairname_to_img2name(pairname) flowname = self.pairname_to_flowname(pairname) if self.pairname_to_flowname is not None else None # load images and disparities img1 = _read_img(img1name) img2 = _read_img(img2name) flow = self.load_flow(flowname) if flowname is not None else None
# apply augmentations if self.augmentor is not None: img1, img2, flow = self.augmentor(img1, img2, flow, self.name) if self.totensor: img1 = img_to_tensor(img1) img2 = img_to_tensor(img2) if flow is not None: flow = flow_to_tensor(flow) else: flow = torch.tensor([]) # to allow dataloader batching with default collate_gn pairname = str(pairname) # transform potential tuple to str to be able to batch it
return img1, img2, flow, pairname def __rmul__(self, v): self.rmul *= v self.pairnames = v * self.pairnames return self def __str__(self): return f'{self.__class__.__name__}_{self.split}' def __repr__(self): s = f'{self.__class__.__name__}(split={self.split}, augmentor={self.augmentor_str}, crop_size={str(self.crop_size)}, totensor={self.totensor})' if self.rmul==1: s+=f'\n\tnum pairs: {len(self.pairnames)}' else: s+=f'\n\tnum pairs: {len(self.pairnames)} ({len(self.pairnames)//self.rmul}x{self.rmul})' return s
def _set_root(self): self.root = dataset_to_root[self.name] assert os.path.isdir(self.root), f"could not find root directory for dataset {self.name}: {self.root}"
def _load_or_build_cache(self): cache_file = osp.join(cache_dir, self.name+'.pkl') if osp.isfile(cache_file): with open(cache_file, 'rb') as fid: self.pairnames = pickle.load(fid)[self.split] else: tosave = self._build_cache() os.makedirs(cache_dir, exist_ok=True) with open(cache_file, 'wb') as fid: pickle.dump(tosave, fid) self.pairnames = tosave[self.split]
class TartanAirDataset(FlowDataset):
def _prepare_data(self): self.name = "TartanAir" self._set_root() assert self.split in ['train'] self.pairname_to_img1name = lambda pairname: osp.join(self.root, pairname[0], 'image_left/{:06d}_left.png'.format(pairname[1])) self.pairname_to_img2name = lambda pairname: osp.join(self.root, pairname[0], 'image_left/{:06d}_left.png'.format(pairname[2])) self.pairname_to_flowname = lambda pairname: osp.join(self.root, pairname[0], 'flow/{:06d}_{:06d}_flow.npy'.format(pairname[1],pairname[2])) self.pairname_to_str = lambda pairname: os.path.join(pairname[0][pairname[0].find('/')+1:], '{:06d}_{:06d}'.format(pairname[1], pairname[2])) self.load_flow = _read_numpy_flow def _build_cache(self): seqs = sorted(os.listdir(self.root)) pairs = [(osp.join(s,s,difficulty,Pxxx),int(a[:6]),int(a[:6])+1) for s in seqs for difficulty in ['Easy','Hard'] for Pxxx in sorted(os.listdir(osp.join(self.root,s,s,difficulty))) for a in sorted(os.listdir(osp.join(self.root,s,s,difficulty,Pxxx,'image_left/')))[:-1]] assert len(pairs)==306268, "incorrect parsing of pairs in TartanAir" tosave = {'train': pairs} return tosave class FlyingChairsDataset(FlowDataset):
def _prepare_data(self): self.name = "FlyingChairs" self._set_root() assert self.split in ['train','val'] self.pairname_to_img1name = lambda pairname: osp.join(self.root, 'data', pairname+'_img1.ppm') self.pairname_to_img2name = lambda pairname: osp.join(self.root, 'data', pairname+'_img2.ppm') self.pairname_to_flowname = lambda pairname: osp.join(self.root, 'data', pairname+'_flow.flo') self.pairname_to_str = lambda pairname: pairname self.load_flow = _read_flo_file def _build_cache(self): split_file = osp.join(self.root, 'chairs_split.txt') split_list = np.loadtxt(split_file, dtype=np.int32) trainpairs = ['{:05d}'.format(i) for i in np.where(split_list==1)[0]+1] valpairs = ['{:05d}'.format(i) for i in np.where(split_list==2)[0]+1] assert len(trainpairs)==22232 and len(valpairs)==640, "incorrect parsing of pairs in MPI-Sintel" tosave = {'train': trainpairs, 'val': valpairs} return tosave class FlyingThingsDataset(FlowDataset): def _prepare_data(self): self.name = "FlyingThings" self._set_root() assert self.split in [f'{set_}_{pass_}pass{camstr}' for set_ in ['train','test','test1024'] for camstr in ['','_rightcam'] for pass_ in ['clean','final','all']] self.pairname_to_img1name = lambda pairname: osp.join(self.root, f'frames_{pairname[3]}pass', pairname[0].replace('into_future','').replace('into_past',''), '{:04d}.png'.format(pairname[1])) self.pairname_to_img2name = lambda pairname: osp.join(self.root, f'frames_{pairname[3]}pass', pairname[0].replace('into_future','').replace('into_past',''), '{:04d}.png'.format(pairname[2])) self.pairname_to_flowname = lambda pairname: osp.join(self.root, 'optical_flow', pairname[0], 'OpticalFlowInto{f:s}_{i:04d}_{c:s}.pfm'.format(f='Future' if 'future' in pairname[0] else 'Past', i=pairname[1], c='L' if 'left' in pairname[0] else 'R' )) self.pairname_to_str = lambda pairname: os.path.join(pairname[3]+'pass', pairname[0], 'Into{f:s}_{i:04d}_{c:s}'.format(f='Future' if 'future' in pairname[0] else 'Past', i=pairname[1], c='L' if 'left' in pairname[0] else 'R' )) self.load_flow = _read_pfm_flow def _build_cache(self): tosave = {} # train and test splits for the different passes for set_ in ['train', 'test']: sroot = osp.join(self.root, 'optical_flow', set_.upper()) fname_to_i = lambda f: int(f[len('OpticalFlowIntoFuture_'):-len('_L.pfm')]) pp = [(osp.join(set_.upper(), d, s, 'into_future/left'),fname_to_i(fname)) for d in sorted(os.listdir(sroot)) for s in sorted(os.listdir(osp.join(sroot,d))) for fname in sorted(os.listdir(osp.join(sroot,d, s, 'into_future/left')))[:-1]] pairs = [(a,i,i+1) for a,i in pp] pairs += [(a.replace('into_future','into_past'),i+1,i) for a,i in pp] assert len(pairs)=={'train': 40302, 'test': 7866}[set_], "incorrect parsing of pairs Flying Things" for cam in ['left','right']: camstr = '' if cam=='left' else f'_{cam}cam' for pass_ in ['final', 'clean']: tosave[f'{set_}_{pass_}pass{camstr}'] = [(a.replace('left',cam),i,j,pass_) for a,i,j in pairs] tosave[f'{set_}_allpass{camstr}'] = tosave[f'{set_}_cleanpass{camstr}'] + tosave[f'{set_}_finalpass{camstr}'] # test1024: this is the same split as unimatch 'validation' split # see https://github.com/autonomousvision/unimatch/blob/master/dataloader/flow/datasets.py#L229 test1024_nsamples = 1024 alltest_nsamples = len(tosave['test_cleanpass']) # 7866 stride = alltest_nsamples // test1024_nsamples remove = alltest_nsamples % test1024_nsamples for cam in ['left','right']: camstr = '' if cam=='left' else f'_{cam}cam' for pass_ in ['final','clean']: tosave[f'test1024_{pass_}pass{camstr}'] = sorted(tosave[f'test_{pass_}pass{camstr}'])[:-remove][::stride] # warning, it was not sorted before assert len(tosave['test1024_cleanpass'])==1024, "incorrect parsing of pairs in Flying Things" tosave[f'test1024_allpass{camstr}'] = tosave[f'test1024_cleanpass{camstr}'] + tosave[f'test1024_finalpass{camstr}'] return tosave class MPISintelDataset(FlowDataset): def _prepare_data(self): self.name = "MPISintel" self._set_root() assert self.split in [s+'_'+p for s in ['train','test','subval','subtrain'] for p in ['cleanpass','finalpass','allpass']] self.pairname_to_img1name = lambda pairname: osp.join(self.root, pairname[0], 'frame_{:04d}.png'.format(pairname[1])) self.pairname_to_img2name = lambda pairname: osp.join(self.root, pairname[0], 'frame_{:04d}.png'.format(pairname[1]+1)) self.pairname_to_flowname = lambda pairname: None if pairname[0].startswith('test/') else osp.join(self.root, pairname[0].replace('/clean/','/flow/').replace('/final/','/flow/'), 'frame_{:04d}.flo'.format(pairname[1])) self.pairname_to_str = lambda pairname: osp.join(pairname[0], 'frame_{:04d}'.format(pairname[1])) self.load_flow = _read_flo_file def _build_cache(self): trainseqs = sorted(os.listdir(self.root+'training/clean')) trainpairs = [ (osp.join('training/clean', s),i) for s in trainseqs for i in range(1, len(os.listdir(self.root+'training/clean/'+s)))] subvalseqs = ['temple_2','temple_3'] subtrainseqs = [s for s in trainseqs if s not in subvalseqs] subvalpairs = [ (p,i) for p,i in trainpairs if any(s in p for s in subvalseqs)] subtrainpairs = [ (p,i) for p,i in trainpairs if any(s in p for s in subtrainseqs)] testseqs = sorted(os.listdir(self.root+'test/clean')) testpairs = [ (osp.join('test/clean', s),i) for s in testseqs for i in range(1, len(os.listdir(self.root+'test/clean/'+s)))] assert len(trainpairs)==1041 and len(testpairs)==552 and len(subvalpairs)==98 and len(subtrainpairs)==943, "incorrect parsing of pairs in MPI-Sintel" tosave = {} tosave['train_cleanpass'] = trainpairs tosave['test_cleanpass'] = testpairs tosave['subval_cleanpass'] = subvalpairs tosave['subtrain_cleanpass'] = subtrainpairs for t in ['train','test','subval','subtrain']: tosave[t+'_finalpass'] = [(p.replace('/clean/','/final/'),i) for p,i in tosave[t+'_cleanpass']] tosave[t+'_allpass'] = tosave[t+'_cleanpass'] + tosave[t+'_finalpass'] return tosave def submission_save_pairname(self, pairname, prediction, outdir, _time): assert prediction.shape[2]==2 outfile = os.path.join(outdir, 'submission', self.pairname_to_str(pairname)+'.flo') os.makedirs( os.path.dirname(outfile), exist_ok=True) writeFlowFile(prediction, outfile) def finalize_submission(self, outdir): assert self.split == 'test_allpass' bundle_exe = "/nfs/data/ffs-3d/datasets/StereoFlow/MPI-Sintel/bundler/linux-x64/bundler" # eg <bundle_exe> <path_to_results_for_clean> <path_to_results_for_final> <output/bundled.lzma> if os.path.isfile(bundle_exe): cmd = f'{bundle_exe} "{outdir}/submission/test/clean/" "{outdir}/submission/test/final" "{outdir}/submission/bundled.lzma"' print(cmd) os.system(cmd) print(f'Done. Submission file at: "{outdir}/submission/bundled.lzma"') else: print('Could not find bundler executable for submission.') print('Please download it and run:') print(f'<bundle_exe> "{outdir}/submission/test/clean/" "{outdir}/submission/test/final" "{outdir}/submission/bundled.lzma"') class SpringDataset(FlowDataset):
def _prepare_data(self): self.name = "Spring" self._set_root() assert self.split in ['train','test','subtrain','subval'] self.pairname_to_img1name = lambda pairname: osp.join(self.root, pairname[0], pairname[1], 'frame_'+pairname[3], 'frame_{:s}_{:04d}.png'.format(pairname[3], pairname[4])) self.pairname_to_img2name = lambda pairname: osp.join(self.root, pairname[0], pairname[1], 'frame_'+pairname[3], 'frame_{:s}_{:04d}.png'.format(pairname[3], pairname[4]+(1 if pairname[2]=='FW' else -1))) self.pairname_to_flowname = lambda pairname: None if pairname[0]=='test' else osp.join(self.root, pairname[0], pairname[1], f'flow_{pairname[2]}_{pairname[3]}', f'flow_{pairname[2]}_{pairname[3]}_{pairname[4]:04d}.flo5') self.pairname_to_str = lambda pairname: osp.join(pairname[0], pairname[1], f'flow_{pairname[2]}_{pairname[3]}', f'flow_{pairname[2]}_{pairname[3]}_{pairname[4]:04d}') self.load_flow = _read_hdf5_flow
def _build_cache(self): # train trainseqs = sorted(os.listdir( osp.join(self.root,'train'))) trainpairs = [] for leftright in ['left','right']: for fwbw in ['FW','BW']: trainpairs += [('train',s,fwbw,leftright,int(f[len(f'flow_{fwbw}_{leftright}_'):-len('.flo5')])) for s in trainseqs for f in sorted(os.listdir(osp.join(self.root,'train',s,f'flow_{fwbw}_{leftright}')))] # test testseqs = sorted(os.listdir( osp.join(self.root,'test'))) testpairs = [] for leftright in ['left','right']: testpairs += [('test',s,'FW',leftright,int(f[len(f'frame_{leftright}_'):-len('.png')])) for s in testseqs for f in sorted(os.listdir(osp.join(self.root,'test',s,f'frame_{leftright}')))[:-1]] testpairs += [('test',s,'BW',leftright,int(f[len(f'frame_{leftright}_'):-len('.png')])+1) for s in testseqs for f in sorted(os.listdir(osp.join(self.root,'test',s,f'frame_{leftright}')))[:-1]] # subtrain / subval subtrainpairs = [p for p in trainpairs if p[1]!='0041'] subvalpairs = [p for p in trainpairs if p[1]=='0041'] assert len(trainpairs)==19852 and len(testpairs)==3960 and len(subtrainpairs)==19472 and len(subvalpairs)==380, "incorrect parsing of pairs in Spring" tosave = {'train': trainpairs, 'test': testpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs} return tosave def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==3 assert prediction.shape[2]==2 assert prediction.dtype==np.float32 outfile = osp.join(outdir, pairname[0], pairname[1], f'flow_{pairname[2]}_{pairname[3]}', f'flow_{pairname[2]}_{pairname[3]}_{pairname[4]:04d}.flo5') os.makedirs( os.path.dirname(outfile), exist_ok=True) writeFlo5File(prediction, outfile) def finalize_submission(self, outdir): assert self.split=='test' exe = "{self.root}/flow_subsampling" if os.path.isfile(exe): cmd = f'cd "{outdir}/test"; {exe} .' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/test/flow_submission.hdf5') else: print('Could not find flow_subsampling executable for submission.') print('Please download it and run:') print(f'cd "{outdir}/test"; <flow_subsampling_exe> .')
class Kitti12Dataset(FlowDataset):
def _prepare_data(self): self.name = "Kitti12" self._set_root() assert self.split in ['train','test'] self.pairname_to_img1name = lambda pairname: osp.join(self.root, pairname+'_10.png') self.pairname_to_img2name = lambda pairname: osp.join(self.root, pairname+'_11.png') self.pairname_to_flowname = None if self.split=='test' else lambda pairname: osp.join(self.root, pairname.replace('/colored_0/','/flow_occ/')+'_10.png') self.pairname_to_str = lambda pairname: pairname.replace('/colored_0/','/') self.load_flow = _read_kitti_flow def _build_cache(self): trainseqs = ["training/colored_0/%06d"%(i) for i in range(194)] testseqs = ["testing/colored_0/%06d"%(i) for i in range(195)] assert len(trainseqs)==194 and len(testseqs)==195, "incorrect parsing of pairs in Kitti12" tosave = {'train': trainseqs, 'test': testseqs} return tosave
def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==3 assert prediction.shape[2]==2 outfile = os.path.join(outdir, pairname.split('/')[-1]+'_10.png') os.makedirs( os.path.dirname(outfile), exist_ok=True) writeFlowKitti(outfile, prediction)
def finalize_submission(self, outdir): assert self.split=='test' cmd = f'cd {outdir}/; zip -r "kitti12_flow_results.zip" .' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/kitti12_flow_results.zip')
class Kitti15Dataset(FlowDataset): def _prepare_data(self): self.name = "Kitti15" self._set_root() assert self.split in ['train','subtrain','subval','test'] self.pairname_to_img1name = lambda pairname: osp.join(self.root, pairname+'_10.png') self.pairname_to_img2name = lambda pairname: osp.join(self.root, pairname+'_11.png') self.pairname_to_flowname = None if self.split=='test' else lambda pairname: osp.join(self.root, pairname.replace('/image_2/','/flow_occ/')+'_10.png') self.pairname_to_str = lambda pairname: pairname.replace('/image_2/','/') self.load_flow = _read_kitti_flow def _build_cache(self): trainseqs = ["training/image_2/%06d"%(i) for i in range(200)] subtrainseqs = trainseqs[:-10] subvalseqs = trainseqs[-10:] testseqs = ["testing/image_2/%06d"%(i) for i in range(200)] assert len(trainseqs)==200 and len(subtrainseqs)==190 and len(subvalseqs)==10 and len(testseqs)==200, "incorrect parsing of pairs in Kitti15" tosave = {'train': trainseqs, 'subtrain': subtrainseqs, 'subval': subvalseqs, 'test': testseqs} return tosave
def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==3 assert prediction.shape[2]==2 outfile = os.path.join(outdir, 'flow', pairname.split('/')[-1]+'_10.png') os.makedirs( os.path.dirname(outfile), exist_ok=True) writeFlowKitti(outfile, prediction)
def finalize_submission(self, outdir): assert self.split=='test' cmd = f'cd {outdir}/; zip -r "kitti15_flow_results.zip" flow' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/kitti15_flow_results.zip')
import cv2def _read_numpy_flow(filename): return np.load(filename) def _read_pfm_flow(filename): f, _ = _read_pfm(filename) assert np.all(f[:,:,2]==0.0) return np.ascontiguousarray(f[:,:,:2])
TAG_FLOAT = 202021.25 # tag to check the sanity of the fileTAG_STRING = 'PIEH' # string containing the tagMIN_WIDTH = 1MAX_WIDTH = 99999MIN_HEIGHT = 1MAX_HEIGHT = 99999def readFlowFile(filename): """ readFlowFile(<FILENAME>) reads a flow file <FILENAME> into a 2-band np.array. if <FILENAME> does not exist, an IOError is raised. if <FILENAME> does not finish by '.flo' or the tag, the width, the height or the file's size is illegal, an Expcetion is raised. ---- PARAMETERS ---- filename: string containg the name of the file to read a flow ---- OUTPUTS ---- a np.array of dimension (height x width x 2) containing the flow of type 'float32' """ # check filename if not filename.endswith(".flo"): raise Exception("readFlowFile({:s}): filename must finish with '.flo'".format(filename)) # open the file and read it with open(filename,'rb') as f: # check tag tag = struct.unpack('f',f.read(4))[0] if tag != TAG_FLOAT: raise Exception("flow_utils.readFlowFile({:s}): wrong tag".format(filename)) # read dimension w,h = struct.unpack('ii',f.read(8)) if w < MIN_WIDTH or w > MAX_WIDTH: raise Exception("flow_utils.readFlowFile({:s}: illegal width {:d}".format(filename,w)) if h < MIN_HEIGHT or h > MAX_HEIGHT: raise Exception("flow_utils.readFlowFile({:s}: illegal height {:d}".format(filename,h)) flow = np.fromfile(f,'float32') if not flow.shape == (h*w*2,): raise Exception("flow_utils.readFlowFile({:s}: illegal size of the file".format(filename)) flow.shape = (h,w,2) return flow
def writeFlowFile(flow,filename): """ writeFlowFile(flow,<FILENAME>) write flow to the file <FILENAME>. if <FILENAME> does not exist, an IOError is raised. if <FILENAME> does not finish with '.flo' or the flow has not 2 bands, an Exception is raised. ---- PARAMETERS ---- flow: np.array of dimension (height x width x 2) containing the flow to write filename: string containg the name of the file to write a flow """ # check filename if not filename.endswith(".flo"): raise Exception("flow_utils.writeFlowFile(<flow>,{:s}): filename must finish with '.flo'".format(filename)) if not flow.shape[2:] == (2,): raise Exception("flow_utils.writeFlowFile(<flow>,{:s}): <flow> must have 2 bands".format(filename))
# open the file and write it with open(filename,'wb') as f: # write TAG f.write( TAG_STRING.encode('utf-8') ) # write dimension f.write( struct.pack('ii',flow.shape[1],flow.shape[0]) ) # write the flow flow.astype(np.float32).tofile(f) _read_flo_file = readFlowFile
def _read_kitti_flow(filename): flow = cv2.imread(filename, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_COLOR) flow = flow[:, :, ::-1].astype(np.float32) valid = flow[:, :, 2]>0 flow = flow[:, :, :2] flow = (flow - 2 ** 15) / 64.0 flow[~valid,0] = np.inf flow[~valid,1] = np.inf return flow_read_hd1k_flow = _read_kitti_flow def writeFlowKitti(filename, uv): uv = 64.0 * uv + 2 ** 15 valid = np.ones([uv.shape[0], uv.shape[1], 1]) uv = np.concatenate([uv, valid], axis=-1).astype(np.uint16) cv2.imwrite(filename, uv[..., ::-1])
def writeFlo5File(flow, filename): with h5py.File(filename, "w") as f: f.create_dataset("flow", data=flow, compression="gzip", compression_opts=5) def _read_hdf5_flow(filename): flow = np.asarray(h5py.File(filename)['flow']) flow[np.isnan(flow)] = np.inf # make invalid values as +inf return flow.astype(np.float32)
# flow visualizationRY = 15YG = 6GC = 4CB = 11BM = 13MR = 6UNKNOWN_THRESH = 1e9
def colorTest(): """ flow_utils.colorTest(): display an example of image showing the color encoding scheme """ import matplotlib.pylab as plt truerange = 1 h,w = 151,151 trange = truerange*1.04 s2 = round(h/2) x,y = np.meshgrid(range(w),range(h)) u = x*trange/s2-trange v = y*trange/s2-trange img = _computeColor(np.concatenate((u[:,:,np.newaxis],v[:,:,np.newaxis]),2)/trange/np.sqrt(2)) plt.imshow(img) plt.axis('off') plt.axhline(round(h/2),color='k') plt.axvline(round(w/2),color='k') def flowToColor(flow, maxflow=None, maxmaxflow=None, saturate=False): """ flow_utils.flowToColor(flow): return a color code flow field, normalized based on the maximum l2-norm of the flow flow_utils.flowToColor(flow,maxflow): return a color code flow field, normalized by maxflow ---- PARAMETERS ---- flow: flow to display of shape (height x width x 2) maxflow (default:None): if given, normalize the flow by its value, otherwise by the flow norm maxmaxflow (default:None): if given, normalize the flow by the max of its value and the flow norm ---- OUTPUT ---- an np.array of shape (height x width x 3) of type uint8 containing a color code of the flow """ h,w,n = flow.shape # check size of flow assert n == 2, "flow_utils.flowToColor(flow): flow must have 2 bands" # fix unknown flow unknown_idx = np.max(np.abs(flow),2)>UNKNOWN_THRESH flow[unknown_idx] = 0.0 # compute max flow if needed if maxflow is None: maxflow = flowMaxNorm(flow) if maxmaxflow is not None: maxflow = min(maxmaxflow, maxflow) # normalize flow eps = np.spacing(1) # minimum positive float value to avoid division by 0 # compute the flow img = _computeColor(flow/(maxflow+eps), saturate=saturate) # put black pixels in unknown location img[ np.tile( unknown_idx[:,:,np.newaxis],[1,1,3]) ] = 0.0 return img
def flowMaxNorm(flow): """ flow_utils.flowMaxNorm(flow): return the maximum of the l2-norm of the given flow ---- PARAMETERS ---- flow: the flow ---- OUTPUT ---- a float containing the maximum of the l2-norm of the flow """ return np.max( np.sqrt( np.sum( np.square( flow ) , 2) ) )
def _computeColor(flow, saturate=True): """ flow_utils._computeColor(flow): compute color codes for the flow field flow ---- PARAMETERS ---- flow: np.array of dimension (height x width x 2) containing the flow to display ---- OUTPUTS ---- an np.array of dimension (height x width x 3) containing the color conversion of the flow """ # set nan to 0 nanidx = np.isnan(flow[:,:,0]) flow[nanidx] = 0.0 # colorwheel ncols = RY + YG + GC + CB + BM + MR nchans = 3 colorwheel = np.zeros((ncols,nchans),'uint8') col = 0; #RY colorwheel[:RY,0] = 255 colorwheel[:RY,1] = [(255*i) // RY for i in range(RY)] col += RY # YG colorwheel[col:col+YG,0] = [255 - (255*i) // YG for i in range(YG)] colorwheel[col:col+YG,1] = 255 col += YG # GC colorwheel[col:col+GC,1] = 255 colorwheel[col:col+GC,2] = [(255*i) // GC for i in range(GC)] col += GC # CB colorwheel[col:col+CB,1] = [255 - (255*i) // CB for i in range(CB)] colorwheel[col:col+CB,2] = 255 col += CB # BM colorwheel[col:col+BM,0] = [(255*i) // BM for i in range(BM)] colorwheel[col:col+BM,2] = 255 col += BM # MR colorwheel[col:col+MR,0] = 255 colorwheel[col:col+MR,2] = [255 - (255*i) // MR for i in range(MR)]
# compute utility variables rad = np.sqrt( np.sum( np.square(flow) , 2) ) # magnitude a = np.arctan2( -flow[:,:,1] , -flow[:,:,0]) / np.pi # angle fk = (a+1)/2 * (ncols-1) # map [-1,1] to [0,ncols-1] k0 = np.floor(fk).astype('int') k1 = k0+1 k1[k1==ncols] = 0 f = fk-k0
if not saturate: rad = np.minimum(rad,1)
# compute the image img = np.zeros( (flow.shape[0],flow.shape[1],nchans), 'uint8' ) for i in range(nchans): tmp = colorwheel[:,i].astype('float') col0 = tmp[k0]/255 col1 = tmp[k1]/255 col = (1-f)*col0 + f*col1 idx = (rad <= 1) col[idx] = 1-rad[idx]*(1-col[idx]) # increase saturation with radius col[~idx] *= 0.75 # out of range img[:,:,i] = (255*col*(1-nanidx.astype('float'))).astype('uint8')
return img # flow dataset getter def get_train_dataset_flow(dataset_str, augmentor=True, crop_size=None): dataset_str = dataset_str.replace('(','Dataset(') if augmentor: dataset_str = dataset_str.replace(')',', augmentor=True)') if crop_size is not None: dataset_str = dataset_str.replace(')',', crop_size={:s})'.format(str(crop_size))) return eval(dataset_str) def get_test_datasets_flow(dataset_str): dataset_str = dataset_str.replace('(','Dataset(') return [eval(s) for s in dataset_str.split('+')]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Dataset structure for stereo# --------------------------------------------------------
import sys, osimport os.path as ospimport pickleimport numpy as npfrom PIL import Imageimport jsonimport h5pyfrom glob import globimport cv2
import torchfrom torch.utils import data
from .augmentor import StereoAugmentor
dataset_to_root = { 'CREStereo': './data/stereoflow//crenet_stereo_trainset/stereo_trainset/crestereo/', 'SceneFlow': './data/stereoflow//SceneFlow/', 'ETH3DLowRes': './data/stereoflow/eth3d_lowres/', 'Booster': './data/stereoflow/booster_gt/', 'Middlebury2021': './data/stereoflow/middlebury/2021/data/', 'Middlebury2014': './data/stereoflow/middlebury/2014/', 'Middlebury2006': './data/stereoflow/middlebury/2006/', 'Middlebury2005': './data/stereoflow/middlebury/2005/train/', 'MiddleburyEval3': './data/stereoflow/middlebury/MiddEval3/', 'Spring': './data/stereoflow/spring/', 'Kitti15': './data/stereoflow/kitti-stereo-2015/', 'Kitti12': './data/stereoflow/kitti-stereo-2012/',}cache_dir = "./data/stereoflow/datasets_stereo_cache/"
in1k_mean = torch.tensor([0.485, 0.456, 0.406]).view(3,1,1)in1k_std = torch.tensor([0.229, 0.224, 0.225]).view(3,1,1)def img_to_tensor(img): img = torch.from_numpy(img).permute(2, 0, 1).float() / 255. img = (img-in1k_mean)/in1k_std return imgdef disp_to_tensor(disp): return torch.from_numpy(disp)[None,:,:]
class StereoDataset(data.Dataset): def __init__(self, split, augmentor=False, crop_size=None, totensor=True): self.split = split if not augmentor: assert crop_size is None if crop_size: assert augmentor self.crop_size = crop_size self.augmentor_str = augmentor self.augmentor = StereoAugmentor(crop_size) if augmentor else None self.totensor = totensor self.rmul = 1 # keep track of rmul self.has_constant_resolution = True # whether the dataset has constant resolution or not (=> don't use batch_size>1 at test time) self._prepare_data() self._load_or_build_cache() def prepare_data(self): """ to be defined for each dataset """ raise NotImplementedError def __len__(self): return len(self.pairnames) def __getitem__(self, index): pairname = self.pairnames[index] # get filenames Limgname = self.pairname_to_Limgname(pairname) Rimgname = self.pairname_to_Rimgname(pairname) Ldispname = self.pairname_to_Ldispname(pairname) if self.pairname_to_Ldispname is not None else None # load images and disparities Limg = _read_img(Limgname) Rimg = _read_img(Rimgname) disp = self.load_disparity(Ldispname) if Ldispname is not None else None # sanity check if disp is not None: assert np.all(disp>0) or self.name=="Spring", (self.name, pairname, Ldispname) # apply augmentations if self.augmentor is not None: Limg, Rimg, disp = self.augmentor(Limg, Rimg, disp, self.name) if self.totensor: Limg = img_to_tensor(Limg) Rimg = img_to_tensor(Rimg) if disp is None: disp = torch.tensor([]) # to allow dataloader batching with default collate_gn else: disp = disp_to_tensor(disp) return Limg, Rimg, disp, str(pairname) def __rmul__(self, v): self.rmul *= v self.pairnames = v * self.pairnames return self def __str__(self): return f'{self.__class__.__name__}_{self.split}' def __repr__(self): s = f'{self.__class__.__name__}(split={self.split}, augmentor={self.augmentor_str}, crop_size={str(self.crop_size)}, totensor={self.totensor})' if self.rmul==1: s+=f'\n\tnum pairs: {len(self.pairnames)}' else: s+=f'\n\tnum pairs: {len(self.pairnames)} ({len(self.pairnames)//self.rmul}x{self.rmul})' return s
def _set_root(self): self.root = dataset_to_root[self.name] assert os.path.isdir(self.root), f"could not find root directory for dataset {self.name}: {self.root}"
def _load_or_build_cache(self): cache_file = osp.join(cache_dir, self.name+'.pkl') if osp.isfile(cache_file): with open(cache_file, 'rb') as fid: self.pairnames = pickle.load(fid)[self.split] else: tosave = self._build_cache() os.makedirs(cache_dir, exist_ok=True) with open(cache_file, 'wb') as fid: pickle.dump(tosave, fid) self.pairnames = tosave[self.split] class CREStereoDataset(StereoDataset):
def _prepare_data(self): self.name = 'CREStereo' self._set_root() assert self.split in ['train'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname+'_left.jpg') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname+'_right.jpg') self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, pairname+'_left.disp.png') self.pairname_to_str = lambda pairname: pairname self.load_disparity = _read_crestereo_disp def _build_cache(self): allpairs = [s+'/'+f[:-len('_left.jpg')] for s in sorted(os.listdir(self.root)) for f in sorted(os.listdir(self.root+'/'+s)) if f.endswith('_left.jpg')] assert len(allpairs)==200000, "incorrect parsing of pairs in CreStereo" tosave = {'train': allpairs} return tosave class SceneFlowDataset(StereoDataset):
def _prepare_data(self): self.name = "SceneFlow" self._set_root() assert self.split in ['train_finalpass','train_cleanpass','train_allpass','test_finalpass','test_cleanpass','test_allpass','test1of100_cleanpass','test1of100_finalpass'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname) self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname).replace('/left/','/right/') self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, pairname).replace('/frames_finalpass/','/disparity/').replace('/frames_cleanpass/','/disparity/')[:-4]+'.pfm' self.pairname_to_str = lambda pairname: pairname[:-4] self.load_disparity = _read_sceneflow_disp def _build_cache(self): trainpairs = [] # driving pairs = sorted(glob(self.root+'Driving/frames_finalpass/*/*/*/left/*.png')) pairs = list(map(lambda x: x[len(self.root):], pairs)) assert len(pairs) == 4400, "incorrect parsing of pairs in SceneFlow" trainpairs += pairs # monkaa pairs = sorted(glob(self.root+'Monkaa/frames_finalpass/*/left/*.png')) pairs = list(map(lambda x: x[len(self.root):], pairs)) assert len(pairs) == 8664, "incorrect parsing of pairs in SceneFlow" trainpairs += pairs # flyingthings pairs = sorted(glob(self.root+'FlyingThings/frames_finalpass/TRAIN/*/*/left/*.png')) pairs = list(map(lambda x: x[len(self.root):], pairs)) assert len(pairs) == 22390, "incorrect parsing of pairs in SceneFlow" trainpairs += pairs assert len(trainpairs) == 35454, "incorrect parsing of pairs in SceneFlow" testpairs = sorted(glob(self.root+'FlyingThings/frames_finalpass/TEST/*/*/left/*.png')) testpairs = list(map(lambda x: x[len(self.root):], testpairs)) assert len(testpairs) == 4370, "incorrect parsing of pairs in SceneFlow" test1of100pairs = testpairs[::100] assert len(test1of100pairs) == 44, "incorrect parsing of pairs in SceneFlow" # all tosave = {'train_finalpass': trainpairs, 'train_cleanpass': list(map(lambda x: x.replace('frames_finalpass','frames_cleanpass'), trainpairs)), 'test_finalpass': testpairs, 'test_cleanpass': list(map(lambda x: x.replace('frames_finalpass','frames_cleanpass'), testpairs)), 'test1of100_finalpass': test1of100pairs, 'test1of100_cleanpass': list(map(lambda x: x.replace('frames_finalpass','frames_cleanpass'), test1of100pairs)), } tosave['train_allpass'] = tosave['train_finalpass']+tosave['train_cleanpass'] tosave['test_allpass'] = tosave['test_finalpass']+tosave['test_cleanpass'] return tosave class Md21Dataset(StereoDataset):
def _prepare_data(self): self.name = "Middlebury2021" self._set_root() assert self.split in ['train','subtrain','subval'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname) self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname.replace('/im0','/im1')) self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, pairname.split('/')[0], 'disp0.pfm') self.pairname_to_str = lambda pairname: pairname[:-4] self.load_disparity = _read_middlebury_disp def _build_cache(self): seqs = sorted(os.listdir(self.root)) trainpairs = [] for s in seqs: #trainpairs += [s+'/im0.png'] # we should remove it, it is included as such in other lightings trainpairs += [s+'/ambient/'+b+'/'+a for b in sorted(os.listdir(osp.join(self.root,s,'ambient'))) for a in sorted(os.listdir(osp.join(self.root,s,'ambient',b))) if a.startswith('im0')] assert len(trainpairs)==355 subtrainpairs = [p for p in trainpairs if any(p.startswith(s+'/') for s in seqs[:-2])] subvalpairs = [p for p in trainpairs if any(p.startswith(s+'/') for s in seqs[-2:])] assert len(subtrainpairs)==335 and len(subvalpairs)==20, "incorrect parsing of pairs in Middlebury 2021" tosave = {'train': trainpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs} return tosave
class Md14Dataset(StereoDataset):
def _prepare_data(self): self.name = "Middlebury2014" self._set_root() assert self.split in ['train','subtrain','subval'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, osp.dirname(pairname), 'im0.png') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname) self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, osp.dirname(pairname), 'disp0.pfm') self.pairname_to_str = lambda pairname: pairname[:-4] self.load_disparity = _read_middlebury_disp self.has_constant_resolution = False def _build_cache(self): seqs = sorted(os.listdir(self.root)) trainpairs = [] for s in seqs: trainpairs += [s+'/im1.png',s+'/im1E.png',s+'/im1L.png'] assert len(trainpairs)==138 valseqs = ['Umbrella-imperfect','Vintage-perfect'] assert all(s in seqs for s in valseqs) subtrainpairs = [p for p in trainpairs if not any(p.startswith(s+'/') for s in valseqs)] subvalpairs = [p for p in trainpairs if any(p.startswith(s+'/') for s in valseqs)] assert len(subtrainpairs)==132 and len(subvalpairs)==6, "incorrect parsing of pairs in Middlebury 2014" tosave = {'train': trainpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs} return tosave
class Md06Dataset(StereoDataset):
def _prepare_data(self): self.name = "Middlebury2006" self._set_root() assert self.split in ['train','subtrain','subval'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname) self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, osp.dirname(pairname), 'view5.png') self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, pairname.split('/')[0], 'disp1.png') self.load_disparity = _read_middlebury20052006_disp self.has_constant_resolution = False def _build_cache(self): seqs = sorted(os.listdir(self.root)) trainpairs = [] for s in seqs: for i in ['Illum1','Illum2','Illum3']: for e in ['Exp0','Exp1','Exp2']: trainpairs.append(osp.join(s,i,e,'view1.png')) assert len(trainpairs)==189 valseqs = ['Rocks1','Wood2'] assert all(s in seqs for s in valseqs) subtrainpairs = [p for p in trainpairs if not any(p.startswith(s+'/') for s in valseqs)] subvalpairs = [p for p in trainpairs if any(p.startswith(s+'/') for s in valseqs)] assert len(subtrainpairs)==171 and len(subvalpairs)==18, "incorrect parsing of pairs in Middlebury 2006" tosave = {'train': trainpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs} return tosave
class Md05Dataset(StereoDataset):
def _prepare_data(self): self.name = "Middlebury2005" self._set_root() assert self.split in ['train','subtrain','subval'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname) self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, osp.dirname(pairname), 'view5.png') self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, pairname.split('/')[0], 'disp1.png') self.pairname_to_str = lambda pairname: pairname[:-4] self.load_disparity = _read_middlebury20052006_disp def _build_cache(self): seqs = sorted(os.listdir(self.root)) trainpairs = [] for s in seqs: for i in ['Illum1','Illum2','Illum3']: for e in ['Exp0','Exp1','Exp2']: trainpairs.append(osp.join(s,i,e,'view1.png')) assert len(trainpairs)==54, "incorrect parsing of pairs in Middlebury 2005" valseqs = ['Reindeer'] assert all(s in seqs for s in valseqs) subtrainpairs = [p for p in trainpairs if not any(p.startswith(s+'/') for s in valseqs)] subvalpairs = [p for p in trainpairs if any(p.startswith(s+'/') for s in valseqs)] assert len(subtrainpairs)==45 and len(subvalpairs)==9, "incorrect parsing of pairs in Middlebury 2005" tosave = {'train': trainpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs} return tosave class MdEval3Dataset(StereoDataset):
def _prepare_data(self): self.name = "MiddleburyEval3" self._set_root() assert self.split in [s+'_'+r for s in ['train','subtrain','subval','test','all'] for r in ['full','half','quarter']] if self.split.endswith('_full'): self.root = self.root.replace('/MiddEval3','/MiddEval3_F') elif self.split.endswith('_half'): self.root = self.root.replace('/MiddEval3','/MiddEval3_H') else: assert self.split.endswith('_quarter') self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname, 'im0.png') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname, 'im1.png') self.pairname_to_Ldispname = lambda pairname: None if pairname.startswith('test') else osp.join(self.root, pairname, 'disp0GT.pfm') self.pairname_to_str = lambda pairname: pairname self.load_disparity = _read_middlebury_disp # for submission only self.submission_methodname = "CroCo-Stereo" self.submission_sresolution = 'F' if self.split.endswith('_full') else ('H' if self.split.endswith('_half') else 'Q') def _build_cache(self): trainpairs = ['train/'+s for s in sorted(os.listdir(self.root+'train/'))] testpairs = ['test/'+s for s in sorted(os.listdir(self.root+'test/'))] subvalpairs = trainpairs[-1:] subtrainpairs = trainpairs[:-1] allpairs = trainpairs+testpairs assert len(trainpairs)==15 and len(testpairs)==15 and len(subvalpairs)==1 and len(subtrainpairs)==14 and len(allpairs)==30, "incorrect parsing of pairs in Middlebury Eval v3" tosave = {} for r in ['full','half','quarter']: tosave.update(**{'train_'+r: trainpairs, 'subtrain_'+r: subtrainpairs, 'subval_'+r: subvalpairs, 'test_'+r: testpairs, 'all_'+r: allpairs}) return tosave def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==2 assert prediction.dtype==np.float32 outfile = os.path.join(outdir, pairname.split('/')[0].replace('train','training')+self.submission_sresolution, pairname.split('/')[1], 'disp0'+self.submission_methodname+'.pfm') os.makedirs( os.path.dirname(outfile), exist_ok=True) writePFM(outfile, prediction) timefile = os.path.join( os.path.dirname(outfile), "time"+self.submission_methodname+'.txt') with open(timefile, 'w') as fid: fid.write(str(time))
def finalize_submission(self, outdir): cmd = f'cd {outdir}/; zip -r "{self.submission_methodname}.zip" .' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/{self.submission_methodname}.zip')
class ETH3DLowResDataset(StereoDataset):
def _prepare_data(self): self.name = "ETH3DLowRes" self._set_root() assert self.split in ['train','test','subtrain','subval','all'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname, 'im0.png') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname, 'im1.png') self.pairname_to_Ldispname = None if self.split=='test' else lambda pairname: None if pairname.startswith('test/') else osp.join(self.root, pairname.replace('train/','train_gt/'), 'disp0GT.pfm') self.pairname_to_str = lambda pairname: pairname self.load_disparity = _read_eth3d_disp self.has_constant_resolution = False def _build_cache(self): trainpairs = ['train/' + s for s in sorted(os.listdir(self.root+'train/'))] testpairs = ['test/' + s for s in sorted(os.listdir(self.root+'test/'))] assert len(trainpairs) == 27 and len(testpairs) == 20, "incorrect parsing of pairs in ETH3D Low Res" subvalpairs = ['train/delivery_area_3s','train/electro_3l','train/playground_3l'] assert all(p in trainpairs for p in subvalpairs) subtrainpairs = [p for p in trainpairs if not p in subvalpairs] assert len(subvalpairs)==3 and len(subtrainpairs)==24, "incorrect parsing of pairs in ETH3D Low Res" tosave = {'train': trainpairs, 'test': testpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs, 'all': trainpairs+testpairs} return tosave
def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==2 assert prediction.dtype==np.float32 outfile = os.path.join(outdir, 'low_res_two_view', pairname.split('/')[1]+'.pfm') os.makedirs( os.path.dirname(outfile), exist_ok=True) writePFM(outfile, prediction) timefile = outfile[:-4]+'.txt' with open(timefile, 'w') as fid: fid.write('runtime '+str(time))
def finalize_submission(self, outdir): cmd = f'cd {outdir}/; zip -r "eth3d_low_res_two_view_results.zip" low_res_two_view' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/eth3d_low_res_two_view_results.zip')
class BoosterDataset(StereoDataset):
def _prepare_data(self): self.name = "Booster" self._set_root() assert self.split in ['train_balanced','test_balanced','subtrain_balanced','subval_balanced'] # we use only the balanced version self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname) self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname).replace('/camera_00/','/camera_02/') self.pairname_to_Ldispname = lambda pairname: osp.join(self.root, osp.dirname(pairname), '../disp_00.npy') # same images with different colors, same gt per sequence self.pairname_to_str = lambda pairname: pairname[:-4].replace('/camera_00/','/') self.load_disparity = _read_booster_disp def _build_cache(self): trainseqs = sorted(os.listdir(self.root+'train/balanced')) trainpairs = ['train/balanced/'+s+'/camera_00/'+imname for s in trainseqs for imname in sorted(os.listdir(self.root+'train/balanced/'+s+'/camera_00/'))] testpairs = ['test/balanced/'+s+'/camera_00/'+imname for s in sorted(os.listdir(self.root+'test/balanced')) for imname in sorted(os.listdir(self.root+'test/balanced/'+s+'/camera_00/'))] assert len(trainpairs) == 228 and len(testpairs) == 191 subtrainpairs = [p for p in trainpairs if any(s in p for s in trainseqs[:-2])] subvalpairs = [p for p in trainpairs if any(s in p for s in trainseqs[-2:])] # warning: if we do validation split, we should split scenes!!! tosave = {'train_balanced': trainpairs, 'test_balanced': testpairs, 'subtrain_balanced': subtrainpairs, 'subval_balanced': subvalpairs,} return tosave class SpringDataset(StereoDataset):
def _prepare_data(self): self.name = "Spring" self._set_root() assert self.split in ['train', 'test', 'subtrain', 'subval'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname+'.png') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname+'.png').replace('frame_right','<frame_right>').replace('frame_left','frame_right').replace('<frame_right>','frame_left') self.pairname_to_Ldispname = lambda pairname: None if pairname.startswith('test') else osp.join(self.root, pairname+'.dsp5').replace('frame_left','disp1_left').replace('frame_right','disp1_right') self.pairname_to_str = lambda pairname: pairname self.load_disparity = _read_hdf5_disp def _build_cache(self): trainseqs = sorted(os.listdir( osp.join(self.root,'train'))) trainpairs = [osp.join('train',s,'frame_left',f[:-4]) for s in trainseqs for f in sorted(os.listdir(osp.join(self.root,'train',s,'frame_left')))] testseqs = sorted(os.listdir( osp.join(self.root,'test'))) testpairs = [osp.join('test',s,'frame_left',f[:-4]) for s in testseqs for f in sorted(os.listdir(osp.join(self.root,'test',s,'frame_left')))] testpairs += [p.replace('frame_left','frame_right') for p in testpairs] """maxnorm = {'0001': 32.88, '0002': 228.5, '0004': 298.2, '0005': 142.5, '0006': 113.6, '0007': 27.3, '0008': 554.5, '0009': 155.6, '0010': 126.1, '0011': 87.6, '0012': 303.2, '0013': 24.14, '0014': 82.56, '0015': 98.44, '0016': 156.9, '0017': 28.17, '0018': 21.03, '0020': 178.0, '0021': 58.06, '0022': 354.2, '0023': 8.79, '0024': 97.06, '0025': 55.16, '0026': 91.9, '0027': 156.6, '0030': 200.4, '0032': 58.66, '0033': 373.5, '0036': 149.4, '0037': 5.625, '0038': 37.0, '0039': 12.2, '0041': 453.5, '0043': 457.0, '0044': 379.5, '0045': 161.8, '0047': 105.44} # => let'use 0041""" subtrainpairs = [p for p in trainpairs if p.split('/')[1]!='0041'] subvalpairs = [p for p in trainpairs if p.split('/')[1]=='0041'] assert len(trainpairs)==5000 and len(testpairs)==2000 and len(subtrainpairs)==4904 and len(subvalpairs)==96, "incorrect parsing of pairs in Spring" tosave = {'train': trainpairs, 'test': testpairs, 'subtrain': subtrainpairs, 'subval': subvalpairs} return tosave def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==2 assert prediction.dtype==np.float32 outfile = os.path.join(outdir, pairname+'.dsp5').replace('frame_left','disp1_left').replace('frame_right','disp1_right') os.makedirs( os.path.dirname(outfile), exist_ok=True) writeDsp5File(prediction, outfile) def finalize_submission(self, outdir): assert self.split=='test' exe = "{self.root}/disp1_subsampling" if os.path.isfile(exe): cmd = f'cd "{outdir}/test"; {exe} .' print(cmd) os.system(cmd) else: print('Could not find disp1_subsampling executable for submission.') print('Please download it and run:') print(f'cd "{outdir}/test"; <disp1_subsampling_exe> .')
class Kitti12Dataset(StereoDataset):
def _prepare_data(self): self.name = "Kitti12" self._set_root() assert self.split in ['train','test'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname+'_10.png') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname.replace('/colored_0/','/colored_1/')+'_10.png') self.pairname_to_Ldispname = None if self.split=='test' else lambda pairname: osp.join(self.root, pairname.replace('/colored_0/','/disp_occ/')+'_10.png') self.pairname_to_str = lambda pairname: pairname.replace('/colored_0/','/') self.load_disparity = _read_kitti_disp def _build_cache(self): trainseqs = ["training/colored_0/%06d"%(i) for i in range(194)] testseqs = ["testing/colored_0/%06d"%(i) for i in range(195)] assert len(trainseqs)==194 and len(testseqs)==195, "incorrect parsing of pairs in Kitti12" tosave = {'train': trainseqs, 'test': testseqs} return tosave
def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==2 assert prediction.dtype==np.float32 outfile = os.path.join(outdir, pairname.split('/')[-1]+'_10.png') os.makedirs( os.path.dirname(outfile), exist_ok=True) img = (prediction * 256).astype('uint16') Image.fromarray(img).save(outfile)
def finalize_submission(self, outdir): assert self.split=='test' cmd = f'cd {outdir}/; zip -r "kitti12_results.zip" .' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/kitti12_results.zip')
class Kitti15Dataset(StereoDataset):
def _prepare_data(self): self.name = "Kitti15" self._set_root() assert self.split in ['train','subtrain','subval','test'] self.pairname_to_Limgname = lambda pairname: osp.join(self.root, pairname+'_10.png') self.pairname_to_Rimgname = lambda pairname: osp.join(self.root, pairname.replace('/image_2/','/image_3/')+'_10.png') self.pairname_to_Ldispname = None if self.split=='test' else lambda pairname: osp.join(self.root, pairname.replace('/image_2/','/disp_occ_0/')+'_10.png') self.pairname_to_str = lambda pairname: pairname.replace('/image_2/','/') self.load_disparity = _read_kitti_disp def _build_cache(self): trainseqs = ["training/image_2/%06d"%(i) for i in range(200)] subtrainseqs = trainseqs[:-5] subvalseqs = trainseqs[-5:] testseqs = ["testing/image_2/%06d"%(i) for i in range(200)] assert len(trainseqs)==200 and len(subtrainseqs)==195 and len(subvalseqs)==5 and len(testseqs)==200, "incorrect parsing of pairs in Kitti15" tosave = {'train': trainseqs, 'subtrain': subtrainseqs, 'subval': subvalseqs, 'test': testseqs} return tosave
def submission_save_pairname(self, pairname, prediction, outdir, time): assert prediction.ndim==2 assert prediction.dtype==np.float32 outfile = os.path.join(outdir, 'disp_0', pairname.split('/')[-1]+'_10.png') os.makedirs( os.path.dirname(outfile), exist_ok=True) img = (prediction * 256).astype('uint16') Image.fromarray(img).save(outfile)
def finalize_submission(self, outdir): assert self.split=='test' cmd = f'cd {outdir}/; zip -r "kitti15_results.zip" disp_0' print(cmd) os.system(cmd) print(f'Done. Submission file at {outdir}/kitti15_results.zip')
### auxiliary functions
def _read_img(filename): # convert to RGB for scene flow finalpass data img = np.asarray(Image.open(filename).convert('RGB')) return img
def _read_booster_disp(filename): disp = np.load(filename) disp[disp==0.0] = np.inf return disp
def _read_png_disp(filename, coef=1.0): disp = np.asarray(Image.open(filename)) disp = disp.astype(np.float32) / coef disp[disp==0.0] = np.inf return disp
def _read_pfm_disp(filename): disp = np.ascontiguousarray(_read_pfm(filename)[0]) disp[disp<=0] = np.inf # eg /nfs/data/ffs-3d/datasets/middlebury/2014/Shopvac-imperfect/disp0.pfm return disp
def _read_npy_disp(filename): return np.load(filename)
def _read_crestereo_disp(filename): return _read_png_disp(filename, coef=32.0)def _read_middlebury20052006_disp(filename): return _read_png_disp(filename, coef=1.0)def _read_kitti_disp(filename): return _read_png_disp(filename, coef=256.0)_read_sceneflow_disp = _read_pfm_disp_read_eth3d_disp = _read_pfm_disp_read_middlebury_disp = _read_pfm_disp_read_carla_disp = _read_pfm_disp_read_tartanair_disp = _read_npy_disp def _read_hdf5_disp(filename): disp = np.asarray(h5py.File(filename)['disparity']) disp[np.isnan(disp)] = np.inf # make invalid values as +inf #disp[disp==0.0] = np.inf # make invalid values as +inf return disp.astype(np.float32) import redef _read_pfm(file): file = open(file, 'rb')
color = None width = None height = None scale = None endian = None
header = file.readline().rstrip() if header.decode("ascii") == 'PF': color = True elif header.decode("ascii") == 'Pf': color = False else: raise Exception('Not a PFM file.')
dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode("ascii")) if dim_match: width, height = list(map(int, dim_match.groups())) else: raise Exception('Malformed PFM header.')
scale = float(file.readline().decode("ascii").rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian
data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width)
data = np.reshape(data, shape) data = np.flipud(data) return data, scale
def writePFM(file, image, scale=1): file = open(file, 'wb')
color = None
if image.dtype.name != 'float32': raise Exception('Image dtype must be float32.')
image = np.flipud(image)
if len(image.shape) == 3 and image.shape[2] == 3: # color image color = True elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale color = False else: raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')
file.write('PF\n' if color else 'Pf\n'.encode()) file.write('%d %d\n'.encode() % (image.shape[1], image.shape[0]))
endian = image.dtype.byteorder
if endian == '<' or endian == '=' and sys.byteorder == 'little': scale = -scale
file.write('%f\n'.encode() % scale)
image.tofile(file)
def writeDsp5File(disp, filename): with h5py.File(filename, "w") as f: f.create_dataset("disparity", data=disp, compression="gzip", compression_opts=5)
# disp visualization
def vis_disparity(disp, m=None, M=None): if m is None: m = disp.min() if M is None: M = disp.max() disp_vis = (disp - m) / (M-m) * 255.0 disp_vis = disp_vis.astype("uint8") disp_vis = cv2.applyColorMap(disp_vis, cv2.COLORMAP_INFERNO) return disp_vis
# dataset getter def get_train_dataset_stereo(dataset_str, augmentor=True, crop_size=None): dataset_str = dataset_str.replace('(','Dataset(') if augmentor: dataset_str = dataset_str.replace(')',', augmentor=True)') if crop_size is not None: dataset_str = dataset_str.replace(')',', crop_size={:s})'.format(str(crop_size))) return eval(dataset_str) def get_test_datasets_stereo(dataset_str): dataset_str = dataset_str.replace('(','Dataset(') return [eval(s) for s in dataset_str.split('+')]123456789101112# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
model=$1outfile="stereoflow_models/${model}"if [[ ! -f $outfile ]]then mkdir -p stereoflow_models/; wget https://download.europe.naverlabs.com/ComputerVision/CroCo/StereoFlow_models/$1 -P stereoflow_models/;else echo "Model ${model} already downloaded in ${outfile}."fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Main function for training one epoch or testing# --------------------------------------------------------
import mathimport sysfrom typing import Iterableimport numpy as npimport torchimport torchvision
from utils import misc as misc
def split_prediction_conf(predictions, with_conf=False): if not with_conf: return predictions, None conf = predictions[:,-1:,:,:] predictions = predictions[:,:-1,:,:] return predictions, conf
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, metrics: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, log_writer=None, print_freq = 20, args=None): model.train(True) metric_logger = misc.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}')) header = 'Epoch: [{}]'.format(epoch)
accum_iter = args.accum_iter
optimizer.zero_grad()
details = {}
if log_writer is not None: print('log_dir: {}'.format(log_writer.log_dir))
if args.img_per_epoch: iter_per_epoch = args.img_per_epoch // args.batch_size + int(args.img_per_epoch % args.batch_size > 0) assert len(data_loader) >= iter_per_epoch, 'Dataset is too small for so many iterations' len_data_loader = iter_per_epoch else: len_data_loader, iter_per_epoch = len(data_loader), None
for data_iter_step, (image1, image2, gt, pairname) in enumerate(metric_logger.log_every(data_loader, print_freq, header, max_iter=iter_per_epoch)): image1 = image1.to(device, non_blocking=True) image2 = image2.to(device, non_blocking=True) gt = gt.to(device, non_blocking=True) # we use a per iteration (instead of per epoch) lr scheduler if data_iter_step % accum_iter == 0: misc.adjust_learning_rate(optimizer, data_iter_step / len_data_loader + epoch, args)
with torch.cuda.amp.autocast(enabled=bool(args.amp)): prediction = model(image1, image2) prediction, conf = split_prediction_conf(prediction, criterion.with_conf) batch_metrics = metrics(prediction.detach(), gt) loss = criterion(prediction, gt) if conf is None else criterion(prediction, gt, conf) loss_value = loss.item() if not math.isfinite(loss_value): print("Loss is {}, stopping training".format(loss_value)) sys.exit(1)
loss /= accum_iter loss_scaler(loss, optimizer, parameters=model.parameters(), update_grad=(data_iter_step + 1) % accum_iter == 0) if (data_iter_step + 1) % accum_iter == 0: optimizer.zero_grad()
torch.cuda.synchronize() metric_logger.update(loss=loss_value) for k,v in batch_metrics.items(): metric_logger.update(**{k: v.item()}) lr = optimizer.param_groups[0]["lr"] metric_logger.update(lr=lr)
#if args.dsitributed: loss_value_reduce = misc.all_reduce_mean(loss_value) time_to_log = ((data_iter_step + 1) % (args.tboard_log_step * accum_iter) == 0 or data_iter_step == len_data_loader-1) loss_value_reduce = misc.all_reduce_mean(loss_value) if log_writer is not None and time_to_log: epoch_1000x = int((data_iter_step / len_data_loader + epoch) * 1000) # We use epoch_1000x as the x-axis in tensorboard. This calibrates different curves when batch size changes. log_writer.add_scalar('train/loss', loss_value_reduce, epoch_1000x) log_writer.add_scalar('lr', lr, epoch_1000x) for k,v in batch_metrics.items(): log_writer.add_scalar('train/'+k, v.item(), epoch_1000x)
# gather the stats from all processes #if args.distributed: metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
@torch.no_grad()def validate_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, metrics: torch.nn.Module, data_loaders: list[Iterable], device: torch.device, epoch: int, log_writer=None, args=None):
model.eval() metric_loggers = [] header = 'Epoch: [{}]'.format(epoch) print_freq = 20
conf_mode = args.tile_conf_mode crop = args.crop if log_writer is not None: print('log_dir: {}'.format(log_writer.log_dir))
results = {} dnames = [] image1, image2, gt, prediction = None, None, None, None for didx, data_loader in enumerate(data_loaders): dname = str(data_loader.dataset) dnames.append(dname) metric_loggers.append(misc.MetricLogger(delimiter=" ")) for data_iter_step, (image1, image2, gt, pairname) in enumerate(metric_loggers[didx].log_every(data_loader, print_freq, header)): image1 = image1.to(device, non_blocking=True) image2 = image2.to(device, non_blocking=True) gt = gt.to(device, non_blocking=True) if dname.startswith('Spring'): assert gt.size(2)==image1.size(2)*2 and gt.size(3)==image1.size(3)*2 gt = (gt[:,:,0::2,0::2] + gt[:,:,0::2,1::2] + gt[:,:,1::2,0::2] + gt[:,:,1::2,1::2] ) / 4.0 # we approximate the gt based on the 2x upsampled ones
with torch.inference_mode(): prediction, tiled_loss, c = tiled_pred(model, criterion, image1, image2, gt, conf_mode=conf_mode, overlap=args.val_overlap, crop=crop, with_conf=criterion.with_conf) batch_metrics = metrics(prediction.detach(), gt) loss = criterion(prediction.detach(), gt) if not criterion.with_conf else criterion(prediction.detach(), gt, c) loss_value = loss.item() metric_loggers[didx].update(loss_tiled=tiled_loss.item()) metric_loggers[didx].update(**{f'loss': loss_value}) for k,v in batch_metrics.items(): metric_loggers[didx].update(**{dname+'_' + k: v.item()}) results = {k: meter.global_avg for ml in metric_loggers for k, meter in ml.meters.items()} if len(dnames)>1: for k in batch_metrics.keys(): results['AVG_'+k] = sum(results[dname+'_'+k] for dname in dnames) / len(dnames) if log_writer is not None : epoch_1000x = int((1 + epoch) * 1000) for k,v in results.items(): log_writer.add_scalar('val/'+k, v, epoch_1000x)
print("Averaged stats:", results) return results
import torch.nn.functional as Fdef _resize_img(img, new_size): return F.interpolate(img, size=new_size, mode='bicubic', align_corners=False)def _resize_stereo_or_flow(data, new_size): assert data.ndim==4 assert data.size(1) in [1,2] scale_x = new_size[1]/float(data.size(3)) out = F.interpolate(data, size=new_size, mode='bicubic', align_corners=False) out[:,0,:,:] *= scale_x if out.size(1)==2: scale_y = new_size[0]/float(data.size(2)) out[:,1,:,:] *= scale_y print(scale_x, new_size, data.shape) return out
@torch.no_grad()def tiled_pred(model, criterion, img1, img2, gt, overlap=0.5, bad_crop_thr=0.05, downscale=False, crop=512, ret='loss', conf_mode='conf_expsigmoid_10_5', with_conf=False, return_time=False): # for each image, we are going to run inference on many overlapping patches # then, all predictions will be weighted-averaged if gt is not None: B, C, H, W = gt.shape else: B, _, H, W = img1.shape C = model.head.num_channels-int(with_conf) win_height, win_width = crop[0], crop[1] # upscale to be larger than the crop do_change_scale = H<win_height or W<win_width if do_change_scale: upscale_factor = max(win_width/W, win_height/W) original_size = (H,W) new_size = (round(H*upscale_factor),round(W*upscale_factor)) img1 = _resize_img(img1, new_size) img2 = _resize_img(img2, new_size) # resize gt just for the computation of tiled losses if gt is not None: gt = _resize_stereo_or_flow(gt, new_size) H,W = img1.shape[2:4] if conf_mode.startswith('conf_expsigmoid_'): # conf_expsigmoid_30_10 beta, betasigmoid = map(float, conf_mode[len('conf_expsigmoid_'):].split('_')) elif conf_mode.startswith('conf_expbeta'): # conf_expbeta3 beta = float(conf_mode[len('conf_expbeta'):]) else: raise NotImplementedError(f"conf_mode {conf_mode} is not implemented")
def crop_generator(): for sy in _overlapping(H, win_height, overlap): for sx in _overlapping(W, win_width, overlap): yield sy, sx, sy, sx, True
# keep track of weighted sum of prediction*weights and weights accu_pred = img1.new_zeros((B, C, H, W)) # accumulate the weighted sum of predictions accu_conf = img1.new_zeros((B, H, W)) + 1e-16 # accumulate the weights accu_c = img1.new_zeros((B, H, W)) # accumulate the weighted sum of confidences ; not so useful except for computing some losses
tiled_losses = [] if return_time: start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record()
for sy1, sx1, sy2, sx2, aligned in crop_generator(): # compute optical flow there pred = model(_crop(img1,sy1,sx1), _crop(img2,sy2,sx2)) pred, predconf = split_prediction_conf(pred, with_conf=with_conf) if gt is not None: gtcrop = _crop(gt,sy1,sx1) if criterion is not None and gt is not None: tiled_losses.append( criterion(pred, gtcrop).item() if predconf is None else criterion(pred, gtcrop, predconf).item() ) if conf_mode.startswith('conf_expsigmoid_'): conf = torch.exp(- beta * 2 * (torch.sigmoid(predconf / betasigmoid) - 0.5)).view(B,win_height,win_width) elif conf_mode.startswith('conf_expbeta'): conf = torch.exp(- beta * predconf).view(B,win_height,win_width) else: raise NotImplementedError accu_pred[...,sy1,sx1] += pred * conf[:,None,:,:] accu_conf[...,sy1,sx1] += conf accu_c[...,sy1,sx1] += predconf.view(B,win_height,win_width) * conf pred = accu_pred / accu_conf[:, None,:,:] c = accu_c / accu_conf assert not torch.any(torch.isnan(pred))
if return_time: end.record() torch.cuda.synchronize() time = start.elapsed_time(end)/1000.0 # this was in milliseconds
if do_change_scale: pred = _resize_stereo_or_flow(pred, original_size) if return_time: return pred, torch.mean(torch.tensor(tiled_losses)), c, time return pred, torch.mean(torch.tensor(tiled_losses)), c
def _overlapping(total, window, overlap=0.5): assert total >= window and 0 <= overlap < 1, (total, window, overlap) num_windows = 1 + int(np.ceil( (total - window) / ((1-overlap) * window) )) offsets = np.linspace(0, total-window, num_windows).round().astype(int) yield from (slice(x, x+window) for x in offsets)
def _crop(img, sy, sx): B, THREE, H, W = img.shape if 0 <= sy.start and sy.stop <= H and 0 <= sx.start and sx.stop <= W: return img[:,:,sy,sx] l, r = max(0,-sx.start), max(0,sx.stop-W) t, b = max(0,-sy.start), max(0,sy.stop-H) img = torch.nn.functional.pad(img, (l,r,t,b), mode='constant') return img[:, :, slice(sy.start+t,sy.stop+t), slice(sx.start+l,sx.stop+l)]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Main test function# --------------------------------------------------------
import osimport argparseimport picklefrom PIL import Imageimport numpy as npfrom tqdm import tqdm
import torchfrom torch.utils.data import DataLoader
import utils.misc as miscfrom models.croco_downstream import CroCoDownstreamBinocularfrom models.head_downstream import PixelwiseTaskWithDPT
from stereoflow.criterion import *from stereoflow.datasets_stereo import get_test_datasets_stereofrom stereoflow.datasets_flow import get_test_datasets_flowfrom stereoflow.engine import tiled_pred
from stereoflow.datasets_stereo import vis_disparityfrom stereoflow.datasets_flow import flowToColor
def get_args_parser(): parser = argparse.ArgumentParser('Test CroCo models on stereo/flow', add_help=False) # important argument parser.add_argument('--model', required=True, type=str, help='Path to the model to evaluate') parser.add_argument('--dataset', required=True, type=str, help="test dataset (there can be multiple dataset separated by a +)") # tiling parser.add_argument('--tile_conf_mode', type=str, default='', help='Weights for the tiling aggregation based on confidence (empty means use the formula from the loaded checkpoint') parser.add_argument('--tile_overlap', type=float, default=0.7, help='overlap between tiles') # save (it will automatically go to <model_path>_<dataset_str>/<tile_str>_<save>) parser.add_argument('--save', type=str, nargs='+', default=[], help='what to save: \ metrics (pickle file), \ pred (raw prediction save as torch tensor), \ visu (visualization in png of each prediction), \ err10 (visualization in png of the error clamp at 10 for each prediction), \ submission (submission file)') # other (no impact) parser.add_argument('--num_workers', default=4, type=int) return parser def _load_model_and_criterion(model_path, do_load_metrics, device): print('loading model from', model_path) assert os.path.isfile(model_path) ckpt = torch.load(model_path, 'cpu') ckpt_args = ckpt['args'] task = ckpt_args.task tile_conf_mode = ckpt_args.tile_conf_mode num_channels = {'stereo': 1, 'flow': 2}[task] with_conf = eval(ckpt_args.criterion).with_conf if with_conf: num_channels += 1 print('head: PixelwiseTaskWithDPT()') head = PixelwiseTaskWithDPT() head.num_channels = num_channels print('croco_args:', ckpt_args.croco_args) model = CroCoDownstreamBinocular(head, **ckpt_args.croco_args) msg = model.load_state_dict(ckpt['model'], strict=True) model.eval() model = model.to(device) if do_load_metrics: if task=='stereo': metrics = StereoDatasetMetrics().to(device) else: metrics = FlowDatasetMetrics().to(device) else: metrics = None return model, metrics, ckpt_args.crop, with_conf, task, tile_conf_mode def _save_batch(pred, gt, pairnames, dataset, task, save, outdir, time, submission_dir=None):
for i in range(len(pairnames)): pairname = eval(pairnames[i]) if pairnames[i].startswith('(') else pairnames[i] # unbatch pairname fname = os.path.join(outdir, dataset.pairname_to_str(pairname)) os.makedirs(os.path.dirname(fname), exist_ok=True) predi = pred[i,...] if gt is not None: gti = gt[i,...] if 'pred' in save: torch.save(predi.squeeze(0).cpu(), fname+'_pred.pth') if 'visu' in save: if task=='stereo': disparity = predi.permute((1,2,0)).squeeze(2).cpu().numpy() m,M = None if gt is not None: mask = torch.isfinite(gti) m = gt[mask].min() M = gt[mask].max() img_disparity = vis_disparity(disparity, m=m, M=M) Image.fromarray(img_disparity).save(fname+'_pred.png') else: # normalize flowToColor according to the maxnorm of gt (or prediction if not available) flowNorm = torch.sqrt(torch.sum( (gti if gt is not None else predi)**2, dim=0)).max().item() imgflow = flowToColor(predi.permute((1,2,0)).cpu().numpy(), maxflow=flowNorm) Image.fromarray(imgflow).save(fname+'_pred.png') if 'err10' in save: assert gt is not None L2err = torch.sqrt(torch.sum( (gti-predi)**2, dim=0)) valid = torch.isfinite(gti[0,:,:]) L2err[~valid] = 0.0 L2err = torch.clamp(L2err, max=10.0) red = (L2err*255.0/10.0).to(dtype=torch.uint8)[:,:,None] zer = torch.zeros_like(red) imgerr = torch.cat( (red,zer,zer), dim=2).cpu().numpy() Image.fromarray(imgerr).save(fname+'_err10.png') if 'submission' in save: assert submission_dir is not None predi_np = predi.permute(1,2,0).squeeze(2).cpu().numpy() # transform into HxWx2 for flow or HxW for stereo dataset.submission_save_pairname(pairname, predi_np, submission_dir, time)
def main(args): # load the pretrained model and metrics device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') model, metrics, cropsize, with_conf, task, tile_conf_mode = _load_model_and_criterion(args.model, 'metrics' in args.save, device) if args.tile_conf_mode=='': args.tile_conf_mode = tile_conf_mode # load the datasets datasets = (get_test_datasets_stereo if task=='stereo' else get_test_datasets_flow)(args.dataset) dataloaders = [DataLoader(dataset, batch_size=1, shuffle=False, num_workers=args.num_workers, pin_memory=True, drop_last=False) for dataset in datasets] # run for i,dataloader in enumerate(dataloaders): dataset = datasets[i] dstr = args.dataset.split('+')[i] outdir = args.model+'_'+misc.filename(dstr) if 'metrics' in args.save and len(args.save)==1: fname = os.path.join(outdir, f'conf_{args.tile_conf_mode}_overlap_{args.tile_overlap}.pkl') if os.path.isfile(fname) and len(args.save)==1: print(' metrics already compute in '+fname) with open(fname, 'rb') as fid: results = pickle.load(fid) for k,v in results.items(): print('{:s}: {:.3f}'.format(k, v)) continue if 'submission' in args.save: dirname = f'submission_conf_{args.tile_conf_mode}_overlap_{args.tile_overlap}' submission_dir = os.path.join(outdir, dirname) else: submission_dir = None print('') print('saving {:s} in {:s}'.format('+'.join(args.save), outdir)) print(repr(dataset)) if metrics is not None: metrics.reset() for data_iter_step, (image1, image2, gt, pairnames) in enumerate(tqdm(dataloader)): do_flip = (task=='stereo' and dstr.startswith('Spring') and any("right" in p for p in pairnames)) # we flip the images and will flip the prediction after as we assume img1 is on the left image1 = image1.to(device, non_blocking=True) image2 = image2.to(device, non_blocking=True) gt = gt.to(device, non_blocking=True) if gt.numel()>0 else None # special case for test time if do_flip: assert all("right" in p for p in pairnames) image1 = image1.flip(dims=[3]) # this is already the right frame, let's flip it image2 = image2.flip(dims=[3]) gt = gt # that is ok with torch.inference_mode(): pred, _, _, time = tiled_pred(model, None, image1, image2, None if dataset.name=='Spring' else gt, conf_mode=args.tile_conf_mode, overlap=args.tile_overlap, crop=cropsize, with_conf=with_conf, return_time=True)
if do_flip: pred = pred.flip(dims=[3]) if metrics is not None: metrics.add_batch(pred, gt) if any(k in args.save for k in ['pred','visu','err10','submission']): _save_batch(pred, gt, pairnames, dataset, task, args.save, outdir, time, submission_dir=submission_dir)
# print if metrics is not None: results = metrics.get_results() for k,v in results.items(): print('{:s}: {:.3f}'.format(k, v)) # save if needed if 'metrics' in args.save: os.makedirs(os.path.dirname(fname), exist_ok=True) with open(fname, 'wb') as fid: pickle.dump(results, fid) print('metrics saved in', fname) # finalize submission if needed if 'submission' in args.save: dataset.finalize_submission(submission_dir) if __name__ == '__main__': args = get_args_parser() args = args.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
# --------------------------------------------------------# Main training function# --------------------------------------------------------
import argparseimport datetimeimport jsonimport numpy as npimport osimport sysimport time
import torchimport torch.distributed as distimport torch.backends.cudnn as cudnnfrom torch.utils.tensorboard import SummaryWriterimport torchvision.transforms as transformsimport torchvision.datasets as datasetsfrom torch.utils.data import DataLoader
import utilsimport utils.misc as miscfrom utils.misc import NativeScalerWithGradNormCount as NativeScalerfrom models.croco_downstream import CroCoDownstreamBinocular, croco_args_from_ckptfrom models.pos_embed import interpolate_pos_embedfrom models.head_downstream import PixelwiseTaskWithDPT
from stereoflow.datasets_stereo import get_train_dataset_stereo, get_test_datasets_stereofrom stereoflow.datasets_flow import get_train_dataset_flow, get_test_datasets_flowfrom stereoflow.engine import train_one_epoch, validate_one_epochfrom stereoflow.criterion import *
def get_args_parser(): # prepare subparsers parser = argparse.ArgumentParser('Finetuning CroCo models on stereo or flow', add_help=False) subparsers = parser.add_subparsers(title="Task (stereo or flow)", dest="task", required=True) parser_stereo = subparsers.add_parser('stereo', help='Training stereo model') parser_flow = subparsers.add_parser('flow', help='Training flow model') def add_arg(name_or_flags, default=None, default_stereo=None, default_flow=None, **kwargs): if default is not None: assert default_stereo is None and default_flow is None, "setting default makes default_stereo and default_flow disabled" parser_stereo.add_argument(name_or_flags, default=default if default is not None else default_stereo, **kwargs) parser_flow.add_argument(name_or_flags, default=default if default is not None else default_flow, **kwargs) # output dir add_arg('--output_dir', required=True, type=str, help='path where to save, if empty, automatically created') # model add_arg('--crop', type=int, nargs = '+', default_stereo=[352, 704], default_flow=[320, 384], help = "size of the random image crops used during training.") add_arg('--pretrained', required=True, type=str, help="Load pretrained model (required as croco arguments come from there)") # criterion add_arg('--criterion', default_stereo='LaplacianLossBounded2()', default_flow='LaplacianLossBounded()', type=str, help='string to evaluate to get criterion') add_arg('--bestmetric', default_stereo='avgerr', default_flow='EPE', type=str) # dataset add_arg('--dataset', type=str, required=True, help="training set") # training add_arg('--seed', default=0, type=int, help='seed') add_arg('--batch_size', default_stereo=6, default_flow=8, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') add_arg('--epochs', default=32, type=int, help='number of training epochs') add_arg('--img_per_epoch', type=int, default=None, help='Fix the number of images seen in an epoch (None means use all training pairs)') add_arg('--accum_iter', default=1, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') add_arg('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') add_arg('--lr', type=float, default_stereo=3e-5, default_flow=2e-5, metavar='LR', help='learning rate (absolute lr)') add_arg('--min_lr', type=float, default=0., metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') add_arg('--warmup_epochs', type=int, default=1, metavar='N', help='epochs to warmup LR') add_arg('--optimizer', default='AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95))', type=str, help="Optimizer from torch.optim [ default: AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95)) ]") add_arg('--amp', default=0, type=int, choices=[0,1], help='enable automatic mixed precision training') # validation add_arg('--val_dataset', type=str, default='', help="Validation sets, multiple separated by + (empty string means that no validation is performed)") add_arg('--tile_conf_mode', type=str, default_stereo='conf_expsigmoid_15_3', default_flow='conf_expsigmoid_10_5', help='Weights for tile aggregation') add_arg('--val_overlap', default=0.7, type=float, help='Overlap value for the tiling') # others add_arg('--num_workers', default=8, type=int) add_arg('--eval_every', type=int, default=1, help='Val loss evaluation frequency') add_arg('--save_every', type=int, default=1, help='Save checkpoint frequency') add_arg('--start_from', type=str, default=None, help='Start training using weights from an other model (eg for finetuning)') add_arg('--tboard_log_step', type=int, default=100, help='Log to tboard every so many steps') add_arg('--dist_url', default='env://', help='url used to set up distributed training')
return parser def main(args): misc.init_distributed_mode(args) global_rank = misc.get_rank() num_tasks = misc.get_world_size()
assert os.path.isfile(args.pretrained) print("output_dir: "+args.output_dir) os.makedirs(args.output_dir, exist_ok=True)
# fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True
# Metrics / criterion device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') metrics = (StereoMetrics if args.task=='stereo' else FlowMetrics)().to(device) criterion = eval(args.criterion).to(device) print('Criterion: ', args.criterion)
# Prepare model assert os.path.isfile(args.pretrained) ckpt = torch.load(args.pretrained, 'cpu') croco_args = croco_args_from_ckpt(ckpt) croco_args['img_size'] = (args.crop[0], args.crop[1]) print('Croco args: '+str(croco_args)) args.croco_args = croco_args # saved for test time # prepare head num_channels = {'stereo': 1, 'flow': 2}[args.task] if criterion.with_conf: num_channels += 1 print(f'Building head PixelwiseTaskWithDPT() with {num_channels} channel(s)') head = PixelwiseTaskWithDPT() head.num_channels = num_channels # build model and load pretrained weights model = CroCoDownstreamBinocular(head, **croco_args) interpolate_pos_embed(model, ckpt['model']) msg = model.load_state_dict(ckpt['model'], strict=False) print(msg)
total_params = sum(p.numel() for p in model.parameters()) total_params_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"Total params: {total_params}") print(f"Total params trainable: {total_params_trainable}") model_without_ddp = model.to(device)
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() print("lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size)
if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], static_graph=True) model_without_ddp = model.module # following timm: set wd as 0 for bias and norm layers param_groups = misc.get_parameter_groups(model_without_ddp, args.weight_decay) optimizer = eval(f"torch.optim.{args.optimizer}") print(optimizer) loss_scaler = NativeScaler() # automatic restart last_ckpt_fname = os.path.join(args.output_dir, f'checkpoint-last.pth') args.resume = last_ckpt_fname if os.path.isfile(last_ckpt_fname) else None
if not args.resume and args.start_from: print(f"Starting from an other model's weights: {args.start_from}") best_so_far = None args.start_epoch = 0 ckpt = torch.load(args.start_from, 'cpu') msg = model_without_ddp.load_state_dict(ckpt['model'], strict=False) print(msg) else: best_so_far = misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
if best_so_far is None: best_so_far = np.inf # tensorboard log_writer = None if global_rank == 0 and args.output_dir is not None: log_writer = SummaryWriter(log_dir=args.output_dir, purge_step=args.start_epoch*1000)
# dataset and loader print('Building Train Data loader for dataset: ', args.dataset) train_dataset = (get_train_dataset_stereo if args.task=='stereo' else get_train_dataset_flow)(args.dataset, crop_size=args.crop) def _print_repr_dataset(d): if isinstance(d, torch.utils.data.dataset.ConcatDataset): for dd in d.datasets: _print_repr_dataset(dd) else: print(repr(d)) _print_repr_dataset(train_dataset) print(' total length:', len(train_dataset)) if args.distributed: sampler_train = torch.utils.data.DistributedSampler( train_dataset, num_replicas=num_tasks, rank=global_rank, shuffle=True ) else: sampler_train = torch.utils.data.RandomSampler(train_dataset) data_loader_train = torch.utils.data.DataLoader( train_dataset, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=True, drop_last=True, ) if args.val_dataset=='': data_loaders_val = None else: print('Building Val Data loader for datasets: ', args.val_dataset) val_datasets = (get_test_datasets_stereo if args.task=='stereo' else get_test_datasets_flow)(args.val_dataset) for val_dataset in val_datasets: print(repr(val_dataset)) data_loaders_val = [DataLoader(val_dataset, batch_size=1, shuffle=False, num_workers=args.num_workers, pin_memory=True, drop_last=False) for val_dataset in val_datasets] bestmetric = ("AVG_" if len(data_loaders_val)>1 else str(data_loaders_val[0].dataset)+'_')+args.bestmetric print(f"Start training for {args.epochs} epochs") start_time = time.time() # Training Loop for epoch in range(args.start_epoch, args.epochs):
if args.distributed: data_loader_train.sampler.set_epoch(epoch) # Train epoch_start = time.time() train_stats = train_one_epoch(model, criterion, metrics, data_loader_train, optimizer, device, epoch, loss_scaler, log_writer=log_writer, args=args) epoch_time = time.time() - epoch_start
if args.distributed: dist.barrier()
# Validation (current naive implementation runs the validation on every gpu ... not smart ...) if data_loaders_val is not None and args.eval_every > 0 and (epoch+1) % args.eval_every == 0: val_epoch_start = time.time() val_stats = validate_one_epoch(model, criterion, metrics, data_loaders_val, device, epoch, log_writer=log_writer, args=args) val_epoch_time = time.time() - val_epoch_start
val_best = val_stats[bestmetric] # Save best of all if val_best <= best_so_far: best_so_far = val_best misc.save_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch, best_so_far=best_so_far, fname='best') log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch, **{f'val_{k}': v for k, v in val_stats.items()}} else: log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch,} if args.distributed: dist.barrier() # Save stuff if args.output_dir and ((epoch+1) % args.save_every == 0 or epoch + 1 == args.epochs): misc.save_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch, best_so_far=best_so_far, fname='last')
if args.output_dir: if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) if __name__ == '__main__': args = get_args_parser() args = args.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463# Copyright (C) 2022-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).# # --------------------------------------------------------# utilitary functions for CroCo# --------------------------------------------------------# References:# MAE: https://github.com/facebookresearch/mae# DeiT: https://github.com/facebookresearch/deit# BEiT: https://github.com/microsoft/unilm/tree/master/beit# --------------------------------------------------------
import builtinsimport datetimeimport osimport timeimport mathimport jsonfrom collections import defaultdict, dequefrom pathlib import Pathimport numpy as np
import torchimport torch.distributed as distfrom torch import inf
class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the global series average. """
def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{median:.4f} ({global_avg:.4f})" self.deque = deque(maxlen=window_size) self.total = 0.0 self.count = 0 self.fmt = fmt
def update(self, value, n=1): self.deque.append(value) self.count += n self.total += value * n
def synchronize_between_processes(self): """ Warning: does not synchronize the deque! """ if not is_dist_avail_and_initialized(): return t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') dist.barrier() dist.all_reduce(t) t = t.tolist() self.count = int(t[0]) self.total = t[1]
@property def median(self): d = torch.tensor(list(self.deque)) return d.median().item()
@property def avg(self): d = torch.tensor(list(self.deque), dtype=torch.float32) return d.mean().item()
@property def global_avg(self): return self.total / self.count
@property def max(self): return max(self.deque)
@property def value(self): return self.deque[-1]
def __str__(self): return self.fmt.format( median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value)
class MetricLogger(object): def __init__(self, delimiter="\t"): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter
def update(self, **kwargs): for k, v in kwargs.items(): if v is None: continue if isinstance(v, torch.Tensor): v = v.item() assert isinstance(v, (float, int)) self.meters[k].update(v)
def __getattr__(self, attr): if attr in self.meters: return self.meters[attr] if attr in self.__dict__: return self.__dict__[attr] raise AttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, attr))
def __str__(self): loss_str = [] for name, meter in self.meters.items(): loss_str.append( "{}: {}".format(name, str(meter)) ) return self.delimiter.join(loss_str)
def synchronize_between_processes(self): for meter in self.meters.values(): meter.synchronize_between_processes()
def add_meter(self, name, meter): self.meters[name] = meter
def log_every(self, iterable, print_freq, header=None, max_iter=None): i = 0 if not header: header = '' start_time = time.time() end = time.time() iter_time = SmoothedValue(fmt='{avg:.4f}') data_time = SmoothedValue(fmt='{avg:.4f}') len_iterable = min(len(iterable), max_iter) if max_iter else len(iterable) space_fmt = ':' + str(len(str(len_iterable))) + 'd' log_msg = [ header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}', 'time: {time}', 'data: {data}' ] if torch.cuda.is_available(): log_msg.append('max mem: {memory:.0f}') log_msg = self.delimiter.join(log_msg) MB = 1024.0 * 1024.0 for it,obj in enumerate(iterable): data_time.update(time.time() - end) yield obj iter_time.update(time.time() - end) if i % print_freq == 0 or i == len_iterable - 1: eta_seconds = iter_time.global_avg * (len_iterable - i) eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) if torch.cuda.is_available(): print(log_msg.format( i, len_iterable, eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time), memory=torch.cuda.max_memory_allocated() / MB)) else: print(log_msg.format( i, len_iterable, eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time))) i += 1 end = time.time() if max_iter and it >= max_iter: break total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('{} Total time: {} ({:.4f} s / it)'.format( header, total_time_str, total_time / len_iterable))
def setup_for_distributed(is_master): """ This function disables printing when not in master process """ builtin_print = builtins.print
def print(*args, **kwargs): force = kwargs.pop('force', False) force = force or (get_world_size() > 8) if is_master or force: now = datetime.datetime.now().time() builtin_print('[{}] '.format(now), end='') # print with time stamp builtin_print(*args, **kwargs)
builtins.print = print
def is_dist_avail_and_initialized(): if not dist.is_available(): return False if not dist.is_initialized(): return False return True
def get_world_size(): if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size()
def get_rank(): if not is_dist_avail_and_initialized(): return 0 return dist.get_rank()
def is_main_process(): return get_rank() == 0
def save_on_master(*args, **kwargs): if is_main_process(): torch.save(*args, **kwargs)
def init_distributed_mode(args): nodist = args.nodist if hasattr(args,'nodist') else False if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ and not nodist: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ['WORLD_SIZE']) args.gpu = int(os.environ['LOCAL_RANK']) else: print('Not using distributed mode') setup_for_distributed(is_master=True) # hack args.distributed = False return
args.distributed = True
torch.cuda.set_device(args.gpu) args.dist_backend = 'nccl' print('| distributed init (rank {}): {}, gpu {}'.format( args.rank, args.dist_url, args.gpu), flush=True) torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank) torch.distributed.barrier() setup_for_distributed(args.rank == 0)
class NativeScalerWithGradNormCount: state_dict_key = "amp_scaler"
def __init__(self, enabled=True): self._scaler = torch.cuda.amp.GradScaler(enabled=enabled)
def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): self._scaler.scale(loss).backward(create_graph=create_graph) if update_grad: if clip_grad is not None: assert parameters is not None self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad) else: self._scaler.unscale_(optimizer) norm = get_grad_norm_(parameters) self._scaler.step(optimizer) self._scaler.update() else: norm = None return norm
def state_dict(self): return self._scaler.state_dict()
def load_state_dict(self, state_dict): self._scaler.load_state_dict(state_dict)
def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor: if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = [p for p in parameters if p.grad is not None] norm_type = float(norm_type) if len(parameters) == 0: return torch.tensor(0.) device = parameters[0].grad.device if norm_type == inf: total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters) else: total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type) return total_norm
def save_model(args, epoch, model_without_ddp, optimizer, loss_scaler, fname=None, best_so_far=None): output_dir = Path(args.output_dir) if fname is None: fname = str(epoch) checkpoint_path = output_dir / ('checkpoint-%s.pth' % fname) to_save = { 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'scaler': loss_scaler.state_dict(), 'args': args, 'epoch': epoch, } if best_so_far is not None: to_save['best_so_far'] = best_so_far print(f'>> Saving model to {checkpoint_path} ...') save_on_master(to_save, checkpoint_path)
def load_model(args, model_without_ddp, optimizer, loss_scaler): args.start_epoch = 0 best_so_far = None if args.resume is not None: if args.resume.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.resume, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.resume, map_location='cpu') print("Resume checkpoint %s" % args.resume) model_without_ddp.load_state_dict(checkpoint['model'], strict=False) args.start_epoch = checkpoint['epoch'] + 1 optimizer.load_state_dict(checkpoint['optimizer']) if 'scaler' in checkpoint: loss_scaler.load_state_dict(checkpoint['scaler']) if 'best_so_far' in checkpoint: best_so_far = checkpoint['best_so_far'] print(" & best_so_far={:g}".format(best_so_far)) else: print("") print("With optim & sched! start_epoch={:d}".format(args.start_epoch), end='') return best_so_far
def all_reduce_mean(x): world_size = get_world_size() if world_size > 1: x_reduce = torch.tensor(x).cuda() dist.all_reduce(x_reduce) x_reduce /= world_size return x_reduce.item() else: return x
def _replace(text, src, tgt, rm=''): """ Advanced string replacement. Given a text: - replace all elements in src by the corresponding element in tgt - remove all elements in rm """ if len(tgt) == 1: tgt = tgt * len(src) assert len(src) == len(tgt), f"'{src}' and '{tgt}' should have the same len" for s,t in zip(src, tgt): text = text.replace(s,t) for c in rm: text = text.replace(c,'') return text def filename( obj ): """ transform a python obj or cmd into a proper filename. - \1 gets replaced by slash '/' - \2 gets replaced by comma ',' """ if not isinstance(obj, str): obj = repr(obj) obj = str(obj).replace('()','') obj = _replace(obj, '_,(*/\1\2','-__x%/,', rm=' )\'"') assert all(len(s) < 256 for s in obj.split(os.sep)), 'filename too long (>256 characters):\n'+obj return obj
def _get_num_layer_for_vit(var_name, enc_depth, dec_depth): if var_name in ("cls_token", "mask_token", "pos_embed", "global_tokens"): return 0 elif var_name.startswith("patch_embed"): return 0 elif var_name.startswith("enc_blocks"): layer_id = int(var_name.split('.')[1]) return layer_id + 1 elif var_name.startswith('decoder_embed') or var_name.startswith('enc_norm'): # part of the last black return enc_depth elif var_name.startswith('dec_blocks'): layer_id = int(var_name.split('.')[1]) return enc_depth + layer_id + 1 elif var_name.startswith('dec_norm'): # part of the last block return enc_depth + dec_depth elif any(var_name.startswith(k) for k in ['head','prediction_head']): return enc_depth + dec_depth + 1 else: raise NotImplementedError(var_name)
def get_parameter_groups(model, weight_decay, layer_decay=1.0, skip_list=(), no_lr_scale_list=[]): parameter_group_names = {} parameter_group_vars = {} enc_depth, dec_depth = None, None # prepare layer decay values assert layer_decay==1.0 or 0.<layer_decay<1. if layer_decay<1.: enc_depth = model.enc_depth dec_depth = model.dec_depth if hasattr(model, 'dec_blocks') else 0 num_layers = enc_depth+dec_depth layer_decay_values = list(layer_decay ** (num_layers + 1 - i) for i in range(num_layers + 2)) for name, param in model.named_parameters(): if not param.requires_grad: continue # frozen weights
# Assign weight decay values if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: group_name = "no_decay" this_weight_decay = 0. else: group_name = "decay" this_weight_decay = weight_decay
# Assign layer ID for LR scaling if layer_decay<1.: skip_scale = False layer_id = _get_num_layer_for_vit(name, enc_depth, dec_depth) group_name = "layer_%d_%s" % (layer_id, group_name) if name in no_lr_scale_list: skip_scale = True group_name = f'{group_name}_no_lr_scale' else: layer_id = 0 skip_scale = True
if group_name not in parameter_group_names: if not skip_scale: scale = layer_decay_values[layer_id] else: scale = 1.
parameter_group_names[group_name] = { "weight_decay": this_weight_decay, "params": [], "lr_scale": scale } parameter_group_vars[group_name] = { "weight_decay": this_weight_decay, "params": [], "lr_scale": scale }
parameter_group_vars[group_name]["params"].append(param) parameter_group_names[group_name]["params"].append(name) print("Param groups = %s" % json.dumps(parameter_group_names, indent=2)) return list(parameter_group_vars.values())
def adjust_learning_rate(optimizer, epoch, args): """Decay the learning rate with half-cycle cosine after warmup""" if epoch < args.warmup_epochs: lr = args.lr * epoch / args.warmup_epochs else: lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \ (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs))) for param_group in optimizer.param_groups: if "lr_scale" in param_group: param_group["lr"] = lr * param_group["lr_scale"] else: param_group["lr"] = lr return lr123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566## Steps to reproduce synthetic training data using the Habitat-Sim simulator
### Create a conda environment```bashconda create -n habitat python=3.8 habitat-sim=0.2.1 headless=2.0 -c aihabitat -c conda-forgeconda active habitatconda install pytorch -c pytorchpip install opencv-python tqdm```
or (if you get the error `For headless systems, compile with --headless for EGL support`)```git clone --branch stable https://github.com/facebookresearch/habitat-sim.gitcd habitat-sim
conda create -n habitat python=3.9 cmake=3.14.0conda activate habitatpip install . -vconda install pytorch -c pytorchpip install opencv-python tqdm```
### Download Habitat-Sim scenesDownload Habitat-Sim scenes:- Download links can be found here: https://github.com/facebookresearch/habitat-sim/blob/main/DATASETS.md- We used scenes from the HM3D, habitat-test-scenes, ReplicaCad and ScanNet datasets.- Please put the scenes in a directory `$SCENES_DIR` following the structure below:(Note: the habitat-sim dataset installer may install an incompatible version for ReplicaCAD backed lighting.The correct scene dataset can be dowloaded from Huggingface: `git clone git@hf.co:datasets/ai-habitat/ReplicaCAD_baked_lighting`).```$SCENES_DIR/├──hm3d/├──gibson/├──habitat-test-scenes/├──ReplicaCAD_baked_lighting/└──scannet/```
### Download renderings metadata
Download metadata corresponding to each scene and extract them into a directory `$METADATA_DIR````bashwget https://download.europe.naverlabs.com/ComputerVision/DUSt3R/habitat_5views_v1_512x512_metadata.tar.gztar -xvzf habitat_5views_v1_512x512_metadata.tar.gz```
### Render the scenes
Render the scenes in an output directory `$OUTPUT_DIR````bashexport METADATA_DIR="/path/to/habitat/5views_v1_512x512_metadata"export SCENES_DIR="/path/to/habitat/data/scene_datasets/"export OUTPUT_DIR="data/habitat_processed"cd datasets_preprocess/habitat/export PYTHONPATH=$(pwd)# Print commandlines to generate images corresponding to each scenepython preprocess_habitat.py --scenes_dir=$SCENES_DIR --metadata_dir=$METADATA_DIR --output_dir=$OUTPUT_DIR# Launch these commandlines in parallel e.g. using GNU-Parallel as follows:python preprocess_habitat.py --scenes_dir=$SCENES_DIR --metadata_dir=$METADATA_DIR --output_dir=$OUTPUT_DIR | parallel -j 16```
### Make a list of scenes
```bashpython find_scenes.py --root $OUTPUT_DIR```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778#!/usr/bin/env python3# Copyright (C) 2024-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).## --------------------------------------------------------# Script to export the list of scenes for habitat (after having rendered them).# Usage:# python3 datasets_preprocess/preprocess_co3d.py --root data/habitat_processed# --------------------------------------------------------import numpy as npimport osfrom collections import defaultdictfrom tqdm import tqdm
def find_all_scenes(habitat_root, n_scenes=[100000]): np.random.seed(777)
try: fpath = os.path.join(habitat_root, f'Habitat_all_scenes.txt') list_subscenes = open(fpath).read().splitlines()
except IOError: if input('parsing sub-folders to find scenes? (y/n) ') != 'y': return list_subscenes = [] for root, dirs, files in tqdm(os.walk(habitat_root)): for f in files: if not f.endswith('_1_depth.exr'): continue scene = os.path.join(os.path.relpath(root, habitat_root), f.replace('_1_depth.exr', '')) if hash(scene) % 1000 == 0: print('... adding', scene) list_subscenes.append(scene)
with open(fpath, 'w') as f: f.write('\n'.join(list_subscenes)) print(f'>> wrote {fpath}')
print(f'Loaded {len(list_subscenes)} sub-scenes')
# separate scenes list_scenes = defaultdict(list) for scene in list_subscenes: scene, id = os.path.split(scene) list_scenes[scene].append(id)
list_scenes = list(list_scenes.items()) print(f'from {len(list_scenes)} scenes in total')
np.random.shuffle(list_scenes) train_scenes = list_scenes[len(list_scenes)//10:] val_scenes = list_scenes[:len(list_scenes)//10]
def write_scene_list(scenes, n, fpath): sub_scenes = [os.path.join(scene, id) for scene, ids in scenes for id in ids] np.random.shuffle(sub_scenes)
if len(sub_scenes) < n: return
with open(fpath, 'w') as f: f.write('\n'.join(sub_scenes[:n])) print(f'>> wrote {fpath}')
for n in n_scenes: write_scene_list(train_scenes, n, os.path.join(habitat_root, f'Habitat_{n}_scenes_train.txt')) write_scene_list(val_scenes, n//10, os.path.join(habitat_root, f'Habitat_{n//10}_scenes_val.txt'))
if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--root", required=True) parser.add_argument("--n_scenes", nargs='+', default=[1_000, 1_000_000], type=int)
args = parser.parse_args() find_all_scenes(args.root, args.n_scenes)12# Copyright (C) 2024-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170# Copyright (C) 2024-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).## --------------------------------------------------------# Render environment maps from 3D meshes using the Habitat Sim simulator.# --------------------------------------------------------import numpy as npimport habitat_simimport mathfrom habitat_renderer import projections
# OpenCV to habitat camera convention transformationR_OPENCV2HABITAT = np.stack((habitat_sim.geo.RIGHT, -habitat_sim.geo.UP, habitat_sim.geo.FRONT), axis=0)
CUBEMAP_FACE_LABELS = ["left", "front", "right", "back", "up", "down"]# Expressed while considering Habitat coordinates systemsCUBEMAP_FACE_ORIENTATIONS_ROTVEC = [ [0, math.pi / 2, 0], # Left [0, 0, 0], # Front [0, - math.pi / 2, 0], # Right [0, math.pi, 0], # Back [math.pi / 2, 0, 0], # Up [-math.pi / 2, 0, 0],] # Down
class NoNaviguableSpaceError(RuntimeError): def __init__(self, *args): super().__init__(*args)
class HabitatEnvironmentMapRenderer: def __init__(self, scene, navmesh, scene_dataset_config_file, render_equirectangular=False, equirectangular_resolution=(512, 1024), render_cubemap=False, cubemap_resolution=(512, 512), render_depth=False, gpu_id=0): self.scene = scene self.navmesh = navmesh self.scene_dataset_config_file = scene_dataset_config_file self.gpu_id = gpu_id
self.render_equirectangular = render_equirectangular self.equirectangular_resolution = equirectangular_resolution self.equirectangular_projection = projections.EquirectangularProjection(*equirectangular_resolution) # 3D unit ray associated to each pixel of the equirectangular map equirectangular_rays = projections.get_projection_rays(self.equirectangular_projection) # Not needed, but just in case. equirectangular_rays /= np.linalg.norm(equirectangular_rays, axis=-1, keepdims=True) # Depth map created by Habitat are produced by warping a cubemap, # so the values do not correspond to distance to the center and need some scaling. self.equirectangular_depth_scale_factors = 1.0 / np.max(np.abs(equirectangular_rays), axis=-1)
self.render_cubemap = render_cubemap self.cubemap_resolution = cubemap_resolution
self.render_depth = render_depth
self.seed = None self._lazy_initialization()
def _lazy_initialization(self): # Lazy random seeding and instantiation of the simulator to deal with multiprocessing properly if self.seed == None: # Re-seed numpy generator np.random.seed() self.seed = np.random.randint(2**32-1) sim_cfg = habitat_sim.SimulatorConfiguration() sim_cfg.scene_id = self.scene if self.scene_dataset_config_file is not None and self.scene_dataset_config_file != "": sim_cfg.scene_dataset_config_file = self.scene_dataset_config_file sim_cfg.random_seed = self.seed sim_cfg.load_semantic_mesh = False sim_cfg.gpu_device_id = self.gpu_id
sensor_specifications = []
# Add cubemaps if self.render_cubemap: for face_id, orientation in enumerate(CUBEMAP_FACE_ORIENTATIONS_ROTVEC): rgb_sensor_spec = habitat_sim.CameraSensorSpec() rgb_sensor_spec.uuid = f"color_cubemap_{CUBEMAP_FACE_LABELS[face_id]}" rgb_sensor_spec.sensor_type = habitat_sim.SensorType.COLOR rgb_sensor_spec.resolution = self.cubemap_resolution rgb_sensor_spec.hfov = 90 rgb_sensor_spec.position = [0.0, 0.0, 0.0] rgb_sensor_spec.orientation = orientation sensor_specifications.append(rgb_sensor_spec)
if self.render_depth: depth_sensor_spec = habitat_sim.CameraSensorSpec() depth_sensor_spec.uuid = f"depth_cubemap_{CUBEMAP_FACE_LABELS[face_id]}" depth_sensor_spec.sensor_type = habitat_sim.SensorType.DEPTH depth_sensor_spec.resolution = self.cubemap_resolution depth_sensor_spec.hfov = 90 depth_sensor_spec.position = [0.0, 0.0, 0.0] depth_sensor_spec.orientation = orientation sensor_specifications.append(depth_sensor_spec)
# Add equirectangular map if self.render_equirectangular: rgb_sensor_spec = habitat_sim.bindings.EquirectangularSensorSpec() rgb_sensor_spec.uuid = "color_equirectangular" rgb_sensor_spec.resolution = self.equirectangular_resolution rgb_sensor_spec.position = [0.0, 0.0, 0.0] sensor_specifications.append(rgb_sensor_spec)
if self.render_depth: depth_sensor_spec = habitat_sim.bindings.EquirectangularSensorSpec() depth_sensor_spec.uuid = "depth_equirectangular" depth_sensor_spec.sensor_type = habitat_sim.SensorType.DEPTH depth_sensor_spec.resolution = self.equirectangular_resolution depth_sensor_spec.position = [0.0, 0.0, 0.0] depth_sensor_spec.orientation sensor_specifications.append(depth_sensor_spec)
agent_cfg = habitat_sim.agent.AgentConfiguration(sensor_specifications=sensor_specifications)
cfg = habitat_sim.Configuration(sim_cfg, [agent_cfg]) self.sim = habitat_sim.Simulator(cfg) if self.navmesh is not None and self.navmesh != "": # Use pre-computed navmesh (the one generated automatically does some weird stuffs like going on top of the roof) # See https://youtu.be/kunFMRJAu2U?t=1522 regarding navmeshes self.sim.pathfinder.load_nav_mesh(self.navmesh)
# Check that the navmesh is not empty if not self.sim.pathfinder.is_loaded: # Try to compute a navmesh navmesh_settings = habitat_sim.NavMeshSettings() navmesh_settings.set_defaults() self.sim.recompute_navmesh(self.sim.pathfinder, navmesh_settings, True)
# Check that the navmesh is not empty if not self.sim.pathfinder.is_loaded: raise NoNaviguableSpaceError(f"No naviguable location (scene: {self.scene} -- navmesh: {self.navmesh})")
self.agent = self.sim.initialize_agent(agent_id=0)
def close(self): if hasattr(self, 'sim'): self.sim.close()
def __del__(self): self.close()
def render_viewpoint(self, viewpoint_position): agent_state = habitat_sim.AgentState() agent_state.position = viewpoint_position # agent_state.rotation = viewpoint_orientation self.agent.set_state(agent_state) viewpoint_observations = self.sim.get_sensor_observations(agent_ids=0)
try: # Depth map values have been obtained using cubemap rendering internally, # so they do not really correspond to distance to the viewpoint in practice # and they need some scaling viewpoint_observations["depth_equirectangular"] *= self.equirectangular_depth_scale_factors except KeyError: pass
data = dict(observations=viewpoint_observations, position=viewpoint_position) return data
def up_direction(self): return np.asarray(habitat_sim.geo.UP).tolist() def R_cam_to_world(self): return R_OPENCV2HABITAT.tolist()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Copyright (C) 2024-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).## --------------------------------------------------------# Generate pairs of crops from a dataset of environment maps.# --------------------------------------------------------import osimport numpy as npos.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1" # noqaimport cv2import collectionsfrom habitat_renderer import projections, projections_conversionsfrom habitat_renderer.habitat_sim_envmaps_renderer import HabitatEnvironmentMapRenderer
ViewpointData = collections.namedtuple("ViewpointData", ["colormap", "distancemap", "pointmap", "position"])
class HabitatMultiviewCrops: def __init__(self, scene, navmesh, scene_dataset_config_file, equirectangular_resolution=(400, 800), crop_resolution=(240, 320), pixel_jittering_iterations=5, jittering_noise_level=1.0): self.crop_resolution = crop_resolution
self.pixel_jittering_iterations = pixel_jittering_iterations self.jittering_noise_level = jittering_noise_level
# Instanciate the low resolution habitat sim renderer self.lowres_envmap_renderer = HabitatEnvironmentMapRenderer(scene=scene, navmesh=navmesh, scene_dataset_config_file=scene_dataset_config_file, equirectangular_resolution=equirectangular_resolution, render_depth=True, render_equirectangular=True) self.R_cam_to_world = np.asarray(self.lowres_envmap_renderer.R_cam_to_world()) self.up_direction = np.asarray(self.lowres_envmap_renderer.up_direction())
# Projection applied by each environment map self.envmap_height, self.envmap_width = self.lowres_envmap_renderer.equirectangular_resolution base_projection = projections.EquirectangularProjection(self.envmap_height, self.envmap_width) self.envmap_projection = projections.RotatedProjection(base_projection, self.R_cam_to_world.T) # 3D Rays map associated to each envmap self.envmap_rays = projections.get_projection_rays(self.envmap_projection)
def compute_pointmap(self, distancemap, position): # Point cloud associated to each ray return self.envmap_rays * distancemap[:, :, None] + position
def render_viewpoint_data(self, position): data = self.lowres_envmap_renderer.render_viewpoint(np.asarray(position)) colormap = data['observations']['color_equirectangular'][..., :3] # Ignore the alpha channel distancemap = data['observations']['depth_equirectangular'] pointmap = self.compute_pointmap(distancemap, position) return ViewpointData(colormap=colormap, distancemap=distancemap, pointmap=pointmap, position=position)
def extract_cropped_camera(self, projection, color_image, distancemap, pointmap, voxelmap=None): remapper = projections_conversions.RemapProjection(input_projection=self.envmap_projection, output_projection=projection, pixel_jittering_iterations=self.pixel_jittering_iterations, jittering_noise_level=self.jittering_noise_level) cropped_color_image = remapper.convert( color_image, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_WRAP, single_map=False) cropped_distancemap = remapper.convert( distancemap, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_WRAP, single_map=True) cropped_pointmap = remapper.convert(pointmap, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_WRAP, single_map=True) cropped_voxelmap = (None if voxelmap is None else remapper.convert(voxelmap, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_WRAP, single_map=True)) # Convert the distance map into a depth map cropped_depthmap = np.asarray( cropped_distancemap / np.linalg.norm(remapper.output_rays, axis=-1), dtype=cropped_distancemap.dtype)
return cropped_color_image, cropped_depthmap, cropped_pointmap, cropped_voxelmap
def perspective_projection_to_dict(persp_projection, position): """ Serialization-like function.""" camera_params = dict(camera_intrinsics=projections.colmap_to_opencv_intrinsics(persp_projection.base_projection.K).tolist(), size=(persp_projection.base_projection.width, persp_projection.base_projection.height), R_cam2world=persp_projection.R_to_base_projection.T.tolist(), t_cam2world=position) return camera_params
def dict_to_perspective_projection(camera_params): K = projections.opencv_to_colmap_intrinsics(np.asarray(camera_params["camera_intrinsics"])) size = camera_params["size"] R_cam2world = np.asarray(camera_params["R_cam2world"]) projection = projections.PerspectiveProjection(K, height=size[1], width=size[0]) projection = projections.RotatedProjection(projection, R_to_base_projection=R_cam2world.T) position = camera_params["t_cam2world"] return projection, position123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151# Copyright (C) 2024-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).## --------------------------------------------------------# Various 3D/2D projection utils, useful to sample virtual cameras.# --------------------------------------------------------import numpy as np
class EquirectangularProjection: """ Convention for the central pixel of the equirectangular map similar to OpenCV perspective model: +X from left to right +Y from top to bottom +Z going outside the camera EXCEPT that the top left corner of the image is assumed to have (0,0) coordinates (OpenCV assumes (-0.5,-0.5)) """
def __init__(self, height, width): self.height = height self.width = width self.u_scaling = (2 * np.pi) / self.width self.v_scaling = np.pi / self.height
def unproject(self, u, v): """ Args: u, v: 2D coordinates Returns: unnormalized 3D rays. """ longitude = self.u_scaling * u - np.pi minus_latitude = self.v_scaling * v - np.pi/2
cos_latitude = np.cos(minus_latitude) x, z = np.sin(longitude) * cos_latitude, np.cos(longitude) * cos_latitude y = np.sin(minus_latitude)
rays = np.stack([x, y, z], axis=-1) return rays
def project(self, rays): """ Args: rays: Bx3 array of 3D rays. Returns: u, v: tuple of 2D coordinates. """ rays = rays / np.linalg.norm(rays, axis=-1, keepdims=True) x, y, z = [rays[..., i] for i in range(3)]
longitude = np.arctan2(x, z) minus_latitude = np.arcsin(y)
u = (longitude + np.pi) * (1.0 / self.u_scaling) v = (minus_latitude + np.pi/2) * (1.0 / self.v_scaling) return u, v
class PerspectiveProjection: """ OpenCV convention: World space: +X from left to right +Y from top to bottom +Z going outside the camera Pixel space: +u from left to right +v from top to bottom EXCEPT that the top left corner of the image is assumed to have (0,0) coordinates (OpenCV assumes (-0.5,-0.5)). """
def __init__(self, K, height, width): self.height = height self.width = width self.K = K self.Kinv = np.linalg.inv(K)
def project(self, rays): uv_homogeneous = np.einsum("ik, ...k -> ...i", self.K, rays) uv = uv_homogeneous[..., :2] / uv_homogeneous[..., 2, None] return uv[..., 0], uv[..., 1]
def unproject(self, u, v): uv_homogeneous = np.stack((u, v, np.ones_like(u)), axis=-1) rays = np.einsum("ik, ...k -> ...i", self.Kinv, uv_homogeneous) return rays
class RotatedProjection: def __init__(self, base_projection, R_to_base_projection): self.base_projection = base_projection self.R_to_base_projection = R_to_base_projection
@property def width(self): return self.base_projection.width
@property def height(self): return self.base_projection.height
def project(self, rays): if self.R_to_base_projection is not None: rays = np.einsum("ik, ...k -> ...i", self.R_to_base_projection, rays) return self.base_projection.project(rays)
def unproject(self, u, v): rays = self.base_projection.unproject(u, v) if self.R_to_base_projection is not None: rays = np.einsum("ik, ...k -> ...i", self.R_to_base_projection.T, rays) return rays
def get_projection_rays(projection, noise_level=0): """ Return a 2D map of 3D rays corresponding to the projection. If noise_level > 0, add some jittering noise to these rays. """ grid_u, grid_v = np.meshgrid(0.5 + np.arange(projection.width), 0.5 + np.arange(projection.height)) if noise_level > 0: grid_u += np.clip(0, noise_level * np.random.uniform(-0.5, 0.5, size=grid_u.shape), projection.width) grid_v += np.clip(0, noise_level * np.random.uniform(-0.5, 0.5, size=grid_v.shape), projection.height) return projection.unproject(grid_u, grid_v)
def compute_camera_intrinsics(height, width, hfov): f = width/2 / np.tan(hfov/2 * np.pi/180) cu, cv = width/2, height/2 return f, cu, cv
def colmap_to_opencv_intrinsics(K): """ Modify camera intrinsics to follow a different convention. Coordinates of the center of the top-left pixels are by default: - (0.5, 0.5) in Colmap - (0,0) in OpenCV """ K = K.copy() K[0, 2] -= 0.5 K[1, 2] -= 0.5 return K
def opencv_to_colmap_intrinsics(K): """ Modify camera intrinsics to follow a different convention. Coordinates of the center of the top-left pixels are by default: - (0.5, 0.5) in Colmap - (0,0) in OpenCV """ K = K.copy() K[0, 2] += 0.5 K[1, 2] += 0.5 return K123456789101112131415161718192021222324252627282930313233343536373839404142434445# Copyright (C) 2024-present Naver Corporation. All rights reserved.# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).## --------------------------------------------------------# Remap data from one projection to an other# --------------------------------------------------------import numpy as npimport cv2from habitat_renderer import projections
class RemapProjection: def __init__(self, input_projection, output_projection, pixel_jittering_iterations=0, jittering_noise_level=0): """ Some naive random jittering can be introduced in the remapping to mitigate aliasing artecfacts. """ assert jittering_noise_level >= 0 assert pixel_jittering_iterations >= 0
maps = [] # Initial map self.output_rays = projections.get_projection_rays(output_projection) map_u, map_v = input_projection.project(self.output_rays) map_u, map_v = np.asarray(map_u, dtype=np.float32), np.asarray(map_v, dtype=np.float32) maps.append((map_u, map_v))
for _ in range(pixel_jittering_iterations): # Define multiple mappings using some coordinates jittering to mitigate aliasing effects crop_rays = projections.get_projection_rays(output_projection, jittering_noise_level) map_u, map_v = input_projection.project(crop_rays) map_u, map_v = np.asarray(map_u, dtype=np.float32), np.asarray(map_v, dtype=np.float32) maps.append((map_u, map_v)) self.maps = maps
def convert(self, img, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_WRAP, single_map=False): remapped = [] for map_u, map_v in self.maps: res = cv2.remap(img, map_u, map_v, interpolation=interpolation, borderMode=borderMode) remapped.append(res) if single_map: break if len(remapped) == 1: res = remapped[0] else: res = np.asarray(np.mean(remapped, axis=0), dtype=img.dtype) return resdust3r/croco/LICENSEAdded+52
dust3r/croco/NOTICEAdded+21
dust3r/croco/README.MDAdded+124
dust3r/croco/croco-stereo-flow-demo.ipynbAdded+191
dust3r/croco/datasets/__init__.pyAdded
dust3r/croco/datasets/crops/README.MDAdded+104
dust3r/croco/datasets/crops/extract_crops_from_images.pyAdded+159
dust3r/croco/datasets/habitat_sim/README.MDAdded+76
dust3r/croco/datasets/habitat_sim/__init__.pyAdded
dust3r/croco/datasets/habitat_sim/generate_from_metadata.pyAdded+92
dust3r/croco/datasets/habitat_sim/generate_from_metadata_files.pyAdded+27
dust3r/croco/datasets/habitat_sim/generate_multiview_images.pyAdded+177
dust3r/croco/datasets/habitat_sim/multiview_habitat_sim_generator.pyAdded+390
dust3r/croco/datasets/habitat_sim/pack_metadata_files.pyAdded+69
dust3r/croco/datasets/habitat_sim/paths.pyAdded+129
dust3r/croco/datasets/pairs_dataset.pyAdded+109
dust3r/croco/datasets/transforms.pyAdded+95
dust3r/croco/demo.pyAdded+55
dust3r/croco/interactive_demo.ipynbAdded+271
dust3r/croco/models/blocks.pyAdded+241
dust3r/croco/models/criterion.pyAdded+37
dust3r/croco/models/croco.pyAdded+249
dust3r/croco/models/croco_downstream.pyAdded+122
dust3r/croco/models/curope/__init__.pyAdded+4
dust3r/croco/models/curope/curope.cppAdded+69
dust3r/croco/models/curope/curope2d.pyAdded+40
dust3r/croco/models/curope/kernels.cuAdded+108
dust3r/croco/models/curope/setup.pyAdded+34
dust3r/croco/models/dpt_block.pyAdded+450
dust3r/croco/models/head_downstream.pyAdded+58
dust3r/croco/models/masking.pyAdded+25
dust3r/croco/models/pos_embed.pyAdded+159
dust3r/croco/pretrain.pyAdded+254
dust3r/croco/stereoflow/README.MDAdded+318
dust3r/croco/stereoflow/augmentor.pyAdded+290
dust3r/croco/stereoflow/criterion.pyAdded+251
dust3r/croco/stereoflow/datasets_flow.pyAdded+630
dust3r/croco/stereoflow/datasets_stereo.pyAdded+674
dust3r/croco/stereoflow/download_model.shAdded+12
dust3r/croco/stereoflow/engine.pyAdded+280
dust3r/croco/stereoflow/test.pyAdded+216
dust3r/croco/stereoflow/train.pyAdded+253
dust3r/croco/utils/misc.pyAdded+463
dust3r/datasets_preprocess/habitat/README.mdAdded+66
dust3r/datasets_preprocess/habitat/find_scenes.pyAdded+78
dust3r/datasets_preprocess/habitat/habitat_renderer/__init__.pyAdded+2
dust3r/datasets_preprocess/habitat/habitat_renderer/habitat_sim_envmaps_renderer.pyAdded+170
dust3r/datasets_preprocess/habitat/habitat_renderer/multiview_crop_generator.pyAdded+93
dust3r/datasets_preprocess/habitat/habitat_renderer/projections.pyAdded+151
dust3r/datasets_preprocess/habitat/habitat_renderer/projections_conversions.pyAdded+45