Views
No views yet


1import torch
2cross_entropy_loss = torch.nn.CrossEntropyLoss()
3
4# Input: f_q (BxCxS) and sampled features from H(G_enc(x))
5# Input: f_k (BxCxS) are sampled features from H(G_enc(G(x))
6# Input: tau is the temperature used in PatchNCE loss.
7# Output: PatchNCE loss
8def PatchNCELoss(f_q, f_k, tau=0.07):
9 # batch size, channel size, and number of sample locations
10 B, C, S = f_q.shape
11
12 # calculate v * v+: BxSx1
13 l_pos = (f_k * f_q).sum(dim=1)[:, :, None]
14
15 # calculate v * v-: BxSxS
16 l_neg = torch.bmm(f_q.transpose(1, 2), f_k)
17
18 # The diagonal entries are not negatives. Remove them.
19 identity_matrix = torch.eye(S)[None, :, :]
20 l_neg.masked_fill_(identity_matrix, -float('inf'))
21
22 # calculate logits: (B)x(S)x(S+1)
23 logits = torch.cat((l_pos, l_neg), dim=2) / tau
24
25 # return PatchNCE loss
26 predictions = logits.flatten(0, 1)
27 targets = torch.zeros(B * S, dtype=torch.long)
28 return cross_entropy_loss(predictions, targets)



