Building blocks for uncertainty-aware cycle consistency presented at NeurIPS'21.

Overview

UncertaintyAwareCycleConsistency

This repository provides the building blocks and the API for the work presented in the NeurIPS'21 paper Robustness via Uncertainty-aware Cycle Consistency. Translation methods often learn deterministic mappings without explicitly modelling the robustness to outliers or predictive uncertainty, leading to performance degradation when encountering unseen perturbations at test time. To address this, we propose a method based on Uncertainty-aware Generalized Adaptive Cycle Consistency (UGAC), which models the per-pixel residual by generalized Gaussian distribution, capable of modelling heavy-tailed distributions.

Requirements

python >= 3.6.10
pytorch >= 1.6.0
jupyter lab
torchio
scikit-image
scikit-learn

The structure of the repository is as follows:

root
 |-ckpt/ (will save all the checkpoints)
 |-data/ (save your data and related script)
 |-src/ (contains all the source code)
    |-ds.py 
    |-networks.py
    |-utils.py
    |-losses.py

Preparing Datasets

To prepare your datasets to use with this repo, place the root directory of the dataset in data/. The recommended way to structure your data is shown below.

data/
    |-Dataset_1/
        |-A/
            |-image1.png
            |-image2.png
            |-image3.png
            |-...
        |-B/
            |-image1.png
            |-image2.png
            |-image3.png
            |-...

Note the images need not be paired. The python script src/ds.py provides the PyTorch Dataset class to read such a dataset, used as explained below.

class Images_w_nameList(data.Dataset):
    '''
    can act as supervised or un-supervised based on flists
    '''
    def __init__(self, root1, root2, flist1, flist2, transform=None):

Here root1 and root2 represents the root directory for domain A and B, respectively. flist1 and flist2 contain image names for domain A and domain B. Note, if flist1 and flist2 are aligned then dataset will load paired images. To use it as unsupervised dataset loader ensure that flist1 and flist2 are not aligned.

Learning models with uncertainty

src/networks.py provides the generator and discriminator architectures.

src/utils.py provides the training API train_UGAC. The API is to train a pair of GANs, with the generators modified to predict the parameters of the generalized Gaussian distribution GGD ($\alpha$, $\beta$, $\mu$), as depicted in the above figure.

An example command to use the first API is:

#first instantiate the generators and discriminators
netG_A = CasUNet_3head(3,3)
netD_A = NLayerDiscriminator(3, n_layers=4)
netG_B = CasUNet_3head(3,3)
netD_B = NLayerDiscriminator(3, n_layers=4)

netG_A, netD_A, netG_B, netD_B = train_UGAC(
    netG_A, netG_B,
    netD_A, netD_B,
    train_loader,
    dtype=torch.cuda.FloatTensor,
    device='cuda',
    num_epochs=10,
    init_lr=1e-5,
    ckpt_path='../ckpt/ugac',
    list_of_hp = [1, 0.015, 0.01, 0.001, 1, 0.015, 0.01, 0.001, 0.05, 0.05, 0.01],
)

This will save checkpoints in ckpt/ named as ugac_eph*.pth. The arguement list_of_hp is a list of all the hyper-parameters representing weights of different weigths in the loss function.

Apart from the code in this repository, we also use the code from many other repositories like this, this, and this.

Bibtex

If you find the bits from this project helpful, please cite the following works:

You might also like...
API for RL algorithm design & testing of BCA (Building Control Agent) HVAC on EnergyPlus building energy simulator by wrapping their EMS Python API
API for RL algorithm design & testing of BCA (Building Control Agent) HVAC on EnergyPlus building energy simulator by wrapping their EMS Python API

RL - EmsPy (work In Progress...) The EmsPy Python package was made to facilitate Reinforcement Learning (RL) algorithm research for developing and tes

Pytorch Implementation for NeurIPS (oral) paper: Pixel Level Cycle Association: A New Perspective for Domain Adaptive Semantic Segmentation

Pixel-Level Cycle Association This is the Pytorch implementation of our NeurIPS 2020 Oral paper Pixel-Level Cycle Association: A New Perspective for D

Code and models for ICCV2021 paper
Code and models for ICCV2021 paper "Robust Object Detection via Instance-Level Temporal Cycle Confusion".

Robust Object Detection via Instance-Level Temporal Cycle Confusion This repo contains the implementation of the ICCV 2021 paper, Robust Object Detect

pcnaDeep integrates cutting-edge detection techniques with tracking and cell cycle resolving models.
pcnaDeep integrates cutting-edge detection techniques with tracking and cell cycle resolving models.

pcnaDeep: a deep-learning based single-cell cycle profiler with PCNA signal Welcome! pcnaDeep integrates cutting-edge detection techniques with tracki