1git clone https://github.com/taesungp/contrastive-unpaired-translation CUT
2cd CUTpip install -r requirements.txt.conda env create -f environment.yml.grumpifycat dataset (Fig 8 of the paper. Russian Blue -> Grumpy Cats)bash ./datasets/download_cut_dataset.sh grumpifycat./datasets/grumpifycat/.python -m visdom.server and click the URL http://localhost:8097.python train.py --dataroot ./datasets/grumpifycat --name grumpycat_CUT --CUT_mode CUTpython train.py --dataroot ./datasets/grumpifycat --name grumpycat_FastCUT --CUT_mode FastCUT./checkpoints/grumpycat_*/web.python test.py --dataroot ./datasets/grumpifycat --name grumpycat_CUT --CUT_mode CUT --phase train./results/grumpifycat/latest_train/index.html.
lambda_NCE=1, while FastCUT is trained without the identity loss but with higher lambda_NCE=10.0. Compared to CycleGAN, CUT learns to perform more powerful distribution matching, while FastCUT is designed as a lighter (half the GPU memory, can fit a larger image), and faster (twice faster to train) alternative to CycleGAN. Please refer to the paper for more details.experiments/grumpifycat_launcher.py that generates the above command line arguments. The launcher scripts are useful for configuring rather complicated command-line arguments of training and testing.1python -m experiments grumpifycat train 0 # CUT
2python -m experiments grumpifycat train 1 # FastCUT1python -m experiments grumpifycat test 0 # CUT
2python -m experiments grumpifycat test 1 # FastCUTexperiments/__main__.py for all commands. Launcher is easy and quick to define and use. For example, the grumpifycat launcher is defined in a few lines:1from .tmux_launcher import Options, TmuxLauncher
2
3
4class Launcher(TmuxLauncher):
5 def common_options(self):
6 return [
7 Options( # Command 0
8 dataroot="./datasets/grumpifycat",
9 name="grumpifycat_CUT",
10 CUT_mode="CUT"
11 ),
12
13 Options( # Command 1
14 dataroot="./datasets/grumpifycat",
15 name="grumpifycat_FastCUT",
16 CUT_mode="FastCUT",
17 )
18 ]
19
20 def commands(self):
21 return ["python train.py " + str(opt) for opt in self.common_options()]
22
23 def test_commands(self):
24 # Russian Blue -> Grumpy Cats dataset does not have test split.
25 # Therefore, let's set the test split to be the "train" set.
26 return ["python test.py " + str(opt.set(phase='train')) for opt in self.common_options()]
271
2# Download and unzip the pretrained models. The weights should be located at
3# checkpoints/horse2zebra_cut_pretrained/latest_net_G.pth, for example.
4wget http://efrosgans.eecs.berkeley.edu/CUT/pretrained_models.tar
5tar -xf pretrained_models.tar
6
7# Generate outputs. The dataset paths might need to be adjusted.
8# To do this, modify the lines of experiments/pretrained_launcher.py
9# [id] corresponds to the respective commands defined in pretrained_launcher.py
10# 0 - CUT on Cityscapes
11# 1 - FastCUT on Cityscapes
12# 2 - CUT on Horse2Zebra
13# 3 - FastCUT on Horse2Zebra
14# 4 - CUT on Cat2Dog
15# 5 - FastCUT on Cat2Dog
16python -m experiments pretrained run_test [id]
17
18# Evaluate FID. To do this, first install pytorch-fid of https://github.com/mseitzer/pytorch-fid
19# pip install pytorch-fid
20# For example, to evaluate horse2zebra FID of CUT,
21# python -m pytorch_fid ./datasets/horse2zebra/testB/ results/horse2zebra_cut_pretrained/test_latest/images/fake_B/
22# To evaluate Cityscapes FID of FastCUT,
23# python -m pytorch_fid ./datasets/cityscapes/valA/ ~/projects/contrastive-unpaired-translation/results/cityscapes_fastcut_pretrained/test_latest/images/fake_B/
24# Note that a special dataset needs to be used for the Cityscapes model. Please read below.
25python -m pytorch_fid [path to real test images] [path to generated images]
26--model option as --model sincut, which invokes the configuration and codes at ./models/sincut_model.py, and./datasets/single_image_monet_etretat/.python train.py --model sincut --name singleimage_monet_etretat --dataroot ./datasets/single_image_monet_etretatpython -m experiments singleimage run 0models/stylegan_networks.py.python test.py --model sincut --name singleimage_monet_etretat --dataroot ./datasets/single_image_monet_etretatpython -m experiments singleimage run_test 0bash datasets/download_cut_datasets.sh horse2zebrabash download.sh afhq-dataset of the github repo. Then reorganize directories as follows.1mkdir datasets/cat2dog
2ln -s datasets/cat2dog/trainA [path_to_afhq]/train/cat
3ln -s datasets/cat2dog/trainB [path_to_afhq]/train/dog
4ln -s datasets/cat2dog/testA [path_to_afhq]/test/cat
5ln -s datasets/cat2dog/testB [path_to_afhq]/test/dog./datasets/prepare_cityscapes_dataset.py to prepare the dataset.--preprocess, --load_size, and --crop_size. The usage follows the CycleGAN/pix2pix repo.--preprocess resize_and_crop --load_size 286 --crop_size 256 resizes the input image to 286x286, and then makes a random crop of size 256x256 as a way to perform data augmentation. There are other preprocessing options that can be specified, and they are specified in base_dataset.py. Below are some example options.--preprocess none: does not perform any preprocessing. Note that the image size is still scaled to be a closest multiple of 4, because the convolutional generator cannot maintain the same image size otherwise.--preprocess scale_width --load_size 768: scales the width of the image to be of size 768.--preprocess scale_shortside_and_crop: scales the image preserving aspect ratio so that the short side is load_size, and then performs random cropping of window size crop_size.get_transform() of base_dataset.py.@inproceedings{park2020cut,
title={Contrastive Learning for Unpaired Image-to-Image Translation},
author={Taesung Park and Alexei A. Efros and Richard Zhang and Jun-Yan Zhu},
booktitle={European Conference on Computer Vision},
year={2020}
}@inproceedings{CycleGAN2017,
title={Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks},
author={Zhu, Jun-Yan and Park, Taesung and Isola, Phillip and Efros, Alexei A},
booktitle={IEEE International Conference on Computer Vision (ICCV)},
year={2017}
}
@inproceedings{isola2017image,
title={Image-to-Image Translation with Conditional Adversarial Networks},
author={Isola, Phillip and Zhu, Jun-Yan and Zhou, Tinghui and Efros, Alexei A},
booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
year={2017}
}