Cycle Consistent Adversarial Domain Adaptation (CyCADA)

Cycle Consistent Adversarial Domain Adaptation (CyCADA) A pytorch implementation of CyCADA. If you use this code in your research please consider citi

Official implementation of the paper ``Unifying Nonlocal Blocks for Neural Networks'' (ICCV'21)
Official implementation of the paper ``Unifying Nonlocal Blocks for Neural Networks'' (ICCV'21)

Spectral Nonlocal Block Overview Official implementation of the paper: Unifying Nonlocal Blocks for Neural Networks (ICCV'21) Spectral View of Nonloca

TensorFlow code for the neural network presented in the paper:
TensorFlow code for the neural network presented in the paper: "Structural Language Models of Code" (ICML'2020)

SLM: Structural Language Models of Code This is an official implementation of the model described in: "Structural Language Models of Code" [PDF] To ap

Provided is code that demonstrates the training and evaluation of the work presented in the paper:
Provided is code that demonstrates the training and evaluation of the work presented in the paper: "On the Detection of Digital Face Manipulation" published in CVPR 2020.

FFD Source Code Provided is code that demonstrates the training and evaluation of the work presented in the paper: "On the Detection of Digital Face M

Comments
  • RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 1, 256, 256]], which is output 0 of ReluBackward0, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

    RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 1, 256, 256]], which is output 0 of ReluBackward0, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

    Hi,

    Frankly speaking, I am a newbie to Pycharm and familiar with Tensorflow. While reproducing your code using Pycharm as the IDE, I am facing the following error. Can you please help me to resolve it? I would really appreciate your help. Thanks in advance.

    RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 1, 256, 256]], which is output 0 of ReluBackward0, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

    I have just edited the dataset file (to load the dataset in an unsupervised way from the directories) and created a new train.py file to run the code in Pycharm. All of the remaining code is exactly the same as you have shared.

    The dataset.py file is edited like this:

    import os
    import glob
    import torch
    import random
    import torch.utils.data as data
    from PIL import Image
    import torchvision.transforms as transforms
    
    
    class Images_with_Names(data.Dataset):
        """ can act both as Supervised or Un-supervised """
    
        def __init__(self, directory_A, directory_B, unsupervised=True, transform=None):
            self.directory_A = directory_A
            self.directory_B = directory_B
            self.unsupervised = unsupervised
            self.transform = transform
    
            self.imageList_A = sorted(glob.glob(f"{directory_A}/*.jpg*"))
            self.imageList_B = sorted(glob.glob(f"{directory_B}/*.jpg*"))
    
        def __getitem__(self, index):
            image_A = Image.open(self.imageList_A[index])
            if self.unsupervised:
                image_B = Image.open(self.imageList_B[random.randint(0, len(self.imageList_B) - 1)])
            else:
                image_B = Image.open(self.imageList_B[index])
    
            if self.transform is not None:
                image_A = self.transform(image_A)
                image_B = self.transform(image_B)
    
            return image_A, image_B
    
        def __len__(self):
            return max(len(self.imageList_A), len(self.imageList_B))
    
    def preprocessing(x):
        x = (x / 127.5) - 1
        x = torch.reshape(x, (-1, x.shape[0], x.shape[1], x.shape[2]))
        return x
    

    The train.py file is:

    import os
    import torch
    import torchvision.transforms as transforms
    from torchsummary import summary
    
    from utils import train_UGAC
    from dataset import Images_with_Names
    from dataset import preprocessing
    from Networks import CasUNet_3head, NLayerDiscriminator
    
    
    # First instantiate the generators and discriminators
    netG_A = CasUNet_3head(3, 3)
    netD_A = NLayerDiscriminator(3, n_layers=4)
    netG_B = CasUNet_3head(3, 3)
    netD_B = NLayerDiscriminator(3, n_layers=4)
    
    data_directory = "../code/UncertaintyAwareCycleConsistency/data/"
    directory_A = os.path.join(data_directory, "A")
    directory_B = os.path.join(data_directory, "B")
    
    data_transformer = transforms.Compose([transforms.PILToTensor(),
                                           transforms.Lambda(lambda x: preprocessing(x))])
    
    train_loader = Images_with_Names(directory_A=directory_A, directory_B=directory_B, unsupervised=True,
                                     transform=data_transformer)
    
    # summary(netG_A.cuda(), input_size=(3, 256, 256))
    train_UGAC(netG_A, netG_B, netD_A, netD_B, train_loader, dtype=torch.cuda.FloatTensor, device='cuda',
               num_epochs=10, init_lr=1e-5, ckpt_path='..saved_models/checkpoints/UGAC',
               list_of_hp=[1, 0.015, 0.01, 0.001, 1, 0.015, 0.01, 0.001, 0.05, 0.05, 0.01])
    

    Attempts that I have tried to resolve the issue are:

    1. Setting inplace=False to all Relu and LeakyReluactivations following this but failed.
    2. Tried to get traceback of forward call that caused the error with torch.autograd.set_detect_anomaly(True), it says the following:
    [W python_anomaly_mode.cpp:104] Warning: Error detected in ReluBackward0. Traceback of forward call that caused the error:
    
    File "/home/xyz/code/UncertaintyAwareCycleConsistency/src/train.py", line 29, in <module>
        netG_A, netG_B, netD_A, netD_B = train_UGAC(netG_A, netG_B, netD_A, netD_B, train_loader, dtype=torch.cuda.FloatTensor,
      File "/home/xyz/code/UncertaintyAwareCycleConsistency/src/utils.py", line 69, in train_UGAC
        t0, t0_alpha, t0_beta = netG_B(xA)
      File "/home/xyz/.conda/envs/pytorch/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
        return forward_call(*input, **kwargs)
      File "/home/xyz/code/UncertaintyAwareCycleConsistency/src/Networks.py", line 205, in forward
        y = self.unet_list[i](y + x)
      File "/home/xyz/.conda/envs/pytorch/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
        return forward_call(*input, **kwargs)
      File "/home/xyz/code/UncertaintyAwareCycleConsistency/src/Networks.py", line 181, in forward
        y_mean, y_alpha, y_beta = self.out_mean(x), self.out_alpha(x), self.out_beta(x)
    

    Looking forward to hearing from you soon. Thanks.

    opened by zeeshannisar 2
Owner
EML Tübingen
Explainable Machine Learning group at University of Tübingen
EML Tübingen
Learning Correspondence from the Cycle-consistency of Time (CVPR 2019)

TimeCycle Code for Learning Correspondence from the Cycle-consistency of Time (CVPR 2019, Oral). The code is developed based on the PyTorch framework,

Xiaolong Wang 706 Nov 29, 2022
This repository is the official implementation of Unleashing the Power of Contrastive Self-Supervised Visual Models via Contrast-Regularized Fine-Tuning (NeurIPS21).

Core-tuning This repository is the official implementation of ``Unleashing the Power of Contrastive Self-Supervised Visual Models via Contrast-Regular

vanint 18 Dec 17, 2022
LBK 35 Dec 26, 2022
Uncertainty-aware Semantic Segmentation of LiDAR Point Clouds for Autonomous Driving

SalsaNext: Fast, Uncertainty-aware Semantic Segmentation of LiDAR Point Clouds for Autonomous Driving Abstract In this paper, we introduce SalsaNext f

null 308 Jan 4, 2023
Official PyTorch implementation of UACANet: Uncertainty Aware Context Attention for Polyp Segmentation

UACANet: Uncertainty Aware Context Attention for Polyp Segmentation Official pytorch implementation of UACANet: Uncertainty Aware Context Attention fo

Taehun Kim 85 Dec 14, 2022
Code of Adverse Weather Image Translation with Asymmetric and Uncertainty aware GAN

Adverse Weather Image Translation with Asymmetric and Uncertainty-aware GAN (AU-GAN) Official Tensorflow implementation of Adverse Weather Image Trans

Jeong-gi Kwak 36 Dec 26, 2022
Symmetry and Uncertainty-Aware Object SLAM for 6DoF Object Pose Estimation

SUO-SLAM This repository hosts the code for our CVPR 2022 paper "Symmetry and Uncertainty-Aware Object SLAM for 6DoF Object Pose Estimation". ArXiv li

Robot Perception & Navigation Group (RPNG) 97 Jan 3, 2023
Semi-supervised Semantic Segmentation with Directional Context-aware Consistency (CVPR 2021)

Semi-supervised Semantic Segmentation with Directional Context-aware Consistency (CAC) Xin Lai*, Zhuotao Tian*, Li Jiang, Shu Liu, Hengshuang Zhao, Li

Jia Research Lab 137 Dec 14, 2022
Semi-supervised Semantic Segmentation with Directional Context-aware Consistency (CVPR 2021)

Semi-supervised Semantic Segmentation with Directional Context-aware Consistency (CAC) Xin Lai*, Zhuotao Tian*, Li Jiang, Shu Liu, Hengshuang Zhao, Li

DV Lab 137 Dec 14, 2022
Self-Supervised Monocular 3D Face Reconstruction by Occlusion-Aware Multi-view Geometry Consistency[ECCV 2020]

Self-Supervised Monocular 3D Face Reconstruction by Occlusion-Aware Multi-view Geometry Consistency(ECCV 2020) This is an official python implementati

null 304 Jan 3, 2023