[
  {
    "path": ".gitignore",
    "content": ".DS_Store\ndebug*\ndatasets/\ncheckpoints/\nresults/\nbuild/\ndist/\n*.png\ntorch.egg-info/\n*/**/__pycache__\ntorch/version.py\ntorch/csrc/generic/TensorMethods.cpp\ntorch/lib/*.so*\ntorch/lib/*.dylib*\ntorch/lib/*.h\ntorch/lib/build\ntorch/lib/tmp_install\ntorch/lib/include\ntorch/lib/torch_shm_manager\ntorch/csrc/cudnn/cuDNN.cpp\ntorch/csrc/nn/THNN.cwrap\ntorch/csrc/nn/THNN.cpp\ntorch/csrc/nn/THCUNN.cwrap\ntorch/csrc/nn/THCUNN.cpp\ntorch/csrc/nn/THNN_generic.cwrap\ntorch/csrc/nn/THNN_generic.cpp\ntorch/csrc/nn/THNN_generic.h\ndocs/src/**/*\ntest/data/legacy_modules.t7\ntest/data/gpu_tensors.pt\ntest/htmlcov\ntest/.coverage\n*/*.pyc\n*/**/*.pyc\n*/**/**/*.pyc\n*/**/**/**/*.pyc\n*/**/**/**/**/*.pyc\n*/*.so*\n*/**/*.so*\n*/**/*.dylib*\ntest/data/legacy_serialized.pt\n*~\n.idea\n\n#Ignore Wandb\nwandb/\n"
  },
  {
    "path": ".replit",
    "content": "language = \"python3\"\nrun = \"<p><a href=\\\"https://github.com/affinelayer/pix2pix-tensorflow\\\"> [Tensorflow]</a> (by Christopher Hesse), <a href=\\\"https://github.com/Eyyub/tensorflow-pix2pix\\\">[Tensorflow]</a> (by Eyyüb Sariu), <a href=\\\"https://github.com/datitran/face2face-demo\\\"> [Tensorflow (face2face)]</a> (by Dat Tran), <a href=\\\"https://github.com/awjuliani/Pix2Pix-Film\\\"> [Tensorflow (film)]</a> (by Arthur Juliani), <a href=\\\"https://github.com/kaonashi-tyc/zi2zi\\\">[Tensorflow (zi2zi)]</a> (by Yuchen Tian), <a href=\\\"https://github.com/pfnet-research/chainer-pix2pix\\\">[Chainer]</a> (by mattya), <a href=\\\"https://github.com/tjwei/GANotebooks\\\">[tf/torch/keras/lasagne]</a> (by tjwei), <a href=\\\"https://github.com/taey16/pix2pixBEGAN.pytorch\\\">[Pytorch]</a> (by taey16) </p> </ul>\""
  },
  {
    "path": "CycleGAN.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"view-in-github\"\n   },\n   \"source\": [\n    \"<a href=\\\"https://colab.research.google.com/github/bkkaggle/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"5VIGyIus8Vr7\"\n   },\n   \"source\": [\n    \"Take a look at the [repository](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) for more information\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"7wNjDKdQy35h\"\n   },\n   \"source\": [\n    \"# Install\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"TRm-USlsHgEV\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"Pt3igws3eiVp\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import os\\n\",\n    \"os.chdir('pytorch-CycleGAN-and-pix2pix/')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"z1EySlOXwwoa\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!pip install -r requirements.txt\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"8daqlgVhw29P\"\n   },\n   \"source\": [\n    \"# Datasets\\n\",\n    \"\\n\",\n    \"Download one of the official datasets with:\\n\",\n    \"\\n\",\n    \"-   `bash ./datasets/download_cyclegan_dataset.sh [apple2orange, summer2winter_yosemite, horse2zebra, monet2photo, cezanne2photo, ukiyoe2photo, vangogh2photo, maps, cityscapes, facades, iphone2dslr_flower, ae_photos]`\\n\",\n    \"\\n\",\n    \"Or use your own dataset by creating the appropriate folders and adding in the images.\\n\",\n    \"\\n\",\n    \"-   Create a dataset folder under `/dataset` for your dataset.\\n\",\n    \"-   Create subfolders `testA`, `testB`, `trainA`, and `trainB` under your dataset's folder. Place any images you want to transform from a to b (cat2dog) in the `testA` folder, images you want to transform from b to a (dog2cat) in the `testB` folder, and do the same for the `trainA` and `trainB` folders.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"vrdOettJxaCc\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!bash ./datasets/download_cyclegan_dataset.sh horse2zebra\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"gdUz4116xhpm\"\n   },\n   \"source\": [\n    \"# Pretrained models\\n\",\n    \"\\n\",\n    \"Download one of the official pretrained models with:\\n\",\n    \"\\n\",\n    \"-   `bash ./scripts/download_cyclegan_model.sh [apple2orange, orange2apple, summer2winter_yosemite, winter2summer_yosemite, horse2zebra, zebra2horse, monet2photo, style_monet, style_cezanne, style_ukiyoe, style_vangogh, sat2map, map2sat, cityscapes_photo2label, cityscapes_label2photo, facades_photo2label, facades_label2photo, iphone2dslr_flower]`\\n\",\n    \"\\n\",\n    \"Or add your own pretrained model to `./checkpoints/{NAME}_pretrained/latest_net_G.pt`\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"B75UqtKhxznS\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!bash ./scripts/download_cyclegan_model.sh horse2zebra\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"yFw1kDQBx3LN\"\n   },\n   \"source\": [\n    \"# Training\\n\",\n    \"\\n\",\n    \"-   `python train.py --dataroot ./datasets/horse2zebra --name horse2zebra --model cycle_gan`\\n\",\n    \"\\n\",\n    \"Change the `--dataroot` and `--name` to your own dataset's path and model's name. Use `--gpu_ids 0,1,..` to train on multiple GPUs and `--batch_size` to change the batch size. I've found that a batch size of 16 fits onto 4 V100s and can finish training an epoch in ~90s.\\n\",\n    \"\\n\",\n    \"Once your model has trained, copy over the last checkpoint to a format that the testing model can automatically detect:\\n\",\n    \"\\n\",\n    \"Use `cp ./checkpoints/horse2zebra/latest_net_G_A.pth ./checkpoints/horse2zebra/latest_net_G.pth` if you want to transform images from class A to class B and `cp ./checkpoints/horse2zebra/latest_net_G_B.pth ./checkpoints/horse2zebra/latest_net_G.pth` if you want to transform images from class B to class A.\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"0sp7TCT2x9dB\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!python train.py --dataroot ./datasets/horse2zebra --name horse2zebra --model cycle_gan --display_id -1\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"9UkcaFZiyASl\"\n   },\n   \"source\": [\n    \"# Testing\\n\",\n    \"\\n\",\n    \"-   `python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout`\\n\",\n    \"\\n\",\n    \"Change the `--dataroot` and `--name` to be consistent with your trained model's configuration.\\n\",\n    \"\\n\",\n    \"> from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix:\\n\",\n    \"> The option --model test is used for generating results of CycleGAN only for one side. This option will automatically set --dataset_mode single, which only loads the images from one set. On the contrary, using --model cycle_gan requires loading and generating results in both directions, which is sometimes unnecessary. The results will be saved at ./results/. Use --results_dir {directory_path_to_save_result} to specify the results directory.\\n\",\n    \"\\n\",\n    \"> For your own experiments, you might want to specify --netG, --norm, --no_dropout to match the generator architecture of the trained model.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"uCsKkEq0yGh0\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"OzSKIPUByfiN\"\n   },\n   \"source\": [\n    \"# Visualize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"9Mgg8raPyizq\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import matplotlib.pyplot as plt\\n\",\n    \"\\n\",\n    \"img = plt.imread('./results/horse2zebra_pretrained/test_latest/images/n02381460_1010_fake.png')\\n\",\n    \"plt.imshow(img)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"0G3oVH9DyqLQ\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import matplotlib.pyplot as plt\\n\",\n    \"\\n\",\n    \"img = plt.imread('./results/horse2zebra_pretrained/test_latest/images/n02381460_1010_real.png')\\n\",\n    \"plt.imshow(img)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"accelerator\": \"GPU\",\n  \"colab\": {\n   \"collapsed_sections\": [],\n   \"include_colab_link\": true,\n   \"name\": \"CycleGAN\",\n   \"provenance\": []\n  },\n  \"environment\": {\n   \"name\": \"tf2-gpu.2-3.m74\",\n   \"type\": \"gcloud\",\n   \"uri\": \"gcr.io/deeplearning-platform-release/tf2-gpu.2-3:m74\"\n  },\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.7.10\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2017, Jun-Yan Zhu and Taesung Park\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n--------------------------- LICENSE FOR pix2pix --------------------------------\nBSD License\n\nFor pix2pix software\nCopyright (c) 2016, Phillip Isola and Jun-Yan Zhu\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n----------------------------- LICENSE FOR DCGAN --------------------------------\nBSD License\n\nFor dcgan.torch software\n\nCopyright (c) 2015, Facebook, Inc. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nNeither the name Facebook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "README.md",
    "content": "<img src='imgs/horse2zebra.gif' align=\"right\" width=384>\n\n<br><br><br>\n\n# CycleGAN and pix2pix in PyTorch\n\n**Udpate in 2025**: we recently updated the code to support Python 3.11 and PyTorch 2.4. It also supports DDP for single-machine multiple-GPU training. (Please use `torchrun --nproc_per_node=4 train.py ...`)\n\n**New**: Please check out [img2img-turbo](https://github.com/GaParmar/img2img-turbo) repo that includes both pix2pix-turbo and CycleGAN-Turbo. Our new one-step image-to-image translation methods can support both paired and unpaired training and produce better results by leveraging the pre-trained StableDiffusion-Turbo model. The inference time for 512x512 image is 0.29 sec on A6000 and 0.11 sec on A100.\n\nPlease check out [contrastive-unpaired-translation](https://github.com/taesungp/contrastive-unpaired-translation) (CUT), our new unpaired image-to-image translation model that enables fast and memory-efficient training.\n\nWe provide PyTorch implementations for both unpaired and paired image-to-image translation.\n\nThe code was written by [Jun-Yan Zhu](https://github.com/junyanz) and [Taesung Park](https://github.com/taesungp), and supported by [Tongzhou Wang](https://github.com/SsnL).\n\nThis PyTorch implementation produces results comparable to or better than our original Torch software. If you would like to reproduce the same results as in the papers, check out the original [CycleGAN Torch](https://github.com/junyanz/CycleGAN) and [pix2pix Torch](https://github.com/phillipi/pix2pix) code in Lua/Torch.\n\n**Note**: The current software works well with PyTorch 2.4+. Check out the older [branch](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/tree/pytorch0.3.1) that supports PyTorch 0.1-0.3.\n\nYou may find useful information in [training/test tips](docs/tips.md) and [frequently asked questions](docs/qa.md). To implement custom models and datasets, check out our [templates](#custom-model-and-dataset). To help users better understand and adapt our codebase, we provide an [overview](docs/overview.md) of the code structure of this repository.\n\n**CycleGAN: [Project](https://junyanz.github.io/CycleGAN/) | [Paper](https://arxiv.org/pdf/1703.10593.pdf) | [Torch](https://github.com/junyanz/CycleGAN) |\n[Tensorflow Core Tutorial](https://www.tensorflow.org/tutorials/generative/cyclegan) | [PyTorch Colab](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb)**\n\n<img src=\"https://junyanz.github.io/CycleGAN/images/teaser_high_res.jpg\" width=\"800\"/>\n\n**Pix2pix: [Project](https://phillipi.github.io/pix2pix/) | [Paper](https://arxiv.org/pdf/1611.07004.pdf) | [Torch](https://github.com/phillipi/pix2pix) |\n[Tensorflow Core Tutorial](https://www.tensorflow.org/tutorials/generative/pix2pix) | [PyTorch Colab](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb)**\n\n<img src=\"https://phillipi.github.io/pix2pix/images/teaser_v3.png\" width=\"800px\"/>\n\n**[EdgesCats Demo](https://affinelayer.com/pixsrv/) | [pix2pix-tensorflow](https://github.com/affinelayer/pix2pix-tensorflow) | by [Christopher Hesse](https://twitter.com/christophrhesse)**\n\n<img src='imgs/edges2cats.jpg' width=\"400px\"/>\n\nIf you use this code for your research, please cite:\n\nUnpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks.<br>\n[Jun-Yan Zhu](https://www.cs.cmu.edu/~junyanz/)\\*, [Taesung Park](https://taesung.me/)\\*, [Phillip Isola](https://people.eecs.berkeley.edu/~isola/), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros). In ICCV 2017. (\\* equal contributions) [[Bibtex]](https://junyanz.github.io/CycleGAN/CycleGAN.txt)\n\nImage-to-Image Translation with Conditional Adversarial Networks.<br>\n[Phillip Isola](https://people.eecs.berkeley.edu/~isola), [Jun-Yan Zhu](https://www.cs.cmu.edu/~junyanz/), [Tinghui Zhou](https://people.eecs.berkeley.edu/~tinghuiz), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros). In CVPR 2017. [[Bibtex]](https://www.cs.cmu.edu/~junyanz/projects/pix2pix/pix2pix.bib)\n\n## Talks and Course\n\npix2pix slides: [keynote](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/pix2pix.key) | [pdf](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/pix2pix.pdf),\nCycleGAN slides: [pptx](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/CycleGAN.pptx) | [pdf](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/CycleGAN.pdf)\n\nCycleGAN course assignment [code](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-code.zip) and [handout](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-handout.pdf) designed by Prof. [Roger Grosse](http://www.cs.toronto.edu/~rgrosse/) for [CSC321](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/) \"Intro to Neural Networks and Machine Learning\" at University of Toronto. Please contact the instructor if you would like to adopt it in your course.\n\n## Colab Notebook\n\nTensorFlow Core CycleGAN Tutorial: [Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/cyclegan.ipynb) | [Code](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/cyclegan.ipynb)\n\nTensorFlow Core pix2pix Tutorial: [Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/pix2pix.ipynb) | [Code](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/pix2pix.ipynb)\n\nPyTorch Colab notebook: [CycleGAN](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb) and [pix2pix](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb)\n\nZeroCostDL4Mic Colab notebook: [CycleGAN](https://colab.research.google.com/github/HenriquesLab/ZeroCostDL4Mic/blob/master/Colab_notebooks_Beta/CycleGAN_ZeroCostDL4Mic.ipynb) and [pix2pix](https://colab.research.google.com/github/HenriquesLab/ZeroCostDL4Mic/blob/master/Colab_notebooks_Beta/pix2pix_ZeroCostDL4Mic.ipynb)\n\n## Other implementations\n\n### CycleGAN\n\n<p><a href=\"https://github.com/leehomyc/cyclegan-1\"> [Tensorflow]</a> (by Harry Yang),\n<a href=\"https://github.com/architrathore/CycleGAN/\">[Tensorflow]</a> (by Archit Rathore),\n<a href=\"https://github.com/vanhuyz/CycleGAN-TensorFlow\">[Tensorflow]</a> (by Van Huy),\n<a href=\"https://github.com/XHUJOY/CycleGAN-tensorflow\">[Tensorflow]</a> (by Xiaowei Hu),\n<a href=\"https://github.com/LynnHo/CycleGAN-Tensorflow-2\"> [Tensorflow2]</a> (by Zhenliang He),\n<a href=\"https://github.com/luoxier/CycleGAN_Tensorlayer\"> [TensorLayer1.0]</a> (by luoxier),\n<a href=\"https://github.com/tensorlayer/cyclegan\"> [TensorLayer2.0]</a> (by zsdonghao),\n<a href=\"https://github.com/Aixile/chainer-cyclegan\">[Chainer]</a> (by Yanghua Jin),\n<a href=\"https://github.com/yunjey/mnist-svhn-transfer\">[Minimal PyTorch]</a> (by yunjey),\n<a href=\"https://github.com/Ldpe2G/DeepLearningForFun/tree/master/Mxnet-Scala/CycleGAN\">[Mxnet]</a> (by Ldpe2G),\n<a href=\"https://github.com/tjwei/GANotebooks\">[lasagne/Keras]</a> (by tjwei),\n<a href=\"https://github.com/simontomaskarlsson/CycleGAN-Keras\">[Keras]</a> (by Simon Karlsson),\n<a href=\"https://github.com/Ldpe2G/DeepLearningForFun/tree/master/Oneflow-Python/CycleGAN\">[OneFlow]</a> (by Ldpe2G)\n</p>\n</ul>\n\n### pix2pix\n\n<p><a href=\"https://github.com/affinelayer/pix2pix-tensorflow\"> [Tensorflow]</a> (by Christopher Hesse),\n<a href=\"https://github.com/Eyyub/tensorflow-pix2pix\">[Tensorflow]</a> (by Eyyüb Sariu),\n<a href=\"https://github.com/datitran/face2face-demo\"> [Tensorflow (face2face)]</a> (by Dat Tran),\n<a href=\"https://github.com/awjuliani/Pix2Pix-Film\"> [Tensorflow (film)]</a> (by Arthur Juliani),\n<a href=\"https://github.com/kaonashi-tyc/zi2zi\">[Tensorflow (zi2zi)]</a> (by Yuchen Tian),\n<a href=\"https://github.com/pfnet-research/chainer-pix2pix\">[Chainer]</a> (by mattya),\n<a href=\"https://github.com/tjwei/GANotebooks\">[tf/torch/keras/lasagne]</a> (by tjwei),\n<a href=\"https://github.com/taey16/pix2pixBEGAN.pytorch\">[Pytorch]</a> (by taey16)\n</p>\n</ul>\n\n## Prerequisites\n\n- Linux or macOS\n- Python 3\n- CPU or NVIDIA GPU + CUDA CuDNN\n\n## Getting Started\n\n### Installation\n\n- Clone this repo:\n\n```bash\ngit clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\ncd pytorch-CycleGAN-and-pix2pix\n```\n\n- Install [PyTorch](http://pytorch.org) and other dependencies. For Conda users, you can create a new Conda environment by\n\n```bash\nconda env create -f environment.yml\n```\n\nand then activate the environment by\n\n```bash\nconda activate pytorch-img2img\n```\n\n- For Docker users, we provide the pre-built Docker image and Dockerfile. Please refer to our [Docker](docs/docker.md) page.\n- For Repl users, please click [![Run on Repl.it](https://repl.it/badge/github/junyanz/pytorch-CycleGAN-and-pix2pix)](https://repl.it/github/junyanz/pytorch-CycleGAN-and-pix2pix).\n\n### CycleGAN train/test\n\n- Download a CycleGAN dataset (e.g. maps):\n\n```bash\nbash ./datasets/download_cyclegan_dataset.sh maps\n```\n\n- To log training progress and test images to W&B dashboard, set the `--use_wandb` flag with training script\n- Train a model:\n\n```bash\n#!./scripts/train_cyclegan.sh\npython train.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan --use_wandb\n```\n\nTo see more intermediate results, check out `./checkpoints/maps_cyclegan/web/index.html`.\n\n- Test the model:\n\n```bash\n#!./scripts/test_cyclegan.sh\npython test.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan\n```\n\n- The test results will be saved to a html file here: `./results/maps_cyclegan/latest_test/index.html`.\n\n### pix2pix train/test\n\n- Download a pix2pix dataset (e.g.[facades](http://cmp.felk.cvut.cz/~tylecr1/facade/)):\n\n```bash\nbash ./datasets/download_pix2pix_dataset.sh facades\n```\n\n- To log training progress and test images to W&B dashboard, set the `--use_wandb` flag with training script\n- Train a model:\n\n```bash\n#!./scripts/train_pix2pix.sh\npython train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA  --use_wandb\n```\n\nTo see more intermediate results, check out `./checkpoints/facades_pix2pix/web/index.html`.\n\n- Test the model (`bash ./scripts/test_pix2pix.sh`):\n\n```bash\n#!./scripts/test_pix2pix.sh\npython test.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA\n```\n\n- The test results will be saved to a html file here: `./results/facades_pix2pix/test_latest/index.html`. You can find more scripts at `scripts` directory.\n- To train and test pix2pix-based colorization models, please add `--model colorization` and `--dataset_mode colorization`. See our training [tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#notes-on-colorization) for more details.\n\n### Apply a pre-trained model (CycleGAN)\n\n- You can download a pretrained model (e.g. horse2zebra) with the following script:\n\n```bash\nbash ./scripts/download_cyclegan_model.sh horse2zebra\n```\n\n- The pretrained model is saved at `./checkpoints/{name}_pretrained/latest_net_G.pth`. Check [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/scripts/download_cyclegan_model.sh#L3) for all the available CycleGAN models.\n- To test the model, you also need to download the horse2zebra dataset:\n\n```bash\nbash ./datasets/download_cyclegan_dataset.sh horse2zebra\n```\n\n- Then generate the results using\n\n```bash\npython test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout\n```\n\n- The option `--model test` is used for generating results of CycleGAN only for one side. This option will automatically set `--dataset_mode single`, which only loads the images from one set. On the contrary, using `--model cycle_gan` requires loading and generating results in both directions, which is sometimes unnecessary. The results will be saved at `./results/`. Use `--results_dir {directory_path_to_save_result}` to specify the results directory.\n\n- For pix2pix and your own models, you need to explicitly specify `--netG`, `--norm`, `--no_dropout` to match the generator architecture of the trained model. See this [FAQ](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md#runtimeerror-errors-in-loading-state_dict-812-671461-296) for more details.\n\n### Apply a pre-trained model (pix2pix)\n\nDownload a pre-trained model with `./scripts/download_pix2pix_model.sh`.\n\n- Check [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/scripts/download_pix2pix_model.sh#L3) for all the available pix2pix models. For example, if you would like to download label2photo model on the Facades dataset,\n\n```bash\nbash ./scripts/download_pix2pix_model.sh facades_label2photo\n```\n\n- Download the pix2pix facades datasets:\n\n```bash\nbash ./datasets/download_pix2pix_dataset.sh facades\n```\n\n- Then generate the results using\n\n```bash\npython test.py --dataroot ./datasets/facades/ --direction BtoA --model pix2pix --name facades_label2photo_pretrained\n```\n\n- Note that we specified `--direction BtoA` as Facades dataset's A to B direction is photos to labels.\n\n- If you would like to apply a pre-trained model to a collection of input images (rather than image pairs), please use `--model test` option. See `./scripts/test_single.sh` for how to apply a model to Facade label maps (stored in the directory `facades/testB`).\n\n- See a list of currently available models at `./scripts/download_pix2pix_model.sh`\n\n### Multi-GPU training\n\nTo train a model on multiple GPUs, please use `torchrun --nproc_per_node=4 train.py ...` instead of `python train.py ...`. We also need to use synchronized batchnorm by setting `--norm sync_batch` (or `--norm sync_instance` for instance normgalization). The `--norm batch` is not compatible with DDP.\n\n## [Docker](docs/docker.md)\n\nWe provide the pre-built Docker image and Dockerfile that can run this code repo. See [docker](docs/docker.md).\n\n## [Datasets](docs/datasets.md)\n\nDownload pix2pix/CycleGAN datasets and create your own datasets.\n\n## [Training/Test Tips](docs/tips.md)\n\nBest practice for training and testing your models.\n\n## [Frequently Asked Questions](docs/qa.md)\n\nBefore you post a new question, please first look at the above Q & A and existing GitHub issues.\n\n## Custom Model and Dataset\n\nIf you plan to implement custom models and dataset for your new applications, we provide a dataset [template](data/template_dataset.py) and a model [template](models/template_model.py) as a starting point.\n\n## [Code structure](docs/overview.md)\n\nTo help users better understand and use our code, we briefly overview the functionality and implementation of each package and each module.\n\n## Pull Request\n\nYou are always welcome to contribute to this repository by sending a [pull request](https://help.github.com/articles/about-pull-requests/).\nPlease run `flake8 --ignore E501 .` and `pytest scripts/test_before_push.py -v` before you commit the code. Please also update the code structure [overview](docs/overview.md) accordingly if you add or remove files.\n\n## Citation\n\nIf you use this code for your research, please cite our papers.\n\n```\n@inproceedings{CycleGAN2017,\n  title={Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks},\n  author={Zhu, Jun-Yan and Park, Taesung and Isola, Phillip and Efros, Alexei A},\n  booktitle={Computer Vision (ICCV), 2017 IEEE International Conference on},\n  year={2017}\n}\n\n\n@inproceedings{isola2017image,\n  title={Image-to-Image Translation with Conditional Adversarial Networks},\n  author={Isola, Phillip and Zhu, Jun-Yan and Zhou, Tinghui and Efros, Alexei A},\n  booktitle={Computer Vision and Pattern Recognition (CVPR), 2017 IEEE Conference on},\n  year={2017}\n}\n```\n\n## Other Languages\n\n[Spanish](docs/README_es.md)\n\n## Related Projects\n\n[img2img-turbo](https://github.com/GaParmar/img2img-turbo)<br>\n[contrastive-unpaired-translation](https://github.com/taesungp/contrastive-unpaired-translation) (CUT)<br>\n[CycleGAN-Torch](https://github.com/junyanz/CycleGAN) |\n[pix2pix-Torch](https://github.com/phillipi/pix2pix) | [pix2pixHD](https://github.com/NVIDIA/pix2pixHD)|\n[BicycleGAN](https://github.com/junyanz/BicycleGAN) | [vid2vid](https://tcwang0509.github.io/vid2vid/) | [SPADE/GauGAN](https://github.com/NVlabs/SPADE)<br>\n[iGAN](https://github.com/junyanz/iGAN) | [GAN Dissection](https://github.com/CSAILVision/GANDissect) | [GAN Paint](http://ganpaint.io/)\n\n## Cat Paper Collection\n\nIf you love cats, and love reading cool graphics, vision, and learning papers, please check out the Cat Paper [Collection](https://github.com/junyanz/CatPapers).\n\n## Acknowledgments\n\nOur code is inspired by [pytorch-DCGAN](https://github.com/pytorch/examples/tree/master/dcgan).\n"
  },
  {
    "path": "data/__init__.py",
    "content": "\"\"\"This package includes all the modules related to data loading and preprocessing\n\n To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset.\n You need to implement four functions:\n    -- <__init__>:                      initialize the class, first call BaseDataset.__init__(self, opt).\n    -- <__len__>:                       return the size of dataset.\n    -- <__getitem__>:                   get a data point from data loader.\n    -- <modify_commandline_options>:    (optionally) add dataset-specific options and set default options.\n\nNow you can use the dataset class by specifying flag '--dataset_mode dummy'.\nSee our template dataset class 'template_dataset.py' for more details.\n\"\"\"\n\nimport importlib\nimport torch.utils.data\nfrom torch.utils.data.distributed import DistributedSampler\nimport torch.distributed as dist\nimport os\nfrom data.base_dataset import BaseDataset\n\n\ndef find_dataset_using_name(dataset_name):\n    \"\"\"Import the module \"data/[dataset_name]_dataset.py\".\n\n    In the file, the class called DatasetNameDataset() will\n    be instantiated. It has to be a subclass of BaseDataset,\n    and it is case-insensitive.\n    \"\"\"\n    dataset_filename = \"data.\" + dataset_name + \"_dataset\"\n    datasetlib = importlib.import_module(dataset_filename)\n\n    dataset = None\n    target_dataset_name = dataset_name.replace(\"_\", \"\") + \"dataset\"\n    for name, cls in datasetlib.__dict__.items():\n        if name.lower() == target_dataset_name.lower() and issubclass(cls, BaseDataset):\n            dataset = cls\n\n    if dataset is None:\n        raise NotImplementedError(\"In %s.py, there should be a subclass of BaseDataset with class name that matches %s in lowercase.\" % (dataset_filename, target_dataset_name))\n\n    return dataset\n\n\ndef get_option_setter(dataset_name):\n    \"\"\"Return the static method <modify_commandline_options> of the dataset class.\"\"\"\n    dataset_class = find_dataset_using_name(dataset_name)\n    return dataset_class.modify_commandline_options\n\n\ndef create_dataset(opt):\n    \"\"\"Create a dataset given the option.\n\n    This function wraps the class CustomDatasetDataLoader.\n        This is the main interface between this package and 'train.py'/'test.py'\n\n    Example:\n        >>> from data import create_dataset\n        >>> dataset = create_dataset(opt)\n    \"\"\"\n    data_loader = CustomDatasetDataLoader(opt)\n    dataset = data_loader.load_data()\n    return dataset\n\n\nclass CustomDatasetDataLoader:\n    \"\"\"Wrapper class of Dataset class that performs multi-threaded data loading\"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize this class\n\n        Step 1: create a dataset instance given the name [dataset_mode]\n        Step 2: create a multi-threaded data loader.\n        \"\"\"\n        self.opt = opt\n        dataset_class = find_dataset_using_name(opt.dataset_mode)\n        self.dataset = dataset_class(opt)\n        print(\"dataset [%s] was created\" % type(self.dataset).__name__)\n\n        # Use DistributedSampler for DDP training\n        if \"LOCAL_RANK\" in os.environ:\n            print(f'create DDP sampler on rank {int(os.environ[\"LOCAL_RANK\"])}')\n            self.sampler = DistributedSampler(self.dataset, shuffle=not opt.serial_batches)\n            shuffle = False  # DistributedSampler handles shuffling\n        else:\n            self.sampler = None\n            shuffle = not opt.serial_batches\n\n        self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=opt.batch_size, shuffle=shuffle, sampler=self.sampler, num_workers=int(opt.num_threads))\n\n    def load_data(self):\n        return self\n\n    def __len__(self):\n        \"\"\"Return the number of data in the dataset\"\"\"\n        return min(len(self.dataset), self.opt.max_dataset_size)\n\n    def __iter__(self):\n        \"\"\"Return a batch of data\"\"\"\n        for i, data in enumerate(self.dataloader):\n            if i * self.opt.batch_size >= self.opt.max_dataset_size:\n                break\n            yield data\n\n    def set_epoch(self, epoch):\n        \"\"\"Set epoch for DistributedSampler to ensure proper shuffling\"\"\"\n        if self.sampler is not None:\n            self.sampler.set_epoch(epoch)\n"
  },
  {
    "path": "data/aligned_dataset.py",
    "content": "import os\nfrom data.base_dataset import BaseDataset, get_params, get_transform\nfrom data.image_folder import make_dataset\nfrom PIL import Image\n\n\nclass AlignedDataset(BaseDataset):\n    \"\"\"A dataset class for paired image dataset.\n\n    It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}.\n    During test time, you need to prepare a directory '/path/to/data/test'.\n    \"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize this dataset class.\n\n        Parameters:\n            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        BaseDataset.__init__(self, opt)\n        self.dir_AB = os.path.join(opt.dataroot, opt.phase)  # get the image directory\n        self.AB_paths = sorted(make_dataset(self.dir_AB, opt.max_dataset_size))  # get image paths\n        assert self.opt.load_size >= self.opt.crop_size  # crop_size should be smaller than the size of loaded image\n        self.input_nc = self.opt.output_nc if self.opt.direction == \"BtoA\" else self.opt.input_nc\n        self.output_nc = self.opt.input_nc if self.opt.direction == \"BtoA\" else self.opt.output_nc\n\n    def __getitem__(self, index):\n        \"\"\"Return a data point and its metadata information.\n\n        Parameters:\n            index - - a random integer for data indexing\n\n        Returns a dictionary that contains A, B, A_paths and B_paths\n            A (tensor) - - an image in the input domain\n            B (tensor) - - its corresponding image in the target domain\n            A_paths (str) - - image paths\n            B_paths (str) - - image paths (same as A_paths)\n        \"\"\"\n        # read a image given a random integer index\n        AB_path = self.AB_paths[index]\n        AB = Image.open(AB_path).convert(\"RGB\")\n        # split AB image into A and B\n        w, h = AB.size\n        w2 = int(w / 2)\n        A = AB.crop((0, 0, w2, h))\n        B = AB.crop((w2, 0, w, h))\n\n        # apply the same transform to both A and B\n        transform_params = get_params(self.opt, A.size)\n        A_transform = get_transform(self.opt, transform_params, grayscale=(self.input_nc == 1))\n        B_transform = get_transform(self.opt, transform_params, grayscale=(self.output_nc == 1))\n\n        A = A_transform(A)\n        B = B_transform(B)\n\n        return {\"A\": A, \"B\": B, \"A_paths\": AB_path, \"B_paths\": AB_path}\n\n    def __len__(self):\n        \"\"\"Return the total number of images in the dataset.\"\"\"\n        return len(self.AB_paths)\n"
  },
  {
    "path": "data/base_dataset.py",
    "content": "\"\"\"This module implements an abstract base class (ABC) 'BaseDataset' for datasets.\n\nIt also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.\n\"\"\"\n\nimport random\nimport numpy as np\nimport torch.utils.data as data\nfrom PIL import Image\nimport torchvision.transforms as transforms\nfrom abc import ABC, abstractmethod\n\n\nclass BaseDataset(data.Dataset, ABC):\n    \"\"\"This class is an abstract base class (ABC) for datasets.\n\n    To create a subclass, you need to implement the following four functions:\n    -- <__init__>:                      initialize the class, first call BaseDataset.__init__(self, opt).\n    -- <__len__>:                       return the size of dataset.\n    -- <__getitem__>:                   get a data point.\n    -- <modify_commandline_options>:    (optionally) add dataset-specific options and set default options.\n    \"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize the class; save the options in the class\n\n        Parameters:\n            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        self.opt = opt\n        self.root = opt.dataroot\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n        \"\"\"\n        return parser\n\n    @abstractmethod\n    def __len__(self):\n        \"\"\"Return the total number of images in the dataset.\"\"\"\n        return 0\n\n    @abstractmethod\n    def __getitem__(self, index):\n        \"\"\"Return a data point and its metadata information.\n\n        Parameters:\n            index - - a random integer for data indexing\n\n        Returns:\n            a dictionary of data with their names. It ususally contains the data itself and its metadata information.\n        \"\"\"\n        pass\n\n\ndef get_params(opt, size):\n    w, h = size\n    new_h = h\n    new_w = w\n    if opt.preprocess == \"resize_and_crop\":\n        new_h = new_w = opt.load_size\n    elif opt.preprocess == \"scale_width_and_crop\":\n        new_w = opt.load_size\n        new_h = opt.load_size * h // w\n\n    x = random.randint(0, np.maximum(0, new_w - opt.crop_size))\n    y = random.randint(0, np.maximum(0, new_h - opt.crop_size))\n\n    flip = random.random() > 0.5\n\n    return {\"crop_pos\": (x, y), \"flip\": flip}\n\n\ndef get_transform(opt, params=None, grayscale=False, method=transforms.InterpolationMode.BICUBIC, convert=True):\n    transform_list = []\n    if grayscale:\n        transform_list.append(transforms.Grayscale(1))\n    if \"resize\" in opt.preprocess:\n        osize = [opt.load_size, opt.load_size]\n        transform_list.append(transforms.Resize(osize, method))\n    elif \"scale_width\" in opt.preprocess:\n        transform_list.append(transforms.Lambda(lambda img: __scale_width(img, opt.load_size, opt.crop_size, method)))\n\n    if \"crop\" in opt.preprocess:\n        if params is None:\n            transform_list.append(transforms.RandomCrop(opt.crop_size))\n        else:\n            transform_list.append(transforms.Lambda(lambda img: __crop(img, params[\"crop_pos\"], opt.crop_size)))\n\n    if opt.preprocess == \"none\":\n        transform_list.append(transforms.Lambda(lambda img: __make_power_2(img, base=4, method=method)))\n\n    if not opt.no_flip:\n        if params is None:\n            transform_list.append(transforms.RandomHorizontalFlip())\n        elif params[\"flip\"]:\n            transform_list.append(transforms.Lambda(lambda img: __flip(img, params[\"flip\"])))\n\n    if convert:\n        transform_list += [transforms.ToTensor()]\n        if grayscale:\n            transform_list += [transforms.Normalize((0.5,), (0.5,))]\n        else:\n            transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n    return transforms.Compose(transform_list)\n\n\ndef __transforms2pil_resize(method):\n    mapper = {\n        transforms.InterpolationMode.BILINEAR: Image.BILINEAR,\n        transforms.InterpolationMode.BICUBIC: Image.BICUBIC,\n        transforms.InterpolationMode.NEAREST: Image.NEAREST,\n        transforms.InterpolationMode.LANCZOS: Image.LANCZOS,\n    }\n    return mapper[method]\n\n\ndef __make_power_2(img, base, method=transforms.InterpolationMode.BICUBIC):\n    method = __transforms2pil_resize(method)\n    ow, oh = img.size\n    h = int(round(oh / base) * base)\n    w = int(round(ow / base) * base)\n    if h == oh and w == ow:\n        return img\n\n    __print_size_warning(ow, oh, w, h)\n    return img.resize((w, h), method)\n\n\ndef __scale_width(img, target_size, crop_size, method=transforms.InterpolationMode.BICUBIC):\n    method = __transforms2pil_resize(method)\n    ow, oh = img.size\n    if ow == target_size and oh >= crop_size:\n        return img\n    w = target_size\n    h = int(max(target_size * oh / ow, crop_size))\n    return img.resize((w, h), method)\n\n\ndef __crop(img, pos, size):\n    ow, oh = img.size\n    x1, y1 = pos\n    tw = th = size\n    if ow > tw or oh > th:\n        return img.crop((x1, y1, x1 + tw, y1 + th))\n    return img\n\n\ndef __flip(img, flip):\n    if flip:\n        return img.transpose(Image.FLIP_LEFT_RIGHT)\n    return img\n\n\ndef __print_size_warning(ow, oh, w, h):\n    \"\"\"Print warning information about image size(only print once)\"\"\"\n    if not hasattr(__print_size_warning, \"has_printed\"):\n        print(\"The image size needs to be a multiple of 4. \" \"The loaded image size was (%d, %d), so it was adjusted to \" \"(%d, %d). This adjustment will be done to all images \" \"whose sizes are not multiples of 4\" % (ow, oh, w, h))\n        __print_size_warning.has_printed = True\n"
  },
  {
    "path": "data/colorization_dataset.py",
    "content": "import os\nfrom data.base_dataset import BaseDataset, get_transform\nfrom data.image_folder import make_dataset\nfrom skimage import color  # require skimage\nfrom PIL import Image\nimport numpy as np\nimport torchvision.transforms as transforms\n\n\nclass ColorizationDataset(BaseDataset):\n    \"\"\"This dataset class can load a set of natural images in RGB, and convert RGB format into (L, ab) pairs in Lab color space.\n\n    This dataset is required by pix2pix-based colorization model ('--model colorization')\n    \"\"\"\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n\n        By default, the number of channels for input image  is 1 (L) and\n        the number of channels for output image is 2 (ab). The direction is from A to B\n        \"\"\"\n        parser.set_defaults(input_nc=1, output_nc=2, direction=\"AtoB\")\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize this dataset class.\n\n        Parameters:\n            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        BaseDataset.__init__(self, opt)\n        self.dir = os.path.join(opt.dataroot, opt.phase)\n        self.AB_paths = sorted(make_dataset(self.dir, opt.max_dataset_size))\n        assert opt.input_nc == 1 and opt.output_nc == 2 and opt.direction == \"AtoB\"\n        self.transform = get_transform(self.opt, convert=False)\n\n    def __getitem__(self, index):\n        \"\"\"Return a data point and its metadata information.\n\n        Parameters:\n            index - - a random integer for data indexing\n\n        Returns a dictionary that contains A, B, A_paths and B_paths\n            A (tensor) - - the L channel of an image\n            B (tensor) - - the ab channels of the same image\n            A_paths (str) - - image paths\n            B_paths (str) - - image paths (same as A_paths)\n        \"\"\"\n        path = self.AB_paths[index]\n        im = Image.open(path).convert(\"RGB\")\n        im = self.transform(im)\n        im = np.array(im)\n        lab = color.rgb2lab(im).astype(np.float32)\n        lab_t = transforms.ToTensor()(lab)\n        A = lab_t[[0], ...] / 50.0 - 1.0\n        B = lab_t[[1, 2], ...] / 110.0\n        return {\"A\": A, \"B\": B, \"A_paths\": path, \"B_paths\": path}\n\n    def __len__(self):\n        \"\"\"Return the total number of images in the dataset.\"\"\"\n        return len(self.AB_paths)\n"
  },
  {
    "path": "data/image_folder.py",
    "content": "\"\"\"A modified image folder class\n\nWe modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)\nso that this class can load images from both current directory and its subdirectories.\n\"\"\"\n\nimport torch.utils.data as data\nfrom pathlib import Path\nfrom PIL import Image\n\nIMG_EXTENSIONS = [\n    \".jpg\",\n    \".JPG\",\n    \".jpeg\",\n    \".JPEG\",\n    \".png\",\n    \".PNG\",\n    \".ppm\",\n    \".PPM\",\n    \".bmp\",\n    \".BMP\",\n    \".tif\",\n    \".TIF\",\n    \".tiff\",\n    \".TIFF\",\n]\n\n\ndef is_image_file(filename):\n    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndef make_dataset(dir, max_dataset_size=float(\"inf\")):\n    images = []\n    dir_path = Path(dir)\n    assert dir_path.is_dir(), f\"{dir} is not a valid directory\"\n\n    for path in sorted(dir_path.rglob(\"*\")):\n        if path.is_file() and is_image_file(path.name):\n            images.append(str(path))\n    return images[: min(max_dataset_size, len(images))]\n\n\ndef default_loader(path):\n    return Image.open(path).convert(\"RGB\")\n\n\nclass ImageFolder(data.Dataset):\n\n    def __init__(self, root, transform=None, return_paths=False, loader=default_loader):\n        imgs = make_dataset(root)\n        if len(imgs) == 0:\n            raise (RuntimeError(\"Found 0 images in: \" + root + \"\\n\" \"Supported image extensions are: \" + \",\".join(IMG_EXTENSIONS)))\n\n        self.root = root\n        self.imgs = imgs\n        self.transform = transform\n        self.return_paths = return_paths\n        self.loader = loader\n\n    def __getitem__(self, index):\n        path = self.imgs[index]\n        img = self.loader(path)\n        if self.transform is not None:\n            img = self.transform(img)\n        if self.return_paths:\n            return img, path\n        else:\n            return img\n\n    def __len__(self):\n        return len(self.imgs)\n"
  },
  {
    "path": "data/single_dataset.py",
    "content": "from data.base_dataset import BaseDataset, get_transform\nfrom data.image_folder import make_dataset\nfrom PIL import Image\n\n\nclass SingleDataset(BaseDataset):\n    \"\"\"This dataset class can load a set of images specified by the path --dataroot /path/to/data.\n\n    It can be used for generating CycleGAN results only for one side with the model option '-model test'.\n    \"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize this dataset class.\n\n        Parameters:\n            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        BaseDataset.__init__(self, opt)\n        self.A_paths = sorted(make_dataset(opt.dataroot, opt.max_dataset_size))\n        input_nc = self.opt.output_nc if self.opt.direction == \"BtoA\" else self.opt.input_nc\n        self.transform = get_transform(opt, grayscale=(input_nc == 1))\n\n    def __getitem__(self, index):\n        \"\"\"Return a data point and its metadata information.\n\n        Parameters:\n            index - - a random integer for data indexing\n\n        Returns a dictionary that contains A and A_paths\n            A(tensor) - - an image in one domain\n            A_paths(str) - - the path of the image\n        \"\"\"\n        A_path = self.A_paths[index]\n        A_img = Image.open(A_path).convert(\"RGB\")\n        A = self.transform(A_img)\n        return {\"A\": A, \"A_paths\": A_path}\n\n    def __len__(self):\n        \"\"\"Return the total number of images in the dataset.\"\"\"\n        return len(self.A_paths)\n"
  },
  {
    "path": "data/template_dataset.py",
    "content": "\"\"\"Dataset class template\n\nThis module provides a template for users to implement custom datasets.\nYou can specify '--dataset_mode template' to use this dataset.\nThe class name should be consistent with both the filename and its dataset_mode option.\nThe filename should be <dataset_mode>_dataset.py\nThe class name should be <Dataset_mode>Dataset.py\nYou need to implement the following functions:\n    -- <modify_commandline_options>:　Add dataset-specific options and rewrite default values for existing options.\n    -- <__init__>: Initialize this dataset class.\n    -- <__getitem__>: Return a data point and its metadata information.\n    -- <__len__>: Return the number of images.\n\"\"\"\n\nfrom data.base_dataset import BaseDataset, get_transform\n\n# from data.image_folder import make_dataset\n# from PIL import Image\n\n\nclass TemplateDataset(BaseDataset):\n    \"\"\"A template dataset class for you to implement custom datasets.\"\"\"\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n        \"\"\"\n        parser.add_argument(\"--new_dataset_option\", type=float, default=1.0, help=\"new dataset option\")\n        parser.set_defaults(max_dataset_size=10, new_dataset_option=2.0)  # specify dataset-specific default values\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize this dataset class.\n\n        Parameters:\n            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n\n        A few things can be done here.\n        - save the options (have been done in BaseDataset)\n        - get image paths and meta information of the dataset.\n        - define the image transformation.\n        \"\"\"\n        # save the option and dataset root\n        BaseDataset.__init__(self, opt)\n        # get the image paths of your dataset;\n        self.image_paths = []  # You can call sorted(make_dataset(self.root, opt.max_dataset_size)) to get all the image paths under the directory self.root\n        # define the default transform function. You can use <base_dataset.get_transform>; You can also define your custom transform function\n        self.transform = get_transform(opt)\n\n    def __getitem__(self, index):\n        \"\"\"Return a data point and its metadata information.\n\n        Parameters:\n            index -- a random integer for data indexing\n\n        Returns:\n            a dictionary of data with their names. It usually contains the data itself and its metadata information.\n\n        Step 1: get a random image path: e.g., path = self.image_paths[index]\n        Step 2: load your data from the disk: e.g., image = Image.open(path).convert('RGB').\n        Step 3: convert your data to a PyTorch tensor. You can use helpder functions such as self.transform. e.g., data = self.transform(image)\n        Step 4: return a data point as a dictionary.\n        \"\"\"\n        path = \"temp\"  # needs to be a string\n        data_A = None  # needs to be a tensor\n        data_B = None  # needs to be a tensor\n        return {\"data_A\": data_A, \"data_B\": data_B, \"path\": path}\n\n    def __len__(self):\n        \"\"\"Return the total number of images.\"\"\"\n        return len(self.image_paths)\n"
  },
  {
    "path": "data/unaligned_dataset.py",
    "content": "import os\nfrom data.base_dataset import BaseDataset, get_transform\nfrom data.image_folder import make_dataset\nfrom PIL import Image\nimport random\n\n\nclass UnalignedDataset(BaseDataset):\n    \"\"\"\n    This dataset class can load unaligned/unpaired datasets.\n\n    It requires two directories to host training images from domain A '/path/to/data/trainA'\n    and from domain B '/path/to/data/trainB' respectively.\n    You can train the model with the dataset flag '--dataroot /path/to/data'.\n    Similarly, you need to prepare two directories:\n    '/path/to/data/testA' and '/path/to/data/testB' during test time.\n    \"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize this dataset class.\n\n        Parameters:\n            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        BaseDataset.__init__(self, opt)\n        self.dir_A = os.path.join(opt.dataroot, opt.phase + \"A\")  # create a path '/path/to/data/trainA'\n        self.dir_B = os.path.join(opt.dataroot, opt.phase + \"B\")  # create a path '/path/to/data/trainB'\n\n        self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size))  # load images from '/path/to/data/trainA'\n        self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size))  # load images from '/path/to/data/trainB'\n        self.A_size = len(self.A_paths)  # get the size of dataset A\n        self.B_size = len(self.B_paths)  # get the size of dataset B\n        btoA = self.opt.direction == \"BtoA\"\n        input_nc = self.opt.output_nc if btoA else self.opt.input_nc  # get the number of channels of input image\n        output_nc = self.opt.input_nc if btoA else self.opt.output_nc  # get the number of channels of output image\n        self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1))\n        self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1))\n\n    def __getitem__(self, index):\n        \"\"\"Return a data point and its metadata information.\n\n        Parameters:\n            index (int)      -- a random integer for data indexing\n\n        Returns a dictionary that contains A, B, A_paths and B_paths\n            A (tensor)       -- an image in the input domain\n            B (tensor)       -- its corresponding image in the target domain\n            A_paths (str)    -- image paths\n            B_paths (str)    -- image paths\n        \"\"\"\n        A_path = self.A_paths[index % self.A_size]  # make sure index is within then range\n        if self.opt.serial_batches:  # make sure index is within then range\n            index_B = index % self.B_size\n        else:  # randomize the index for domain B to avoid fixed pairs.\n            index_B = random.randint(0, self.B_size - 1)\n        B_path = self.B_paths[index_B]\n        A_img = Image.open(A_path).convert(\"RGB\")\n        B_img = Image.open(B_path).convert(\"RGB\")\n        # apply image transformation\n        A = self.transform_A(A_img)\n        B = self.transform_B(B_img)\n\n        return {\"A\": A, \"B\": B, \"A_paths\": A_path, \"B_paths\": B_path}\n\n    def __len__(self):\n        \"\"\"Return the total number of images in the dataset.\n\n        As we have two datasets with potentially different number of images,\n        we take a maximum of\n        \"\"\"\n        return max(self.A_size, self.B_size)\n"
  },
  {
    "path": "docs/Dockerfile",
    "content": "FROM nvidia/cuda:10.1-base\n\n#Nvidia Public GPG Key\nRUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub\n\nRUN apt update && apt install -y wget unzip curl bzip2 git\nRUN curl -LO http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\nRUN bash Miniconda3-latest-Linux-x86_64.sh -p /miniconda -b\nRUN rm Miniconda3-latest-Linux-x86_64.sh\nENV PATH=/miniconda/bin:${PATH}\nRUN conda update -y conda\n\nRUN conda install -y pytorch torchvision -c pytorch\nRUN mkdir /workspace/ && cd /workspace/ && git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix.git && cd pytorch-CycleGAN-and-pix2pix && pip install -r requirements.txt\n\nWORKDIR /workspace\n"
  },
  {
    "path": "docs/README_es.md",
    "content": "<img src='https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/raw/master/imgs/horse2zebra.gif' align=\"right\" width=384>\n\n<br><br><br>\n\n# CycleGAN y pix2pix en PyTorch\n\nImplementacion en PyTorch de Unpaired Image-to-Image Translation.\n\nEste codigo fue escrito por [Jun-Yan Zhu](https://github.com/junyanz) y [Taesung Park](https://github.com/taesung), y con ayuda de [Tongzhou Wang](https://ssnl.github.io/).\n\nEsta implementacion de PyTorch produce resultados comparables o mejores que nuestros original software de Torch. Si te gustaria producir los mismos resultados que en documento oficial, echa un vistazo al codigo original [CycleGAN Torch](https://github.com/junyanz/CycleGAN) y [pix2pix Torch](https://github.com/phillipi/pix2pix)\n\n**Aviso**: El software actual funciona correctamente en PyTorch 2.4+. Para soporte en PyTorch 0.1-0.3: [branch](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/tree/pytorch0.3.1).\n\nPuede encontrar información útil en [training/test tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md) y [preguntas frecuentes](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md). Para implementar modelos y conjuntos de datos personalizados, consulte nuestro [templates](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/README_es.md#modelo-y-dataset-personalizado). Para ayudar a los usuarios a comprender y adaptar mejor nuestra base de código, proporcionamos un [overview](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/overview.md) de la estructura de código de este repositorio.\n\n**CycleGAN: [Proyecto](https://junyanz.github.io/CycleGAN/) |  [PDF](https://arxiv.org/pdf/1703.10593.pdf) |  [Torch](https://github.com/junyanz/CycleGAN) |\n[Guia de Tensorflow Core](https://www.tensorflow.org/tutorials/generative/cyclegan) | [PyTorch Colab](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb)**\n\n<img src=\"https://junyanz.github.io/CycleGAN/images/teaser_high_res.jpg\" width=\"800\"/>\n\n**Pix2pix:  [Proyeto](https://phillipi.github.io/pix2pix/) |  [PDF](https://arxiv.org/pdf/1611.07004.pdf) |  [Torch](https://github.com/phillipi/pix2pix) |\n[Guia de Tensorflow Core](https://www.tensorflow.org/tutorials/generative/cyclegan) | [PyTorch Colab](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb)**\n\n<img src=\"https://phillipi.github.io/pix2pix/images/teaser_v3.png\" width=\"800px\"/>\n\n\n**[EdgesCats Demo](https://affinelayer.com/pixsrv/) | [pix2pix-tensorflow](https://github.com/affinelayer/pix2pix-tensorflow) | por [Christopher Hesse](https://twitter.com/christophrhesse)**\n\n<img src='https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/imgs/edges2cats.jpg' width=\"400px\"/>\n\nSi usa este código para su investigación, cite:\n\nUnpaired Image-to-Image Translation usando Cycle-Consistent Adversarial Networks.<br>\n[Jun-Yan Zhu](https://www.cs.cmu.edu/~junyanz/)\\*,  [Taesung Park](https://taesung.me/)\\*, [Phillip Isola](https://people.eecs.berkeley.edu/~isola/), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros). In ICCV 2017. (* contribucion igualitaria) [[Bibtex]](https://junyanz.github.io/CycleGAN/CycleGAN.txt)\n\n\nImage-to-Image Translation usando Conditional Adversarial Networks.<br>\n[Phillip Isola](https://people.eecs.berkeley.edu/~isola), [Jun-Yan Zhu](https://www.cs.cmu.edu/~junyanz/), [Tinghui Zhou](https://people.eecs.berkeley.edu/~tinghuiz), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros). In CVPR 2017. [[Bibtex]](https://www.cs.cmu.edu/~junyanz/projects/pix2pix/pix2pix.bib)\n\n## Charlas y curso\nPresentacion en PowerPoint de Pix2pix: [keynote](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/pix2pix.key) | [pdf](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/pix2pix.pdf),\nPresentacion en PowerPoint de CycleGAN: [pptx](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/CycleGAN.pptx) | [pdf](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/CycleGAN.pdf)\n\nAsignación del curso CycleGAN [codigo](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-code.zip) y [handout](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-handout.pdf) diseñado por el Prof. [Roger Grosse](http://www.cs.toronto.edu/~rgrosse/) for [CSC321](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/) \"Intro to Neural Networks and Machine Learning\" en la universidad de Toronto. Póngase en contacto con el instructor si desea adoptarlo en su curso.\n\n## Colab Notebook\nTensorFlow Core CycleGAN Tutorial: [Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/cyclegan.ipynb) | [Codigo](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/cyclegan.ipynb)\n\nGuia de TensorFlow Core pix2pix : [Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/pix2pix.ipynb) | [Codigo](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/pix2pix.ipynb)\n\nPyTorch Colab notebook: [CycleGAN](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb) y [pix2pix](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb)\n\n## Otras implementaciones\n### CycleGAN\n<p><a href=\"https://github.com/leehomyc/cyclegan-1\"> [Tensorflow]</a> (por Harry Yang),\n<a href=\"https://github.com/architrathore/CycleGAN/\">[Tensorflow]</a> (por Archit Rathore),\n<a href=\"https://github.com/vanhuyz/CycleGAN-TensorFlow\">[Tensorflow]</a> (por Van Huy),\n<a href=\"https://github.com/XHUJOY/CycleGAN-tensorflow\">[Tensorflow]</a> (por Xiaowei Hu),\n<a href=\"https://github.com/LynnHo/CycleGAN-Tensorflow-Simple\"> [Tensorflow-simple]</a> (por Zhenliang He),\n<a href=\"https://github.com/luoxier/CycleGAN_Tensorlayer\"> [TensorLayer]</a> (por luoxier),\n<a href=\"https://github.com/Aixile/chainer-cyclegan\">[Chainer]</a> (por Yanghua Jin),\n<a href=\"https://github.com/yunjey/mnist-svhn-transfer\">[Minimal PyTorch]</a> (por yunjey),\n<a href=\"https://github.com/Ldpe2G/DeepLearningForFun/tree/master/Mxnet-Scala/CycleGAN\">[Mxnet]</a> (por Ldpe2G),\n<a href=\"https://github.com/tjwei/GANotebooks\">[lasagne/Keras]</a> (por tjwei),\n<a href=\"https://github.com/simontomaskarlsson/CycleGAN-Keras\">[Keras]</a> (por Simon Karlsson)\n</p>\n</ul>\n\n### pix2pix\n<p><a href=\"https://github.com/affinelayer/pix2pix-tensorflow\"> [Tensorflow]</a> (por Christopher Hesse),\n<a href=\"https://github.com/Eyyub/tensorflow-pix2pix\">[Tensorflow]</a> (por Eyyüb Sariu),\n<a href=\"https://github.com/datitran/face2face-demo\"> [Tensorflow (face2face)]</a> (por Dat Tran),\n<a href=\"https://github.com/awjuliani/Pix2Pix-Film\"> [Tensorflow (film)]</a> (por Arthur Juliani),\n<a href=\"https://github.com/kaonashi-tyc/zi2zi\">[Tensorflow (zi2zi)]</a> (por Yuchen Tian),\n<a href=\"https://github.com/pfnet-research/chainer-pix2pix\">[Chainer]</a> (por mattya),\n<a href=\"https://github.com/tjwei/GANotebooks\">[tf/torch/keras/lasagne]</a> (por tjwei),\n<a href=\"https://github.com/taey16/pix2pixBEGAN.pytorch\">[Pytorch]</a> (por taey16)\n</p>\n</ul>\n\n## Requerimientos\n- Linux o macOS\n- Python 3\n- CPU o NVIDIA GPU usando CUDA CuDNN\n\n## Inicio\n### Instalación\n\n- Clone este repositorio:\n```bash\ngit clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\ncd pytorch-CycleGAN-and-pix2pix\n```\n\n- Instale [PyTorch](http://pytorch.org) 0.4+ y sus otras dependencias (e.g., torchvision, [visdom](https://github.com/facebookresearch/visdom) y [dominate](https://github.com/Knio/dominate)).\n  - Para uso de pip, por favor escriba el comando `pip install -r requirements.txt`.\n  - Para uso de Conda, proporcionamos un script de instalación `./scripts/conda_deps.sh`. De forma alterna, puede crear un nuevo entorno Conda usando `conda env create -f environment.yml`.\n  - Para uso de Docker, Proporcionamos la imagen Docker y el archivo Docker preconstruidos. Por favor, consulte nuestra página\n [Docker](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/docker.md).\n\n### CycleGAN entreanimiento/test\n- Descargar el dataset de CycleGAN (e.g. maps):\n```bash\nbash ./datasets/download_cyclegan_dataset.sh maps\n```\n- Para ver los resultados del entrenamiento y las gráficas de pérdidas, `python -m visdom.server` y haga clic en la URL\n http://localhost:8097.\n- Entrenar el modelo:\n```bash\n#!./scripts/train_cyclegan.sh\npython train.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan\n```\nPara ver más resultados intermedios, consulte `./checkpoints/maps_cyclegan/web/index.html`.\n- Pruebe el modelo:\n```bash\n#!./scripts/test_cyclegan.sh\npython test.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan\n```\n-Los resultados de la prueba se guardarán en un archivo html aquí: `./results/maps_cyclegan/latest_test/index.html`.\n\n### pix2pix entrenamiento/test\n- Descargue el dataset de pix2pix (e.g.[facades](http://cmp.felk.cvut.cz/~tylecr1/facade/)):\n```bash\nbash ./datasets/download_pix2pix_dataset.sh facades\n```\n- Para ver los resultados del entrenamiento y las gráficas de pérdidas `python -m visdom.server`, haga clic en la URL http://localhost:8097.\n- Para entrenar el modelo:\n```bash\n#!./scripts/train_pix2pix.sh\npython train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA\n```\nPara ver más resultados intermedios, consulte `./checkpoints/facades_pix2pix/web/index.html`.\n\n- Pruebe el modelo (`bash ./scripts/test_pix2pix.sh`):\n```bash\n#!./scripts/test_pix2pix.sh\npython test.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA\n```\n- Los resultados de la prueba se guardarán en un archivo html aquí: `./results/facades_pix2pix/test_latest/index.html`. Puede encontrar más scripts en `scripts` directory.\n- Para entrenar y probar modelos de colorización basados en pix2pix, agregue la linea `--model colorization` y `--dataset_mode colorization`. Para más detalles de nuestro entrenamiento [tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#notes-on-colorization).\n\n### Aplicar un modelo pre-entrenado (CycleGAN)\n- Puedes descargar un modelo previamente entrenado (e.g. horse2zebra) con el siguiente script:\n```bash\nbash ./scripts/download_cyclegan_model.sh horse2zebra\n```\n- El modelo pre-entrenado se guarda en `./checkpoints/{name}_pretrained/latest_net_G.pth`. Revise [aqui](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/scripts/download_cyclegan_model.sh#L3) para todos los modelos CycleGAN disponibles.\n\n- Para probar el modelo, también debe descargar el dataset horse2zebra:\n```bash\nbash ./datasets/download_cyclegan_dataset.sh horse2zebra\n```\n\n- Luego genere los resultados usando:\n```bash\npython test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout\n```\n- La opcion `--model test` ise usa para generar resultados de CycleGAN de un solo lado. Esta opción configurará automáticamente\n `--dataset_mode single`, carga solo las imágenes de un conjunto. Por el contrario, el uso de `--model cycle_gan` requiere cargar y generar resultados en ambas direcciones, lo que a veces es innecesario. Los resultados se guardarán en `./results/`. Use `--results_dir {directory_path_to_save_result}` para especificar el directorio de resultados.\n\n- Para sus propios experimentos, es posible que desee especificar `--netG`, `--norm`, `--no_dropout` para que coincida con la arquitectura del generador del modelo entrenado.\n\n### Aplicar un modelo pre-entrenado (pix2pix)\nDescargue un modelo pre-entrenado con `./scripts/download_pix2pix_model.sh`.\n\n- Revise [aqui](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/scripts/download_pix2pix_model.sh#L3) para todos los modelos pix2pix disponibles. Por ejemplo, si desea descargar el modelo label2photo en el dataset:\n```bash\nbash ./scripts/download_pix2pix_model.sh facades_label2photo\n```\n- Descarga el dataset facades de pix2pix:\n```bash\nbash ./datasets/download_pix2pix_dataset.sh facades\n```\n- Luego genere los resultados usando:\n```bash\npython test.py --dataroot ./datasets/facades/ --direction BtoA --model pix2pix --name facades_label2photo_pretrained\n```\n- Tenga en cuenta que `--direction BtoA` como Facades dataset's, son direcciones A o B para etiquetado de fotos.\n\n- Si desea aplicar un modelo previamente entrenado a una colección de imágenes de entrada (en lugar de pares de imágenes), use la opcion `--model test`. Vea `./scripts/test_single.sh` obre cómo aplicar un modelo a Facade label maps (almacenados en el directorio `facades/testB`).\n\n- Vea una lista de los modelos disponibles actualmente en `./scripts/download_pix2pix_model.sh`\n\n## [Docker](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/docker.md)\nProporcionamos la imagen Docker y el archivo Docker preconstruidos que pueden ejecutar este repositorio de código. Ver [docker](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/docker.md).\n\n## [Datasets](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/datasets.md)\nDescargue los conjuntos de datos pix2pix / CycleGAN y cree sus propios conjuntos de datos.\n\n## [Entretanimiento/Test Tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md)\nLas mejores prácticas para entrenar y probar sus modelos.\n\n## [Preguntas frecuentes](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md)\nAntes de publicar una nueva pregunta, primero mire las preguntas y respuestas anteriores y los problemas existentes de GitHub.\n\n## Modelo y Dataset personalizado\nSi planea implementar modelos y conjuntos de datos personalizados para sus nuevas aplicaciones, proporcionamos un conjunto de datos [template](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/template_dataset.py) y un modelo [template](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/template_model.py) como punto de partida.\n\n\n## [Estructura de codigo](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/overview.md)\nPara ayudar a los usuarios a comprender mejor y usar nuestro código, presentamos brevemente la funcionalidad e implementación de cada paquete y cada módulo.\n\n## Solicitud de Pull\nSiempre puede contribuir a este repositorio enviando un [pull request](https://help.github.com/articles/about-pull-requests/).\nPor favor ejecute `flake8 --ignore E501 .` y `python ./scripts/test_before_push.py` antes de realizar un Pull en el código, asegure de también actualizar la estructura del código [overview](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/overview.md) en consecuencia si agrega o elimina archivos.\n\n\n## Citación\nSi utiliza este código para su investigación, cite nuestros documentos.\n```\n@inproceedings{CycleGAN2017,\n  title={Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networkss},\n  author={Zhu, Jun-Yan and Park, Taesung and Isola, Phillip and Efros, Alexei A},\n  booktitle={Computer Vision (ICCV), 2017 IEEE International Conference on},\n  year={2017}\n}\n\n\n@inproceedings{isola2017image,\n  title={Image-to-Image Translation with Conditional Adversarial Networks},\n  author={Isola, Phillip and Zhu, Jun-Yan and Zhou, Tinghui and Efros, Alexei A},\n  booktitle={Computer Vision and Pattern Recognition (CVPR), 2017 IEEE Conference on},\n  year={2017}\n}\n```\n\n## Proyectos relacionados\n**[CycleGAN-Torch](https://github.com/junyanz/CycleGAN) |\n[pix2pix-Torch](https://github.com/phillipi/pix2pix) | [pix2pixHD](https://github.com/NVIDIA/pix2pixHD)|\n[BicycleGAN](https://github.com/junyanz/BicycleGAN) | [vid2vid](https://tcwang0509.github.io/vid2vid/) | [SPADE/GauGAN](https://github.com/NVlabs/SPADE)**<br>\n**[iGAN](https://github.com/junyanz/iGAN) | [GAN Dissection](https://github.com/CSAILVision/GANDissect) | [GAN Paint](http://ganpaint.io/)**\n\n## Cat Paper Collection\nSi amas a los gatos y te encanta leer gráficos geniales, computer vision y documentos de aprendizaje, echa un vistazo a Cat Paper [Collection](https://github.com/junyanz/CatPapers).\n\n## Agradecimientos\nNuestro código fue inspirado en [pytorch-DCGAN](https://github.com/pytorch/examples/tree/master/dcgan).\n"
  },
  {
    "path": "docs/datasets.md",
    "content": "\n\n### CycleGAN Datasets\nDownload the CycleGAN datasets using the following script. Some of the datasets are collected by other researchers. Please cite their papers if you use the data.\n```bash\nbash ./datasets/download_cyclegan_dataset.sh dataset_name\n```\n- `facades`: 400 images from the [CMP Facades dataset](http://cmp.felk.cvut.cz/~tylecr1/facade). [[Citation](../datasets/bibtex/facades.tex)]\n- `cityscapes`: 2975 images from the [Cityscapes training set](https://www.cityscapes-dataset.com). [[Citation](../datasets/bibtex/cityscapes.tex)]. Note: Due to license issue, we cannot directly provide the Cityscapes dataset. Please download the Cityscapes dataset from [https://cityscapes-dataset.com](https://cityscapes-dataset.com)  and use the script `./datasets/prepare_cityscapes_dataset.py`.\n- `maps`: 1096 training images scraped from Google Maps.\n- `horse2zebra`: 939 horse images and 1177 zebra images downloaded from [ImageNet](http://www.image-net.org) using keywords `wild horse` and `zebra`\n- `apple2orange`: 996 apple images and 1020 orange images downloaded from [ImageNet](http://www.image-net.org) using keywords `apple` and `navel orange`.\n- `summer2winter_yosemite`: 1273 summer Yosemite images and 854 winter Yosemite images were downloaded using Flickr API. See more details in our paper.\n- `monet2photo`, `vangogh2photo`, `ukiyoe2photo`, `cezanne2photo`: The art images were downloaded from [Wikiart](https://www.wikiart.org/). The real photos are downloaded from Flickr using the combination of the tags *landscape* and *landscapephotography*. The training set size of each class is Monet:1074, Cezanne:584, Van Gogh:401, Ukiyo-e:1433, Photographs:6853.\n- `iphone2dslr_flower`: both classes of images were downlaoded from Flickr. The training set size of each class is iPhone:1813, DSLR:3316. See more details in our paper.\n\nTo train a model on your own datasets, you need to create a data folder with two subdirectories `trainA` and `trainB` that contain images from domain A and B. You can test your model on your training set by setting `--phase train` in `test.py`. You can also create subdirectories `testA` and `testB` if you have test data.\n\nYou should **not** expect our method to work on just any random combination of input and output datasets (e.g. `cats<->keyboards`). From our experiments, we find it works better if two datasets share similar visual content. For example, `landscape painting<->landscape photographs` works much better than `portrait painting <-> landscape photographs`. `zebras<->horses` achieves compelling results while `cats<->dogs` completely fails.\n\n### pix2pix datasets\nDownload the pix2pix datasets using the following script. Some of the datasets are collected by other researchers. Please cite their papers if you use the data.\n```bash\nbash ./datasets/download_pix2pix_dataset.sh dataset_name\n```\n- `facades`: 400 images from [CMP Facades dataset](http://cmp.felk.cvut.cz/~tylecr1/facade). [[Citation](../datasets/bibtex/facades.tex)]\n- `cityscapes`: 2975 images from the [Cityscapes training set](https://www.cityscapes-dataset.com). [[Citation](../datasets/bibtex/cityscapes.tex)]\n- `maps`: 1096 training images scraped from Google Maps\n- `edges2shoes`: 50k training images from [UT Zappos50K dataset](http://vision.cs.utexas.edu/projects/finegrained/utzap50k). Edges are computed by [HED](https://github.com/s9xie/hed) edge detector + post-processing. [[Citation](datasets/bibtex/shoes.tex)]\n- `edges2handbags`: 137K Amazon Handbag images from [iGAN project](https://github.com/junyanz/iGAN). Edges are computed by [HED](https://github.com/s9xie/hed) edge detector + post-processing. [[Citation](datasets/bibtex/handbags.tex)]\n- `night2day`: around 20K natural scene images from  [Transient Attributes dataset](http://transattr.cs.brown.edu/) [[Citation](datasets/bibtex/transattr.tex)]. To train a `day2night` pix2pix model, you need to add `--direction BtoA`.\n\nWe provide a python script to generate pix2pix training data in the form of pairs of images {A,B}, where A and B are two different depictions of the same underlying scene. For example, these might be pairs {label map, photo} or {bw image, color image}. Then we can learn to translate A to B or B to A:\n\nCreate folder `/path/to/data` with subfolders `A` and `B`. `A` and `B` should each have their own subfolders `train`, `val`, `test`, etc. In `/path/to/data/A/train`, put training images in style A. In `/path/to/data/B/train`, put the corresponding images in style B. Repeat same for other data splits (`val`, `test`, etc).\n\nCorresponding images in a pair {A,B} must be the same size and have the same filename, e.g., `/path/to/data/A/train/1.jpg` is considered to correspond to `/path/to/data/B/train/1.jpg`.\n\nOnce the data is formatted this way, call:\n```bash\npython datasets/combine_A_and_B.py --fold_A /path/to/data/A --fold_B /path/to/data/B --fold_AB /path/to/data\n```\n\nThis will combine each pair of images (A,B) into a single image file, ready for training.\n"
  },
  {
    "path": "docs/docker.md",
    "content": "# Docker image with pytorch-CycleGAN-and-pix2pix\n\nWe provide both Dockerfile and pre-built Docker container that can run this code repo.\n\n## Prerequisite\n\n- Install [docker-ce](https://docs.docker.com/install/linux/docker-ce/ubuntu/)\n- Install [nvidia-docker](https://github.com/NVIDIA/nvidia-docker#quickstart)\n\n## Running pre-built Dockerfile\n\n- Pull the pre-built docker file\n\n```bash\ndocker pull taesungp/pytorch-cyclegan-and-pix2pix\n```\n\n- Start an interactive docker session. `-p 8097:8097` option is needed if you want to run `visdom` server on the Docker container.\n\n```bash\nnvidia-docker run -it -p 8097:8097  taesungp/pytorch-cyclegan-and-pix2pix\n```\n\n- Now you are in the Docker environment. Go to our code repo and start running things.\n```bash\ncd /workspace/pytorch-CycleGAN-and-pix2pix\nbash datasets/download_pix2pix_dataset.sh facades\npython -m visdom.server &\nbash scripts/train_pix2pix.sh\n```\n\n## Running with Dockerfile\n\nWe also posted the [Dockerfile](Dockerfile). To generate the pre-built file, download the Dockerfile in this directory and run\n```bash\ndocker build -t [target_tag] .\n```\nin the directory that contains the Dockerfile.\n"
  },
  {
    "path": "docs/overview.md",
    "content": "## Overview of Code Structure\nTo help users better understand and use our codebase, we briefly overview the functionality and implementation of each package and each module. Please see the documentation in each file for more details. If you have questions, you may find useful information in [training/test tips](tips.md) and [frequently asked questions](qa.md).\n\n[train.py](../train.py) is a general-purpose training script. It works for various models (with option `--model`: e.g., `pix2pix`, `cyclegan`, `colorization`) and different datasets (with option `--dataset_mode`: e.g., `aligned`, `unaligned`, `single`, `colorization`). See the main [README](.../README.md) and [training/test  tips](tips.md) for more details.\n\n[test.py](../test.py) is a general-purpose test script. Once you have trained your model with `train.py`, you can use this script to test the model. It will load a saved model from `--checkpoints_dir` and save the results to `--results_dir`. See the main [README](.../README.md) and [training/test tips](tips.md) for more details.\n\n\n[data](../data) directory contains all the modules related to data loading and preprocessing. To add a custom dataset class called `dummy`, you need to add a file called `dummy_dataset.py` and define a subclass `DummyDataset` inherited from `BaseDataset`. You need to implement four functions: `__init__` (initialize the class, you need to first call `BaseDataset.__init__(self, opt)`), `__len__` (return the size of dataset), `__getitem__`　(get a data point), and optionally `modify_commandline_options` (add dataset-specific options and set default options). Now you can use the dataset class by specifying flag `--dataset_mode dummy`. See our template dataset [class](../data/template_dataset.py) for an example.   Below we explain each file in details.\n\n* [\\_\\_init\\_\\_.py](../data/__init__.py) implements the interface between this package and training and test scripts. `train.py` and `test.py` call `from data import create_dataset` and `dataset = create_dataset(opt)` to create a dataset given the option `opt`.\n* [base_dataset.py](../data/base_dataset.py) implements an abstract base class ([ABC](https://docs.python.org/3/library/abc.html)) for datasets. It also includes common transformation functions (e.g., `get_transform`, `__scale_width`), which can be later used in subclasses.\n* [image_folder.py](../data/image_folder.py) implements an image folder class. We modify the official PyTorch image folder [code](https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py) so that this class can load images from both the current directory and its subdirectories.\n* [template_dataset.py](../data/template_dataset.py) provides a dataset template with detailed documentation. Check out this file if you plan to implement your own dataset.\n* [aligned_dataset.py](../data/aligned_dataset.py) includes a dataset class that can load image pairs. It assumes a single image directory `/path/to/data/train`, which contains image pairs in the form of {A,B}. See [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#prepare-your-own-datasets-for-pix2pix) on how to prepare aligned datasets. During test time, you need to prepare a directory `/path/to/data/test` as test data.\n* [unaligned_dataset.py](../data/unaligned_dataset.py) includes a dataset class that can load unaligned/unpaired datasets. It assumes that two directories to host training images from domain A `/path/to/data/trainA` and from domain B `/path/to/data/trainB` respectively. Then you can train the model with the dataset flag `--dataroot /path/to/data`. Similarly, you need to prepare two directories `/path/to/data/testA` and `/path/to/data/testB` during test time.\n* [single_dataset.py](../data/single_dataset.py) includes a dataset class that can load a set of single images specified by the path `--dataroot /path/to/data`. It can be used for generating CycleGAN results only for one side with the model option `-model test`.\n* [colorization_dataset.py](../data/colorization_dataset.py) implements a dataset class that can load a set of nature images in RGB, and convert RGB format into (L, ab) pairs in [Lab](https://en.wikipedia.org/wiki/CIELAB_color_space) color space. It is required by pix2pix-based colorization model (`--model colorization`).\n\n\n[models](../models) directory contains modules related to objective functions, optimizations, and network architectures. To add a custom model class called `dummy`, you need to add a file called `dummy_model.py` and define a subclass `DummyModel` inherited from `BaseModel`. You need to implement four functions: `__init__` (initialize the class; you need to first call `BaseModel.__init__(self, opt)`), `set_input` (unpack data from dataset and apply preprocessing), `forward` (generate intermediate results), `optimize_parameters` (calculate loss, gradients, and update network weights), and optionally `modify_commandline_options` (add model-specific options and set default options). Now you can use the model class by specifying flag `--model dummy`. See our template model [class](../models/template_model.py) for an example.  Below we explain each file in details.\n\n* [\\_\\_init\\_\\_.py](../models/__init__.py)  implements the interface between this package and training and test scripts.  `train.py` and `test.py` call `from models import create_model` and `model = create_model(opt)` to create a model given the option `opt`. You also need to call `model.setup(opt)` to properly initialize the model.\n* [base_model.py](../models/base_model.py) implements an abstract base class ([ABC](https://docs.python.org/3/library/abc.html)) for models. It also includes commonly used helper functions (e.g., `setup`, `test`, `update_learning_rate`, `save_networks`, `load_networks`), which can be later used in subclasses.\n* [template_model.py](../models/template_model.py) provides a model template with detailed documentation. Check out this file if you plan to implement your own model.\n* [pix2pix_model.py](../models/pix2pix_model.py) implements the pix2pix [model](https://phillipi.github.io/pix2pix/), for learning a mapping from input images to output images given paired data. The model training requires `--dataset_mode aligned` dataset. By default, it uses a `--netG unet256` [U-Net](https://arxiv.org/pdf/1505.04597.pdf) generator, a `--netD basic` discriminator (PatchGAN), and  a `--gan_mode vanilla` GAN loss (standard cross-entropy objective).\n* [colorization_model.py](../models/colorization_model.py) implements a subclass of `Pix2PixModel` for image colorization (black & white image to colorful image). The model training requires `-dataset_model colorization` dataset. It trains a pix2pix model, mapping from L channel to ab channels in [Lab](https://en.wikipedia.org/wiki/CIELAB_color_space) color space. By default, the `colorization` dataset will automatically set `--input_nc 1` and `--output_nc 2`.\n* [cycle_gan_model.py](../models/cycle_gan_model.py) implements the CycleGAN [model](https://junyanz.github.io/CycleGAN/), for learning image-to-image translation  without paired data.  The model training requires `--dataset_mode unaligned` dataset. By default, it uses a `--netG resnet_9blocks` ResNet generator, a `--netD basic` discriminator (PatchGAN  introduced by pix2pix), and a least-square GANs [objective](https://arxiv.org/abs/1611.04076) (`--gan_mode lsgan`).\n* [networks.py](../models/networks.py) module implements network architectures (both generators and discriminators), as well as normalization layers, initialization methods, optimization scheduler (i.e., learning rate policy), and GAN objective function (`vanilla`, `lsgan`, `wgangp`).\n* [test_model.py](../models/test_model.py) implements a model that can be used to generate CycleGAN results for only one direction. This model will automatically set `--dataset_mode single`, which only loads the images from one set. See the test [instruction](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix#apply-a-pre-trained-model-cyclegan) for more details.\n\n[options](../options) directory includes our option modules: training options, test options, and basic options (used in both training and test). `TrainOptions` and `TestOptions` are both subclasses of `BaseOptions`. They will reuse the options defined in `BaseOptions`.\n* [\\_\\_init\\_\\_.py](../options/__init__.py)  is required to make Python treat the directory `options` as containing packages,\n* [base_options.py](../options/base_options.py) includes options that are used in both training and test. It also implements a few helper functions such as parsing, printing, and saving the options. It also gathers additional options defined in `modify_commandline_options` functions in both dataset class and model class.\n* [train_options.py](../options/train_options.py) includes options that are only used during training time.\n* [test_options.py](../options/test_options.py) includes options that are only used during test time.\n\n\n[util](../util) directory includes a miscellaneous collection of useful helper functions.\n  * [\\_\\_init\\_\\_.py](../util/__init__.py) is required to make Python treat the directory `util` as containing packages,\n  * [get_data.py](../util/get_data.py) provides a Python script for downloading CycleGAN and pix2pix datasets.  Alternatively, You can also use bash scripts such as [download_pix2pix_model.sh](../scripts/download_pix2pix_model.sh) and [download_cyclegan_model.sh](../scripts/download_cyclegan_model.sh).\n  * [html.py](../util/html.py) implements a module that saves images into a single HTML file.  It consists of functions such as `add_header` (add a text header to the HTML file), `add_images` (add a row of images to the HTML file), `save` (save the HTML to the disk). It is based on Python library `dominate`, a Python library for creating and manipulating HTML documents using a DOM API.\n  * [image_pool.py](../util/image_pool.py) implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. The original idea was discussed in this [paper](http://openaccess.thecvf.com/content_cvpr_2017/papers/Shrivastava_Learning_From_Simulated_CVPR_2017_paper.pdf). The size of the buffer is controlled by the flag `--pool_size`.\n  * [visualizer.py](../util/visualizer.py) includes several functions that can display/save images and print/save logging information. It uses Weights & Biases for logging and a Python library `dominate` (wrapped in `HTML`) for creating HTML files with images.\n  * [util.py](../util/util.py) consists of simple helper functions such as `tensor2im` (convert a tensor array to a numpy image array), `diagnose_network` (calculate and print the mean of average absolute value of gradients), and `mkdirs` (create multiple directories).\n"
  },
  {
    "path": "docs/qa.md",
    "content": "## Frequently Asked Questions\n\nBefore you post a new question, please first look at the following Q & A and existing GitHub issues. You may also want to read [Training/Test tips](tips.md) for more suggestions.\n\n#### Connection Error:HTTPConnectionPool ([#230](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/230), [#24](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/24), [#38](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/38))\n\nSimilar error messages include “Failed to establish a new connection/Connection refused”.\n\nPlease start the visdom server before starting the training:\n\n```bash\npython -m visdom.server\n```\n\nTo install the visdom, you can use the following command:\n\n```bash\npip install visdom\n```\n\nYou can also disable the visdom by setting `--display_id 0`.\n\n#### My PyTorch errors on CUDA related code.\n\nTry to run the following code snippet to make sure that CUDA is working (assuming using PyTorch >= 0.4):\n\n```python\nimport torch\ntorch.cuda.init()\nprint(torch.randn(1, device='cuda'))\n```\n\nIf you met an error, it is likely that your PyTorch build does not work with CUDA, e.g., it is installed from the official MacOS binary, or you have a GPU that is too old and not supported anymore. You may run the the code with CPU using `--gpu_ids -1`.\n\n#### TypeError: Object of type 'Tensor' is not JSON serializable ([#258](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/258))\n\nSimilar errors: AttributeError: module 'torch' has no attribute 'device' ([#314](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/314))\n\nThe current code only works with PyTorch 2.4+. An earlier PyTorch version can often cause the above errors.\n\n#### ValueError: empty range for randrange() ([#390](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/390), [#376](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/376), [#194](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/194))\n\nSimilar error messages include \"ConnectionRefusedError: [Errno 111] Connection refused\"\n\nIt is related to the data augmentation step. It often happens when you use `--preprocess crop`. The program will crop random `crop_size x crop_size` patches out of the input training images. But if some of your image sizes (e.g., `256x384`) are smaller than the `crop_size` (e.g., 512), you will get this error. A simple fix will be to use other data augmentation methods such as `resize_and_crop` or `scale_width_and_crop`. Our program will automatically resize the images according to `load_size` before apply `crop_size x crop_size` cropping. Make sure that `load_size >= crop_size`.\n\n#### Can I continue/resume my training? ([#350](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/350), [#275](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/275), [#234](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/234), [#87](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/87))\n\nYou can use the option `--continue_train`. Also set `--epoch_count` to specify a different starting epoch count. See more discussion in [training/test tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#trainingtest-tips).\n\n#### Why does my training loss not converge? ([#335](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/335), [#164](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/164), [#30](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/30))\n\nMany GAN losses do not converge (exception: WGAN, WGAN-GP, etc. ) due to the nature of minimax optimization. For DCGAN and LSGAN objective, it is quite normal for the G and D losses to go up and down. It should be fine as long as they do not blow up.\n\n#### How can I make it work for my own data (e.g., 16-bit png, tiff, hyperspectral images)? ([#309](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/309), [#320](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/), [#202](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/202))\n\nThe current code only supports RGB and grayscale images. If you would like to train the model on other data types, please follow the following steps:\n\n- change the parameters `--input_nc` and `--output_nc` to the number of channels in your input/output images.\n- Write your own custom data loader (It is easy as long as you know how to load your data with python). If you write a new data loader class, you need to change the flag `--dataset_mode` accordingly. Alternatively, you can modify the existing data loader. For aligned datasets, change this [line](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/aligned_dataset.py#L41); For unaligned datasets, change these two [lines](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/unaligned_dataset.py#L57).\n\n- If you use visdom and HTML to visualize the results, you may also need to change the visualization code.\n\n#### Multi-GPU Training ([#327](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/327), [#292](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/292), [#137](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/137), [#35](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/35))\n\nYou can use Multi-GPU training by setting `--gpu_ids` (e.g., `--gpu_ids 0,1,2,3` for the first four GPUs on your machine.) To fully utilize all the GPUs, you need to increase your batch size. Try `--batch_size 4`, `--batch_size 16`, or even a larger batch_size. Each GPU will process batch_size/#GPUs images. The optimal batch size depends on the number of GPUs you have, GPU memory per GPU, and the resolution of your training images.\n\nWe also recommend that you use the instance normalization for multi-GPU training by setting `--norm instance`. The current batch normalization might not work for multi-GPUs as the batchnorm parameters are not shared across different GPUs. Advanced users can try [synchronized batchnorm](https://github.com/vacancy/Synchronized-BatchNorm-PyTorch).\n\n#### Can I run the model on CPU? ([#310](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/310))\n\nYes, you can set `--gpu_ids -1`. See [training/test tips](tips.md) for more details.\n\n#### Are pre-trained models available? ([#10](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/10))\n\nYes, you can download pretrained models with the bash script `./scripts/download_cyclegan_model.sh`. See [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix#apply-a-pre-trained-model-cyclegan) for more details. We are slowly adding more models to the repo.\n\n#### Out of memory ([#174](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/174))\n\nCycleGAN is more memory-intensive than pix2pix as it requires two generators and two discriminators. If you would like to produce high-resolution images, you can do the following.\n\n- During training, train CycleGAN on cropped images of the training set. Please be careful not to change the aspect ratio or the scale of the original image, as this can lead to the training/test gap. You can usually do this by using `--preprocess crop` option, or `--preprocess scale_width_and_crop`.\n\n- Then at test time, you can load only one generator to produce the results in a single direction. This greatly saves GPU memory as you are not loading the discriminators and the other generator in the opposite direction. You can probably take the whole image as input. You can do this using `--model test --dataroot [path to the directory that contains your test images (e.g., ./datasets/horse2zebra/trainA)] --model_suffix _A --preprocess none`. You can use either `--preprocess none` or `--preprocess scale_width --crop_size [your_desired_image_width]`. Please see the [model_suffix](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/test_model.py#L16) and [preprocess](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/base_dataset.py#L24) for more details.\n\n#### RuntimeError: Error(s) in loading state_dict ([#812](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/812), [#671](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/671),[#461](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/461), [#296](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/296))\n\nIf you get the above errors when loading the generator during test time, you probably have used different network configurations for training and test. There are a few things to check: (1) the network architecture `--netG`: you will get an error if you use `--netG unet256` during training, and use `--netG resnet_6blocks` during test. Make sure that the flag is the same. (2) the normalization parameters `--norm`: we use different default `--norm` parameters for `--model cycle_gan`, `--model pix2pix`, and `--model test`. They might be different from the one you used in your training time. Make sure that you add the `--norm` flag in your test code. (3) If you use dropout during training time, make sure that you use the same Dropout setting in your test. Check the flag `--no_dropout`.\n\nNote that we use different default generators, normalization, and dropout options for different models. The model file can overwrite the default arguments and add new arguments. For example, this [line](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/pix2pix_model.py#L32) adds and changes default arguments for pix2pix. For CycleGAN, the default is `--netG resnet_9blocks --no_dropout --norm instance --dataset_mode unaligned`. For pix2pix, the default is `--netG unet_256 --norm batch --dataset_mode aligned`. For model testing with single direction (`--model test`), the default is `--netG resnet_9blocks --norm instance --dataset_mode single`. To make sure that your training and test follow the same setting, you are encouraged to plicitly specify the `--netG`, `--norm`, `--dataset_mode`, and `--no_dropout` (or not) in your script.\n\n#### NotSupportedError ([#829](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/829))\n\nThe error message states that `slicing multiple dimensions at the same time isn't supported yet proposals (Tensor): boxes to be encoded`. It is not related to our repo. It is often caused by incompatibility between the `torhvision` version and `pytorch` version. You need to re-intall or upgrade your `torchvision` to be compatible with the `pytorch` version.\n\n#### What is the identity loss? ([#322](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/322), [#373](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/373), [#362](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/pull/362))\n\nWe use the identity loss for our photo to painting application. The identity loss can regularize the generator to be close to an identity mapping when fed with real samples from the _target_ domain. If something already looks like from the target domain, you should preserve the image without making additional changes. The generator trained with this loss will often be more conservative for unknown content. Please see more details in Sec 5.2 ''Photo generation from paintings'' and Figure 12 in the CycleGAN [paper](https://arxiv.org/pdf/1703.10593.pdf). The loss was first proposed in Equation 6 of the prior work [[Taigman et al., 2017]](https://arxiv.org/pdf/1611.02200.pdf).\n\n#### The color gets inverted from the beginning of training ([#249](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/249))\n\nThe authors also observe that the generator unnecessarily inverts the color of the input image early in training, and then never learns to undo the inversion. In this case, you can try two things.\n\n- First, try using identity loss `--lambda_identity 1.0` or `--lambda_identity 0.1`. We observe that the identity loss makes the generator to be more conservative and make fewer unnecessary changes. However, because of this, the change may not be as dramatic.\n\n- Second, try smaller variance when initializing weights by changing `--init_gain`. We observe that a smaller variance in weight initialization results in less color inversion.\n\n#### For labels2photo Cityscapes evaluation, why does the pretrained FCN-8s model not work well on the original Cityscapes input images? ([#150](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/150))\n\nThe model was trained on 256x256 images that are resized/upsampled to 1024x2048, so expected input images to the network are very blurry. The purpose of the resizing was to 1) keep the label maps in the original high resolution untouched and 2) avoid the need to change the standard FCN training code for Cityscapes.\n\n#### How do I get the `ground-truth` numbers on the labels2photo Cityscapes evaluation? ([#150](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/150))\n\nYou need to resize the original Cityscapes images to 256x256 before running the evaluation code.\n\n#### What is a good evaluation metric for CycleGAN? ([#730](https://github.com/pulls), [#716](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/716), [#166](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/166))\n\nThe evaluation metric highly depends on your specific task and dataset. There is no single metric that works for all the datasets and tasks.\n\nThere are a few popular choices: (1) we often evaluate CycleGAN on paired datasets (e.g., Cityscapes dataset and the meanIOU metric used in the CycleGAN paper), in which the model was trained without pairs. (2) Many researchers have adopted standard GAN metrics such as FID. Note that FID only evaluates the output images, while it ignores the correspondence between output and input. (3) A user study regarding photorealism might be helpful. Please check out the details of a user study in the CycleGAN paper (Section 5.1.1).\n\nIn summary, how to automatically evaluate the results is an open research problem for GANs research. But for many creative applications, the results are subjective and hard to quantify without humans in the loop.\n\n#### What dose the CycleGAN loss look like if training goes well? ([#1096](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/1096), [#1086](ttps://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/1086), [#288](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/288), [#30](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/30))\n\nTypically, the cycle-consistency loss and identity loss decrease during training, while GAN losses oscillate. To evaluate the quality of your results, you need to adopt additional evaluation metrics to your training and test images. See the Q & A above.\n\n#### Using resize-conv to reduce checkerboard artifacts ([#190](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190), [#64](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/64))\n\nThis Distill [blog](https://distill.pub/2016/deconv-checkerboard/) discussed one of the potential causes of the checkerboard artifacts. You can fix that issue by switching from \"deconvolution\" to nearest-neighbor upsampling, followed by regular convolution. Here is one implementation provided by [@SsnL](https://github.com/SsnL). You can replace the ConvTranspose2d with the following layers.\n\n```python\nnn.Upsample(scale_factor = 2, mode='bilinear'),\nnn.ReflectionPad2d(1),\nnn.Conv2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=1, padding=0),\n```\n\nWe have also noticed that sometimes the checkboard artifacts will go away if you train long enough. Maybe you can try training your model a bit longer.\n\n#### pix2pix/CycleGAN has no random noise z ([#152](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/152))\n\nThe current pix2pix/CycleGAN model does not take z as input. In both pix2pix and CycleGAN, we tried to add z to the generator: e.g., adding z to a latent state, concatenating with a latent state, applying dropout, etc., but often found the output did not vary significantly as a function of z. Conditional GANs do not need noise as long as the input is sufficiently complex so that the input can kind of play the role of noise. Without noise, the mapping is deterministic.\n\nPlease check out the following papers that show ways of getting z to actually have a substantial effect: e.g., [BicycleGAN](https://github.com/junyanz/BicycleGAN), [AugmentedCycleGAN](https://arxiv.org/abs/1802.10151), [MUNIT](https://arxiv.org/abs/1804.04732), [DRIT](https://arxiv.org/pdf/1808.00948.pdf), etc.\n\n#### Experiment details (e.g., BW->color) ([#306](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/306))\n\nYou can find more training details and hyperparameter settings in the appendix of [CycleGAN](https://arxiv.org/abs/1703.10593) and [pix2pix](https://arxiv.org/abs/1611.07004) papers.\n\n#### Results with [Cycada](https://arxiv.org/pdf/1711.03213.pdf)\n\nWe generated the [result of translating GTA images to Cityscapes-style images](https://junyanz.github.io/CycleGAN/) using our Torch repo. Our PyTorch and Torch implementation seemed to produce a little bit different results, although we have not measured the FCN score using the PyTorch-trained model. To reproduce the result of Cycada, please use the Torch repo for now.\n\n#### Loading and using the saved model in your code\n\nYou can easily consume the model in your code using the below code snippet:\n\n```python\nimport torch\nfrom models.networks import define_G\nfrom collections import OrderedDict\n\nmodel_dict = torch.load(\"checkpoints/stars_pix2pix/latest_net_G.pth\")\nnew_dict = OrderedDict()\nfor k, v in model_dict.items():\n    # load_state_dict expects keys with prefix 'module.'\n    new_dict[\"module.\" + k] = v\n\n# make sure you pass the correct parameters to the define_G method\ngenerator_model = define_G(input_nc=1,output_nc=1,ngf=64,netG=\"resnet_9blocks\",\n                            norm=\"batch\",use_dropout=True,init_gain=0.02,gpu_ids=[0])\ngenerator_model.load_state_dict(new_dict)\n```\n\nIf everything goes well you should see a '\\<All keys matched successfully\\>' message.\n"
  },
  {
    "path": "docs/tips.md",
    "content": "## Training/test Tips\n#### Training/test options\nPlease see `options/train_options.py` and `options/base_options.py` for the training flags; see `options/test_options.py` and `options/base_options.py` for the test flags. There are some model-specific flags as well, which are added in the model files, such as `--lambda_A` option in `model/cycle_gan_model.py`. The default values of these options are also adjusted in the model files.\n#### CPU/GPU (default `--gpu_ids 0`)\nPlease set`--gpu_ids -1` to use CPU mode; set `--gpu_ids 0,1,2` for multi-GPU mode. You need a large batch size (e.g., `--batch_size 32`) to benefit from multiple GPUs.\n\n#### Visualization\nDuring training, the current results can be viewed using two methods. First, the intermediate results are saved to `[opt.checkpoints_dir]/[opt.name]/web/` as an HTML file. To avoid this, set `--no_html`. Second, if you set `--use_wandb`, the results and loss plots will appear on your Weights & Biases dashboard.\n\n#### Preprocessing\n Images can be resized and cropped in different ways using `--preprocess` option. The default option `'resize_and_crop'` resizes the image to be of size `(opt.load_size, opt.load_size)` and does a random crop of size `(opt.crop_size, opt.crop_size)`. `'crop'` skips the resizing step and only performs random cropping. `'scale_width'` resizes the image to have width `opt.crop_size` while keeping the aspect ratio. `'scale_width_and_crop'` first resizes the image to have width `opt.load_size` and then does random cropping of size `(opt.crop_size, opt.crop_size)`. `'none'` tries to skip all these preprocessing steps. However, if the image size is not a multiple of some number depending on the number of downsamplings of the generator, you will get an error because the size of the output image may be different from the size of the input image. Therefore, `'none'` option still tries to adjust the image size to be a multiple of 4. You might need a bigger adjustment if you change the generator architecture. Please see `data/base_dataset.py` do see how all these were implemented.\n\n#### Fine-tuning/resume training\nTo fine-tune a pre-trained model, or resume the previous training, use the `--continue_train` flag. The program will then load the model based on `epoch`. By default, the program will initialize the epoch count as 1. Set `--epoch_count <int>` to specify a different starting epoch count.\n\n\n#### Prepare your own datasets for CycleGAN\nYou need to create two directories to host images from domain A `/path/to/data/trainA` and from domain B `/path/to/data/trainB`. Then you can train the model with the dataset flag `--dataroot /path/to/data`. Optionally, you can create hold-out test datasets at `/path/to/data/testA` and `/path/to/data/testB` to test your model on unseen images.\n\n#### Prepare your own datasets for pix2pix\nPix2pix's training requires paired data. We provide a python script to generate training data in the form of pairs of images {A,B}, where A and B are two different depictions of the same underlying scene. For example, these might be pairs {label map, photo} or {bw image, color image}. Then we can learn to translate A to B or B to A:\n\nCreate folder `/path/to/data` with subdirectories `A` and `B`. `A` and `B` should each have their own subdirectories `train`, `val`, `test`, etc. In `/path/to/data/A/train`, put training images in style A. In `/path/to/data/B/train`, put the corresponding images in style B. Repeat same for other data splits (`val`, `test`, etc).\n\nCorresponding images in a pair {A,B} must be the same size and have the same filename, e.g., `/path/to/data/A/train/1.jpg` is considered to correspond to `/path/to/data/B/train/1.jpg`.\n\nOnce the data is formatted this way, call:\n```bash\npython datasets/combine_A_and_B.py --fold_A /path/to/data/A --fold_B /path/to/data/B --fold_AB /path/to/data\n```\n\nThis will combine each pair of images (A,B) into a single image file, ready for training.\n\n\n#### About image size\n Since the generator architecture in CycleGAN involves a series of downsampling / upsampling operations, the size of the input and output image may not match if the input image size is not a multiple of 4. As a result, you may get a runtime error because the L1 identity loss cannot be enforced with images of different size. Therefore, we slightly resize the image to become multiples of 4 even with `--preprocess none` option. For the same reason, `--crop_size` needs to be a multiple of 4.\n\n#### Training/Testing with high res images\nCycleGAN is quite memory-intensive as four networks (two generators and two discriminators) need to be loaded on one GPU, so a large image cannot be entirely loaded. In this case, we recommend training with cropped images. For example, to generate 1024px results, you can train with `--preprocess scale_width_and_crop --load_size 1024 --crop_size 360`, and test with `--preprocess scale_width --load_size 1024`. This way makes sure the training and test will be at the same scale. At test time, you can afford higher resolution because you don’t need to load all networks.\n\n#### Training/Testing with rectangular images\nBoth pix2pix and CycleGAN can work for rectangular images. To make them work, you need to use different preprocessing flags. Let's say that you are working with `360x256` images. During training, you can specify `--preprocess crop` and `--crop_size 256`. This will allow your model to be trained on randomly cropped `256x256` images during training time. During test time, you can apply the model on `360x256` images with the flag `--preprocess none`.\n\nThere are practical restrictions regarding image sizes for each generator architecture. For `unet256`, it only supports images whose width and height are divisible by 256. For `unet128`, the width and height need to be divisible by 128. For `resnet_6blocks` and `resnet_9blocks`, the width and height need to be divisible by 4.\n\n#### About loss curve\nUnfortunately, the loss curve does not reveal much information in training GANs, and CycleGAN is no exception. To check whether the training has converged or not, we recommend periodically generating a few samples and looking at them.\n\n#### About batch size\nFor all experiments in the paper, we set the batch size to be 1. If there is room for memory, you can use higher batch size with batch norm or instance norm. (Note that the default batchnorm does not work well with multi-GPU training. You may consider using [synchronized batchnorm](https://github.com/vacancy/Synchronized-BatchNorm-PyTorch) instead). But please be aware that it can impact the training. In particular, even with Instance Normalization, different batch sizes can lead to different results. Moreover, increasing `--crop_size` may be a good alternative to increasing the batch size.\n\n\n#### Notes on Colorization\nNo need to run `combine_A_and_B.py` for colorization. Instead, you need to prepare natural images and set `--dataset_mode colorization` and `--model colorization` in the script. The program will automatically convert each RGB image into Lab color space, and create  `L -> ab` image pair during the training. Also set `--input_nc 1` and `--output_nc 2`. The training and test directory should be organized as `/your/data/train` and `your/data/test`. See example scripts `scripts/train_colorization.sh` and `scripts/test_colorization` for more details.\n\n#### Notes on Extracting Edges\nWe provide python and Matlab scripts to extract coarse edges from photos. Run `scripts/edges/batch_hed.py` to compute [HED](https://github.com/s9xie/hed) edges. Run `scripts/edges/PostprocessHED.m` to simplify edges with additional post-processing steps. Check the code documentation for more details.\n\n#### Evaluating Labels2Photos on Cityscapes\nWe provide scripts for running the evaluation of the Labels2Photos task on the Cityscapes **validation** set. We assume that you have installed `caffe` (and `pycaffe`) in your system. If not, see the [official website](http://caffe.berkeleyvision.org/installation.html) for installation instructions. Once `caffe` is successfully installed, download the pre-trained FCN-8s semantic segmentation model (512MB) by running\n```bash\nbash ./scripts/eval_cityscapes/download_fcn8s.sh\n```\nThen make sure `./scripts/eval_cityscapes/` is in your system's python path. If not, run the following command to add it\n```bash\nexport PYTHONPATH=${PYTHONPATH}:./scripts/eval_cityscapes/\n```\nNow you can run the following command to evaluate your predictions:\n```bash\npython ./scripts/eval_cityscapes/evaluate.py --cityscapes_dir /path/to/original/cityscapes/dataset/ --result_dir /path/to/your/predictions/ --output_dir /path/to/output/directory/\n```\nImages stored under `--result_dir` should contain your model predictions on the Cityscapes **validation** split, and have the original Cityscapes naming convention (e.g., `frankfurt_000001_038418_leftImg8bit.png`). The script will output a text file under `--output_dir` containing the metric.\n\n**Further notes**: Our pre-trained FCN model is **not** supposed to work on Cityscapes in the original resolution (1024x2048) as it was trained on 256x256 images that are then upsampled to 1024x2048 during training. The purpose of the resizing during training was to 1) keep the label maps in the original high resolution untouched and 2) avoid the need of changing the standard FCN training code and the architecture for Cityscapes. During test time, you need to synthesize 256x256 results. Our test code will automatically upsample your results to 1024x2048 before feeding them to the pre-trained FCN model. The output is at 1024x2048 resolution and will be compared to 1024x2048 ground truth labels. You do not need to resize the ground truth labels. The best way to verify whether everything is correct is to reproduce the numbers for real images in the paper first. To achieve it, you need to resize the original/real Cityscapes images (**not** labels) to 256x256 and feed them to the evaluation code.\n"
  },
  {
    "path": "environment.yml",
    "content": "name: pytorch-img2img\nchannels:\n  - pytorch\n  - conda-forge\n  - nvidia\ndependencies:\n  - python=3.11\n  - pytorch=2.4.0\n  - torchvision=0.19.0\n  - pytorch-cuda=12.1\n  - numpy=1.24.3\n  - scikit-image\n  - pip\n  - pip:\n      - dominate>=2.8.0\n      - Pillow>=10.0.0\n      - wandb>=0.16.0\n"
  },
  {
    "path": "models/__init__.py",
    "content": "\"\"\"This package contains modules related to objective functions, optimizations, and network architectures.\n\nTo add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel.\nYou need to implement the following five functions:\n    -- <__init__>:                      initialize the class; first call BaseModel.__init__(self, opt).\n    -- <set_input>:                     unpack data from dataset and apply preprocessing.\n    -- <forward>:                       produce intermediate results.\n    -- <optimize_parameters>:           calculate loss, gradients, and update network weights.\n    -- <modify_commandline_options>:    (optionally) add model-specific options and set default options.\n\nIn the function <__init__>, you need to define four lists:\n    -- self.loss_names (str list):          specify the training losses that you want to plot and save.\n    -- self.model_names (str list):         define networks used in our training.\n    -- self.visual_names (str list):        specify the images that you want to display and save.\n    -- self.optimizers (optimizer list):    define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an usage.\n\nNow you can use the model class by specifying flag '--model dummy'.\nSee our template model class 'template_model.py' for more details.\n\"\"\"\n\nimport importlib\nfrom models.base_model import BaseModel\n\n\ndef find_model_using_name(model_name: str):\n    \"\"\"Import the module \"models/[model_name]_model.py\".\n\n    In the file, the class called DatasetNameModel() will\n    be instantiated. It has to be a subclass of BaseModel,\n    and it is case-insensitive.\n    \"\"\"\n    model_filename = \"models.\" + model_name + \"_model\"\n    modellib = importlib.import_module(model_filename)\n    model = None\n    target_model_name = model_name.replace(\"_\", \"\") + \"model\"\n    for name, cls in modellib.__dict__.items():\n        if name.lower() == target_model_name.lower() and issubclass(cls, BaseModel):\n            model = cls\n\n    if model is None:\n        print(\"In %s.py, there should be a subclass of BaseModel with class name that matches %s in lowercase.\" % (model_filename, target_model_name))\n        exit(0)\n\n    return model\n\n\ndef get_option_setter(model_name: str):\n    \"\"\"Return the static method <modify_commandline_options> of the model class.\"\"\"\n    model_class = find_model_using_name(model_name)\n    return model_class.modify_commandline_options\n\n\ndef create_model(opt):\n    \"\"\"Create a model given the option.\"\"\"\n    model = find_model_using_name(opt.model)\n    instance = model(opt)\n    print(f\"model [{type(instance).__name__}] was created\")\n    return instance\n"
  },
  {
    "path": "models/base_model.py",
    "content": "import os\nimport torch\nimport torch.distributed as dist\nfrom pathlib import Path\nfrom collections import OrderedDict\nfrom abc import ABC, abstractmethod\nfrom . import networks\n\n\nclass BaseModel(ABC):\n    \"\"\"This class is an abstract base class (ABC) for models.\n    To create a subclass, you need to implement the following five functions:\n        -- <__init__>:                      initialize the class; first call BaseModel.__init__(self, opt).\n        -- <set_input>:                     unpack data from dataset and apply preprocessing.\n        -- <forward>:                       produce intermediate results.\n        -- <optimize_parameters>:           calculate losses, gradients, and update network weights.\n        -- <modify_commandline_options>:    (optionally) add model-specific options and set default options.\n    \"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize the BaseModel class.\n\n        Parameters:\n            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n\n        When creating your custom class, you need to implement your own initialization.\n        In this function, you should first call <BaseModel.__init__(self, opt)>\n        Then, you need to define four lists:\n            -- self.loss_names (str list):          specify the training losses that you want to plot and save.\n            -- self.model_names (str list):         define networks used in our training.\n            -- self.visual_names (str list):        specify the images that you want to display and save.\n            -- self.optimizers (optimizer list):    define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.\n        \"\"\"\n        self.opt = opt\n        self.isTrain = opt.isTrain\n        self.save_dir = Path(opt.checkpoints_dir) / opt.name  # save all the checkpoints to save_dir\n        self.device = opt.device\n        # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark.\n        if opt.preprocess != \"scale_width\":\n            torch.backends.cudnn.benchmark = True\n        self.loss_names = []\n        self.model_names = []\n        self.visual_names = []\n        self.optimizers = []\n        self.image_paths = []\n        self.metric = 0  # used for learning rate policy 'plateau'\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train):\n        \"\"\"Add new model-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n        \"\"\"\n        return parser\n\n    @abstractmethod\n    def set_input(self, input):\n        \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n        Parameters:\n            input (dict): includes the data itself and its metadata information.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def forward(self):\n        \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\"\"\"\n        pass\n\n    @abstractmethod\n    def optimize_parameters(self):\n        \"\"\"Calculate losses, gradients, and update network weights; called in every training iteration\"\"\"\n        pass\n\n    def setup(self, opt):\n        \"\"\"Load and print networks; create schedulers\n\n        Parameters:\n            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        # Initialize all networks and load if needed\n        for name in self.model_names:\n            if isinstance(name, str):\n                net = getattr(self, \"net\" + name)\n                net = networks.init_net(net, opt.init_type, opt.init_gain)\n\n                # Load networks if needed\n                if not self.isTrain or opt.continue_train:\n                    load_suffix = f\"iter_{opt.load_iter}\" if opt.load_iter > 0 else opt.epoch\n                    load_filename = f\"{load_suffix}_net_{name}.pth\"\n                    load_path = self.save_dir / load_filename\n\n                    if isinstance(net, torch.nn.parallel.DistributedDataParallel):\n                        net = net.module\n                    print(f\"loading the model from {load_path}\")\n\n                    state_dict = torch.load(load_path, map_location=str(self.device), weights_only=True)\n\n                    if hasattr(state_dict, \"_metadata\"):\n                        del state_dict._metadata\n\n                    # patch InstanceNorm checkpoints\n                    for key in list(state_dict.keys()):\n                        self.__patch_instance_norm_state_dict(state_dict, net, key.split(\".\"))\n                    net.load_state_dict(state_dict)\n\n                # Move network to device\n                net.to(self.device)\n\n                # Wrap networks with DDP after loading\n                if dist.is_initialized():\n                    # Check if using syncbatch normalization for DDP\n                    if self.opt.norm == \"syncbatch\":\n                        raise ValueError(f\"For distributed training, opt.norm must be 'syncbatch' or 'inst', but got '{self.opt.norm}'. \" \"Please set --norm syncbatch for multi-GPU training.\")\n\n                    net = torch.nn.parallel.DistributedDataParallel(net, device_ids=[self.device.index])\n                    # Sync all processes after DDP wrapping\n                    dist.barrier()\n\n                setattr(self, \"net\" + name, net)\n\n        self.print_networks(opt.verbose)\n\n        if self.isTrain:\n            self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers]\n\n    def eval(self):\n        \"\"\"Make models eval mode during test time\"\"\"\n        for name in self.model_names:\n            if isinstance(name, str):\n                net = getattr(self, \"net\" + name)\n                net.eval()\n\n    def test(self):\n        \"\"\"Forward function used in test time.\n\n        This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop\n        It also calls <compute_visuals> to produce additional visualization results\n        \"\"\"\n        with torch.no_grad():\n            self.forward()\n            self.compute_visuals()\n\n    def compute_visuals(self):\n        \"\"\"Calculate additional output images for visdom and HTML visualization\"\"\"\n        pass\n\n    def get_image_paths(self):\n        \"\"\"Return image paths that are used to load current data\"\"\"\n        return self.image_paths\n\n    def update_learning_rate(self):\n        \"\"\"Update learning rates for all the networks; called at the end of every epoch\"\"\"\n        old_lr = self.optimizers[0].param_groups[0][\"lr\"]\n        for scheduler in self.schedulers:\n            if self.opt.lr_policy == \"plateau\":\n                scheduler.step(self.metric)\n            else:\n                scheduler.step()\n\n        lr = self.optimizers[0].param_groups[0][\"lr\"]\n        print(f\"learning rate {old_lr:.7f} -> {lr:.7f}\")\n\n    def get_current_visuals(self):\n        \"\"\"Return visualization images. train.py will display these images with visdom, and save the images to a HTML\"\"\"\n        visual_ret = OrderedDict()\n        for name in self.visual_names:\n            if isinstance(name, str):\n                visual_ret[name] = getattr(self, name)\n        return visual_ret\n\n    def get_current_losses(self):\n        \"\"\"Return traning losses / errors. train.py will print out these errors on console, and save them to a file\"\"\"\n        errors_ret = OrderedDict()\n        for name in self.loss_names:\n            if isinstance(name, str):\n                errors_ret[name] = float(getattr(self, \"loss_\" + name))  # float(...) works for both scalar tensor and float number\n        return errors_ret\n\n    def save_networks(self, epoch):\n        \"\"\"Save all the networks to the disk, unwrapping them first.\"\"\"\n\n        # Only allow the main process (rank 0) to save the checkpoint\n        if not dist.is_initialized() or dist.get_rank() == 0:\n            for name in self.model_names:\n                if isinstance(name, str):\n                    save_filename = f\"{epoch}_net_{name}.pth\"\n                    save_path = self.save_dir / save_filename\n                    net = getattr(self, \"net\" + name)\n\n                    # 1. First, unwrap from DDP if it exists\n                    if hasattr(net, \"module\"):\n                        model_to_save = net.module\n                    else:\n                        model_to_save = net\n\n                    # 2. Second, unwrap from torch.compile if it exists\n                    if hasattr(model_to_save, \"_orig_mod\"):\n                        model_to_save = model_to_save._orig_mod\n\n                    # 3. Save the final, clean state_dict\n                    torch.save(model_to_save.state_dict(), save_path)\n\n    def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):\n        \"\"\"Fix InstanceNorm checkpoints incompatibility (prior to 0.4)\"\"\"\n        key = keys[i]\n        if i + 1 == len(keys):  # at the end, pointing to a parameter/buffer\n            if module.__class__.__name__.startswith(\"InstanceNorm\") and (key == \"running_mean\" or key == \"running_var\"):\n                if getattr(module, key) is None:\n                    state_dict.pop(\".\".join(keys))\n            if module.__class__.__name__.startswith(\"InstanceNorm\") and (key == \"num_batches_tracked\"):\n                state_dict.pop(\".\".join(keys))\n        else:\n            self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)\n\n    def load_networks(self, epoch):\n        \"\"\"Load all networks from the disk for DDP.\"\"\"\n\n        for name in self.model_names:\n            if isinstance(name, str):\n                load_filename = f\"{epoch}_net_{name}.pth\"\n                load_path = self.save_dir / load_filename\n                net = getattr(self, \"net\" + name)\n\n                if isinstance(net, torch.nn.parallel.DistributedDataParallel):\n                    net = net.module\n                print(f\"loading the model from {load_path}\")\n\n                state_dict = torch.load(load_path, map_location=str(self.device), weights_only=True)\n\n                if hasattr(state_dict, \"_metadata\"):\n                    del state_dict._metadata\n\n                # patch InstanceNorm checkpoints\n                for key in list(state_dict.keys()):\n                    self.__patch_instance_norm_state_dict(state_dict, net, key.split(\".\"))\n                net.load_state_dict(state_dict)\n\n        # Add a barrier to sync all processes before continuing\n        if dist.is_initialized():\n            dist.barrier()\n\n    def print_networks(self, verbose):\n        \"\"\"Print the total number of parameters in the network and (if verbose) network architecture\n\n        Parameters:\n            verbose (bool) -- if verbose: print the network architecture\n        \"\"\"\n        print(\"---------- Networks initialized -------------\")\n        for name in self.model_names:\n            if isinstance(name, str):\n                net = getattr(self, \"net\" + name)\n                num_params = 0\n                for param in net.parameters():\n                    num_params += param.numel()\n                if verbose:\n                    print(net)\n                print(f\"[Network {name}] Total number of parameters : {num_params / 1e6:.3f} M\")\n        print(\"-----------------------------------------------\")\n\n    def set_requires_grad(self, nets, requires_grad=False):\n        \"\"\"Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n        Parameters:\n            nets (network list)   -- a list of networks\n            requires_grad (bool)  -- whether the networks require gradients or not\n        \"\"\"\n        if not isinstance(nets, list):\n            nets = [nets]\n        for net in nets:\n            if net is not None:\n                for param in net.parameters():\n                    param.requires_grad = requires_grad\n\n    def init_networks(self, init_type=\"normal\", init_gain=0.02):\n        \"\"\"Initialize all networks: 1. move to device; 2. initialize weights\n\n        Parameters:\n            init_type (str) -- initialization method: normal | xavier | kaiming | orthogonal\n            init_gain (float) -- scaling factor for normal, xavier and orthogonal\n        \"\"\"\n        import os\n\n        for name in self.model_names:\n            if isinstance(name, str):\n                net = getattr(self, \"net\" + name)\n\n                # Move to device\n                if torch.cuda.is_available():\n                    if \"LOCAL_RANK\" in os.environ:\n                        local_rank = int(os.environ[\"LOCAL_RANK\"])\n                        net.to(local_rank)\n                        print(f\"Initialized network {name} with device cuda:{local_rank}\")\n                    else:\n                        net.to(0)\n                        print(f\"Initialized network {name} with device cuda:0\")\n                else:\n                    net.to(\"cpu\")\n                    print(f\"Initialized network {name} with device cpu\")\n\n                # Initialize weights using networks function\n                networks.init_weights(net, init_type, init_gain)\n"
  },
  {
    "path": "models/colorization_model.py",
    "content": "from .pix2pix_model import Pix2PixModel\nimport torch\nfrom skimage import color  # used for lab2rgb\nimport numpy as np\n\n\nclass ColorizationModel(Pix2PixModel):\n    \"\"\"This is a subclass of Pix2PixModel for image colorization (black & white image -> colorful images).\n\n    The model training requires '-dataset_model colorization' dataset.\n    It trains a pix2pix model, mapping from L channel to ab channels in Lab color space.\n    By default, the colorization dataset will automatically set '--input_nc 1' and '--output_nc 2'.\n    \"\"\"\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train=True):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n\n        By default, we use 'colorization' dataset for this model.\n        See the original pix2pix paper (https://arxiv.org/pdf/1611.07004.pdf) and colorization results (Figure 9 in the paper)\n        \"\"\"\n        Pix2PixModel.modify_commandline_options(parser, is_train)\n        parser.set_defaults(dataset_mode=\"colorization\")\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize the class.\n\n        Parameters:\n            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n\n        For visualization, we set 'visual_names' as 'real_A' (input real image),\n        'real_B_rgb' (ground truth RGB image), and 'fake_B_rgb' (predicted RGB image)\n        We convert the Lab image 'real_B' (inherited from Pix2pixModel) to a RGB image 'real_B_rgb'.\n        we convert the Lab image 'fake_B' (inherited from Pix2pixModel) to a RGB image 'fake_B_rgb'.\n        \"\"\"\n        # reuse the pix2pix model\n        Pix2PixModel.__init__(self, opt)\n        # specify the images to be visualized.\n        self.visual_names = [\"real_A\", \"real_B_rgb\", \"fake_B_rgb\"]\n\n    def lab2rgb(self, L, AB):\n        \"\"\"Convert an Lab tensor image to a RGB numpy output\n        Parameters:\n            L  (1-channel tensor array): L channel images (range: [-1, 1], torch tensor array)\n            AB (2-channel tensor array):  ab channel images (range: [-1, 1], torch tensor array)\n\n        Returns:\n            rgb (RGB numpy image): rgb output images  (range: [0, 255], numpy array)\n        \"\"\"\n        AB2 = AB * 110.0\n        L2 = (L + 1.0) * 50.0\n        Lab = torch.cat([L2, AB2], dim=1)\n        Lab = Lab[0].data.cpu().float().numpy()\n        Lab = np.transpose(Lab.astype(np.float64), (1, 2, 0))\n        rgb = color.lab2rgb(Lab) * 255\n        return rgb\n\n    def compute_visuals(self):\n        \"\"\"Calculate additional output images for visdom and HTML visualization\"\"\"\n        self.real_B_rgb = self.lab2rgb(self.real_A, self.real_B)\n        self.fake_B_rgb = self.lab2rgb(self.real_A, self.fake_B)\n"
  },
  {
    "path": "models/cycle_gan_model.py",
    "content": "import torch\nimport itertools\nfrom util.image_pool import ImagePool\nfrom .base_model import BaseModel\nfrom . import networks\n\n\nclass CycleGANModel(BaseModel):\n    \"\"\"\n    This class implements the CycleGAN model, for learning image-to-image translation without paired data.\n\n    The model training requires '--dataset_mode unaligned' dataset.\n    By default, it uses a '--netG resnet_9blocks' ResNet generator,\n    a '--netD basic' discriminator (PatchGAN introduced by pix2pix),\n    and a least-square GANs objective ('--gan_mode lsgan').\n\n    CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf\n    \"\"\"\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train=True):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n\n        For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses.\n        A (source domain), B (target domain).\n        Generators: G_A: A -> B; G_B: B -> A.\n        Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A.\n        Forward cycle loss:  lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper)\n        Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper)\n        Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 \"Photo generation from paintings\" in the paper)\n        Dropout is not used in the original CycleGAN paper.\n        \"\"\"\n        parser.set_defaults(no_dropout=True)  # default CycleGAN did not use dropout\n        if is_train:\n            parser.add_argument(\"--lambda_A\", type=float, default=10.0, help=\"weight for cycle loss (A -> B -> A)\")\n            parser.add_argument(\"--lambda_B\", type=float, default=10.0, help=\"weight for cycle loss (B -> A -> B)\")\n            parser.add_argument(\n                \"--lambda_identity\",\n                type=float,\n                default=0.5,\n                help=\"use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1\",\n            )\n\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize the CycleGAN class.\n\n        Parameters:\n            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        BaseModel.__init__(self, opt)\n        # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>\n        self.loss_names = [\"D_A\", \"G_A\", \"cycle_A\", \"idt_A\", \"D_B\", \"G_B\", \"cycle_B\", \"idt_B\"]\n        # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>\n        visual_names_A = [\"real_A\", \"fake_B\", \"rec_A\"]\n        visual_names_B = [\"real_B\", \"fake_A\", \"rec_B\"]\n        if self.isTrain and self.opt.lambda_identity > 0.0:  # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_B(A)\n            visual_names_A.append(\"idt_B\")\n            visual_names_B.append(\"idt_A\")\n\n        self.visual_names = visual_names_A + visual_names_B  # combine visualizations for A and B\n        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.\n        if self.isTrain:\n            self.model_names = [\"G_A\", \"G_B\", \"D_A\", \"D_B\"]\n        else:  # during test time, only load Gs\n            self.model_names = [\"G_A\", \"G_B\"]\n\n        # define networks (both Generators and discriminators)\n        # The naming is different from those used in the paper.\n        # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)\n        self.netG_A = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain)\n        self.netG_B = networks.define_G(opt.output_nc, opt.input_nc, opt.ngf, opt.netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain)\n\n        if self.isTrain:  # define discriminators\n            self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain)\n            self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain)\n\n        if self.isTrain:\n            if opt.lambda_identity > 0.0:  # only works when input and output images have the same number of channels\n                assert opt.input_nc == opt.output_nc\n            self.fake_A_pool = ImagePool(opt.pool_size)  # create image buffer to store previously generated images\n            self.fake_B_pool = ImagePool(opt.pool_size)  # create image buffer to store previously generated images\n            # define loss functions\n            self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)  # define GAN loss.\n            self.criterionCycle = torch.nn.L1Loss()\n            self.criterionIdt = torch.nn.L1Loss()\n            # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.\n            self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))\n            self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))\n            self.optimizers.append(self.optimizer_G)\n            self.optimizers.append(self.optimizer_D)\n\n    def set_input(self, input):\n        \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n        Parameters:\n            input (dict): include the data itself and its metadata information.\n\n        The option 'direction' can be used to swap domain A and domain B.\n        \"\"\"\n        AtoB = self.opt.direction == \"AtoB\"\n        self.real_A = input[\"A\" if AtoB else \"B\"].to(self.device)\n        self.real_B = input[\"B\" if AtoB else \"A\"].to(self.device)\n        self.image_paths = input[\"A_paths\" if AtoB else \"B_paths\"]\n\n    def forward(self):\n        \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\"\"\"\n        self.fake_B = self.netG_A(self.real_A)  # G_A(A)\n        self.rec_A = self.netG_B(self.fake_B)  # G_B(G_A(A))\n        self.fake_A = self.netG_B(self.real_B)  # G_B(B)\n        self.rec_B = self.netG_A(self.fake_A)  # G_A(G_B(B))\n\n    def backward_D_basic(self, netD, real, fake):\n        \"\"\"Calculate GAN loss for the discriminator\n\n        Parameters:\n            netD (network)      -- the discriminator D\n            real (tensor array) -- real images\n            fake (tensor array) -- images generated by a generator\n\n        Return the discriminator loss.\n        We also call loss_D.backward() to calculate the gradients.\n        \"\"\"\n        # Real\n        pred_real = netD(real)\n        loss_D_real = self.criterionGAN(pred_real, True)\n        # Fake\n        pred_fake = netD(fake.detach())\n        loss_D_fake = self.criterionGAN(pred_fake, False)\n        # Combined loss and calculate gradients\n        loss_D = (loss_D_real + loss_D_fake) * 0.5\n        loss_D.backward()\n        return loss_D\n\n    def backward_D_A(self):\n        \"\"\"Calculate GAN loss for discriminator D_A\"\"\"\n        fake_B = self.fake_B_pool.query(self.fake_B)\n        self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B)\n\n    def backward_D_B(self):\n        \"\"\"Calculate GAN loss for discriminator D_B\"\"\"\n        fake_A = self.fake_A_pool.query(self.fake_A)\n        self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A)\n\n    def backward_G(self):\n        \"\"\"Calculate the loss for generators G_A and G_B\"\"\"\n        lambda_idt = self.opt.lambda_identity\n        lambda_A = self.opt.lambda_A\n        lambda_B = self.opt.lambda_B\n        # Identity loss\n        if lambda_idt > 0:\n            # G_A should be identity if real_B is fed: ||G_A(B) - B||\n            self.idt_A = self.netG_A(self.real_B)\n            self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt\n            # G_B should be identity if real_A is fed: ||G_B(A) - A||\n            self.idt_B = self.netG_B(self.real_A)\n            self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt\n        else:\n            self.loss_idt_A = 0\n            self.loss_idt_B = 0\n\n        # GAN loss D_A(G_A(A))\n        self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True)\n        # GAN loss D_B(G_B(B))\n        self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True)\n        # Forward cycle loss || G_B(G_A(A)) - A||\n        self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A\n        # Backward cycle loss || G_A(G_B(B)) - B||\n        self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B\n        # combined loss and calculate gradients\n        self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B\n        self.loss_G.backward()\n\n    def optimize_parameters(self):\n        \"\"\"Calculate losses, gradients, and update network weights; called in every training iteration\"\"\"\n        # forward\n        self.forward()  # compute fake images and reconstruction images.\n        # G_A and G_B\n        self.set_requires_grad([self.netD_A, self.netD_B], False)  # Ds require no gradients when optimizing Gs\n        self.optimizer_G.zero_grad()  # set G_A and G_B's gradients to zero\n        self.backward_G()  # calculate gradients for G_A and G_B\n        self.optimizer_G.step()  # update G_A and G_B's weights\n        # D_A and D_B\n        self.set_requires_grad([self.netD_A, self.netD_B], True)\n        self.optimizer_D.zero_grad()  # set D_A and D_B's gradients to zero\n        self.backward_D_A()  # calculate gradients for D_A\n        self.backward_D_B()  # calculate graidents for D_B\n        self.optimizer_D.step()  # update D_A and D_B's weights\n"
  },
  {
    "path": "models/networks.py",
    "content": "import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torch.optim import lr_scheduler\n\n\n###############################################################################\n# Helper Functions\n###############################################################################\n\n\nclass Identity(nn.Module):\n    def forward(self, x):\n        return x\n\n\ndef get_norm_layer(norm_type=\"instance\"):\n    \"\"\"Return a normalization layer\n\n    Parameters:\n        norm_type (str) -- the name of the normalization layer: batch | instance | none\n\n    For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n    For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.\n    \"\"\"\n    if norm_type == \"batch\":\n        norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)\n    elif norm_type == \"syncbatch\":\n        norm_layer = functools.partial(nn.SyncBatchNorm, affine=True, track_running_stats=True)\n    elif norm_type == \"instance\":\n        norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n    elif norm_type == \"none\":\n\n        def norm_layer(x):\n            return Identity()\n\n    else:\n        raise NotImplementedError(\"normalization layer [%s] is not found\" % norm_type)\n    return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n    \"\"\"Return a learning rate scheduler\n\n    Parameters:\n        optimizer          -- the optimizer of the network\n        opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions．\n                              opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine\n\n    For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs\n    and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs.\n    For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.\n    See https://pytorch.org/docs/stable/optim.html for more details.\n    \"\"\"\n    if opt.lr_policy == \"linear\":\n\n        def lambda_rule(epoch):\n            lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.n_epochs) / float(opt.n_epochs_decay + 1)\n            return lr_l\n\n        scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n    elif opt.lr_policy == \"step\":\n        scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)\n    elif opt.lr_policy == \"plateau\":\n        scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode=\"min\", factor=0.2, threshold=0.01, patience=5)\n    elif opt.lr_policy == \"cosine\":\n        scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.n_epochs, eta_min=0)\n    else:\n        return NotImplementedError(\"learning rate policy [%s] is not implemented\", opt.lr_policy)\n    return scheduler\n\n\ndef init_weights(net, init_type=\"normal\", init_gain=0.02):\n    \"\"\"Initialize network weights.\n\n    Parameters:\n        net (network)   -- network to be initialized\n        init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n        init_gain (float)    -- scaling factor for normal, xavier and orthogonal.\n\n    We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might\n    work better for some applications. Feel free to try yourself.\n    \"\"\"\n\n    def init_func(m):  # define the initialization function\n        classname = m.__class__.__name__\n        if hasattr(m, \"weight\") and (classname.find(\"Conv\") != -1 or classname.find(\"Linear\") != -1):\n            if init_type == \"normal\":\n                init.normal_(m.weight.data, 0.0, init_gain)\n            elif init_type == \"xavier\":\n                init.xavier_normal_(m.weight.data, gain=init_gain)\n            elif init_type == \"kaiming\":\n                init.kaiming_normal_(m.weight.data, a=0, mode=\"fan_in\")\n            elif init_type == \"orthogonal\":\n                init.orthogonal_(m.weight.data, gain=init_gain)\n            else:\n                raise NotImplementedError(\"initialization method [%s] is not implemented\" % init_type)\n            if hasattr(m, \"bias\") and m.bias is not None:\n                init.constant_(m.bias.data, 0.0)\n        elif classname.find(\"BatchNorm2d\") != -1:  # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n            init.normal_(m.weight.data, 1.0, init_gain)\n            init.constant_(m.bias.data, 0.0)\n\n    print(\"initialize network with %s\" % init_type)\n    net.apply(init_func)  # apply the initialization function <init_func>\n\n\ndef init_net(net, init_type=\"normal\", init_gain=0.02):\n    \"\"\"Initialize a network: 1. register CPU/GPU device; 2. initialize the network weights\n    Parameters:\n        net (network)      -- the network to be initialized\n        init_type (str)    -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n        gain (float)       -- scaling factor for normal, xavier and orthogonal.\n\n    Return an initialized network.\n    \"\"\"\n    import os\n\n    if torch.cuda.is_available():\n        if \"LOCAL_RANK\" in os.environ:\n            local_rank = int(os.environ[\"LOCAL_RANK\"])\n            net.to(local_rank)\n            print(f\"Initialized with device cuda:{local_rank}\")\n        else:\n            net.to(0)\n            print(\"Initialized with device cuda:0\")\n    init_weights(net, init_type, init_gain=init_gain)\n    return net\n\n\ndef define_G(input_nc, output_nc, ngf, netG, norm=\"batch\", use_dropout=False, init_type=\"normal\", init_gain=0.02):\n    \"\"\"Create a generator\n\n    Parameters:\n        input_nc (int) -- the number of channels in input images\n        output_nc (int) -- the number of channels in output images\n        ngf (int) -- the number of filters in the last conv layer\n        netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_128 | unet_256\n        norm (str) -- the name of normalization layers used in the network: batch | instance | none\n        use_dropout (bool) -- if use dropout layers.\n        init_type (str)    -- the name of our initialization method.\n        init_gain (float)  -- scaling factor for normal, xavier and orthogonal.\n\n    Returns a generator\n    \"\"\"\n    net = None\n    norm_layer = get_norm_layer(norm_type=norm)\n\n    if netG == \"resnet_9blocks\":\n        net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n    elif netG == \"resnet_6blocks\":\n        net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)\n    elif netG == \"unet_128\":\n        net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n    elif netG == \"unet_256\":\n        net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n    else:\n        raise NotImplementedError(\"Generator model name [%s] is not recognized\" % netG)\n    return net\n\n\ndef define_D(input_nc, ndf, netD, n_layers_D=3, norm=\"batch\", init_type=\"normal\", init_gain=0.02):\n    \"\"\"Create a discriminator\n\n    Parameters:\n        input_nc (int)     -- the number of channels in input images\n        ndf (int)          -- the number of filters in the first conv layer\n        netD (str)         -- the architecture's name: basic | n_layers | pixel\n        n_layers_D (int)   -- the number of conv layers in the discriminator; effective when netD=='n_layers'\n        norm (str)         -- the type of normalization layers used in the network.\n        init_type (str)    -- the name of the initialization method.\n        init_gain (float)  -- scaling factor for normal, xavier and orthogonal.\n\n    Returns a discriminator\n\n    Our current implementation provides three types of discriminators:\n        [basic]: 'PatchGAN' classifier described in the original pix2pix paper.\n        It can classify whether 70×70 overlapping patches are real or fake.\n        Such a patch-level discriminator architecture has fewer parameters\n        than a full-image discriminator and can work on arbitrarily-sized images\n        in a fully convolutional fashion.\n\n        [n_layers]: With this mode, you can specify the number of conv layers in the discriminator\n        with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)\n\n        [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.\n        It encourages greater color diversity but has no effect on spatial statistics.\n\n    The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.\n    \"\"\"\n    net = None\n    norm_layer = get_norm_layer(norm_type=norm)\n\n    if netD == \"basic\":  # default PatchGAN classifier\n        net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)\n    elif netD == \"n_layers\":  # more options\n        net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)\n    elif netD == \"pixel\":  # classify if each pixel is real or fake\n        net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)\n    else:\n        raise NotImplementedError(\"Discriminator model name [%s] is not recognized\" % netD)\n    return net\n\n\n##############################################################################\n# Classes\n##############################################################################\nclass GANLoss(nn.Module):\n    \"\"\"Define different GAN objectives.\n\n    The GANLoss class abstracts away the need to create the target label tensor\n    that has the same size as the input.\n    \"\"\"\n\n    def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n        \"\"\"Initialize the GANLoss class.\n\n        Parameters:\n            gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n            target_real_label (bool) - - label for a real image\n            target_fake_label (bool) - - label of a fake image\n\n        Note: Do not use sigmoid as the last layer of Discriminator.\n        LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n        \"\"\"\n        super(GANLoss, self).__init__()\n        self.register_buffer(\"real_label\", torch.tensor(target_real_label))\n        self.register_buffer(\"fake_label\", torch.tensor(target_fake_label))\n        self.gan_mode = gan_mode\n        if gan_mode == \"lsgan\":\n            self.loss = nn.MSELoss()\n        elif gan_mode == \"vanilla\":\n            self.loss = nn.BCEWithLogitsLoss()\n        elif gan_mode in [\"wgangp\"]:\n            self.loss = None\n        else:\n            raise NotImplementedError(\"gan mode %s not implemented\" % gan_mode)\n\n    def get_target_tensor(self, prediction, target_is_real):\n        \"\"\"Create label tensors with the same size as the input.\n\n        Parameters:\n            prediction (tensor) - - tpyically the prediction from a discriminator\n            target_is_real (bool) - - if the ground truth label is for real images or fake images\n\n        Returns:\n            A label tensor filled with ground truth label, and with the size of the input\n        \"\"\"\n\n        if target_is_real:\n            target_tensor = self.real_label\n        else:\n            target_tensor = self.fake_label\n        return target_tensor.expand_as(prediction)\n\n    def __call__(self, prediction, target_is_real):\n        \"\"\"Calculate loss given Discriminator's output and grount truth labels.\n\n        Parameters:\n            prediction (tensor) - - tpyically the prediction output from a discriminator\n            target_is_real (bool) - - if the ground truth label is for real images or fake images\n\n        Returns:\n            the calculated loss.\n        \"\"\"\n        if self.gan_mode in [\"lsgan\", \"vanilla\"]:\n            target_tensor = self.get_target_tensor(prediction, target_is_real)\n            loss = self.loss(prediction, target_tensor)\n        elif self.gan_mode == \"wgangp\":\n            if target_is_real:\n                loss = -prediction.mean()\n            else:\n                loss = prediction.mean()\n        return loss\n\n\ndef cal_gradient_penalty(netD, real_data, fake_data, device, type=\"mixed\", constant=1.0, lambda_gp=10.0):\n    \"\"\"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n\n    Arguments:\n        netD (network)              -- discriminator network\n        real_data (tensor array)    -- real images\n        fake_data (tensor array)    -- generated images from the generator\n        device (str)                -- GPU / CPU\n        type (str)                  -- if we mix real and fake data or not [real | fake | mixed].\n        constant (float)            -- the constant used in formula ( ||gradient||_2 - constant)^2\n        lambda_gp (float)           -- weight for this loss\n\n    Returns the gradient penalty loss\n    \"\"\"\n    if lambda_gp > 0.0:\n        if type == \"real\":  # either use real images, fake images, or a linear interpolation of two.\n            interpolatesv = real_data\n        elif type == \"fake\":\n            interpolatesv = fake_data\n        elif type == \"mixed\":\n            alpha = torch.rand(real_data.shape[0], 1, device=device)\n            alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)\n            interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)\n        else:\n            raise NotImplementedError(f\"{type} not implemented\")\n        interpolatesv.requires_grad_(True)\n        disc_interpolates = netD(interpolatesv)\n        gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True)\n        gradients = gradients[0].view(real_data.size(0), -1)  # flat the data\n        gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp  # added eps\n        return gradient_penalty, gradients\n    else:\n        return 0.0, None\n\n\nclass ResnetGenerator(nn.Module):\n    \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n    We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n    \"\"\"\n\n    def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type=\"reflect\"):\n        \"\"\"Construct a Resnet-based generator\n\n        Parameters:\n            input_nc (int)      -- the number of channels in input images\n            output_nc (int)     -- the number of channels in output images\n            ngf (int)           -- the number of filters in the last conv layer\n            norm_layer          -- normalization layer\n            use_dropout (bool)  -- if use dropout layers\n            n_blocks (int)      -- the number of ResNet blocks\n            padding_type (str)  -- the name of padding layer in conv layers: reflect | replicate | zero\n        \"\"\"\n        assert n_blocks >= 0\n        super(ResnetGenerator, self).__init__()\n        if type(norm_layer) == functools.partial:\n            use_bias = norm_layer.func == nn.InstanceNorm2d\n        else:\n            use_bias = norm_layer == nn.InstanceNorm2d\n\n        model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)]\n\n        n_downsampling = 2\n        for i in range(n_downsampling):  # add downsampling layers\n            mult = 2**i\n            model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)]\n\n        mult = 2**n_downsampling\n        for i in range(n_blocks):  # add ResNet blocks\n\n            model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n        for i in range(n_downsampling):  # add upsampling layers\n            mult = 2 ** (n_downsampling - i)\n            model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)]\n        model += [nn.ReflectionPad2d(3)]\n        model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n        model += [nn.Tanh()]\n\n        self.model = nn.Sequential(*model)\n\n    def forward(self, input):\n        \"\"\"Standard forward\"\"\"\n        return self.model(input)\n\n\nclass ResnetBlock(nn.Module):\n    \"\"\"Define a Resnet block\"\"\"\n\n    def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n        \"\"\"Initialize the Resnet block\n\n        A resnet block is a conv block with skip connections\n        We construct a conv block with build_conv_block function,\n        and implement skip connections in <forward> function.\n        Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf\n        \"\"\"\n        super(ResnetBlock, self).__init__()\n        self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n    def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n        \"\"\"Construct a convolutional block.\n\n        Parameters:\n            dim (int)           -- the number of channels in the conv layer.\n            padding_type (str)  -- the name of padding layer: reflect | replicate | zero\n            norm_layer          -- normalization layer\n            use_dropout (bool)  -- if use dropout layers.\n            use_bias (bool)     -- if the conv layer uses bias or not\n\n        Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))\n        \"\"\"\n        conv_block = []\n        p = 0\n        if padding_type == \"reflect\":\n            conv_block += [nn.ReflectionPad2d(1)]\n        elif padding_type == \"replicate\":\n            conv_block += [nn.ReplicationPad2d(1)]\n        elif padding_type == \"zero\":\n            p = 1\n        else:\n            raise NotImplementedError(\"padding [%s] is not implemented\" % padding_type)\n\n        conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]\n        if use_dropout:\n            conv_block += [nn.Dropout(0.5)]\n\n        p = 0\n        if padding_type == \"reflect\":\n            conv_block += [nn.ReflectionPad2d(1)]\n        elif padding_type == \"replicate\":\n            conv_block += [nn.ReplicationPad2d(1)]\n        elif padding_type == \"zero\":\n            p = 1\n        else:\n            raise NotImplementedError(\"padding [%s] is not implemented\" % padding_type)\n        conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]\n\n        return nn.Sequential(*conv_block)\n\n    def forward(self, x):\n        \"\"\"Forward function (with skip connections)\"\"\"\n        out = x + self.conv_block(x)  # add skip connections\n        return out\n\n\nclass UnetGenerator(nn.Module):\n    \"\"\"Create a Unet-based generator\"\"\"\n\n    def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n        \"\"\"Construct a Unet generator\n        Parameters:\n            input_nc (int)  -- the number of channels in input images\n            output_nc (int) -- the number of channels in output images\n            num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,\n                                image of size 128x128 will become of size 1x1 # at the bottleneck\n            ngf (int)       -- the number of filters in the last conv layer\n            norm_layer      -- normalization layer\n\n        We construct the U-Net from the innermost layer to the outermost layer.\n        It is a recursive process.\n        \"\"\"\n        super(UnetGenerator, self).__init__()\n        # construct unet structure\n        unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True)  # add the innermost layer\n        for i in range(num_downs - 5):  # add intermediate layers with ngf * 8 filters\n            unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n        # gradually reduce the number of filters from ngf * 8 to ngf\n        unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n        unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n        unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n        self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer)  # add the outermost layer\n\n    def forward(self, input):\n        \"\"\"Standard forward\"\"\"\n        return self.model(input)\n\n\nclass UnetSkipConnectionBlock(nn.Module):\n    \"\"\"Defines the Unet submodule with skip connection.\n    X -------------------identity----------------------\n    |-- downsampling -- |submodule| -- upsampling --|\n    \"\"\"\n\n    def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n        \"\"\"Construct a Unet submodule with skip connections.\n\n        Parameters:\n            outer_nc (int) -- the number of filters in the outer conv layer\n            inner_nc (int) -- the number of filters in the inner conv layer\n            input_nc (int) -- the number of channels in input images/features\n            submodule (UnetSkipConnectionBlock) -- previously defined submodules\n            outermost (bool)    -- if this module is the outermost module\n            innermost (bool)    -- if this module is the innermost module\n            norm_layer          -- normalization layer\n            use_dropout (bool)  -- if use dropout layers.\n        \"\"\"\n        super(UnetSkipConnectionBlock, self).__init__()\n        self.outermost = outermost\n        if type(norm_layer) == functools.partial:\n            use_bias = norm_layer.func == nn.InstanceNorm2d\n        else:\n            use_bias = norm_layer == nn.InstanceNorm2d\n        if input_nc is None:\n            input_nc = outer_nc\n        downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias)\n        downrelu = nn.LeakyReLU(0.2, True)\n        downnorm = norm_layer(inner_nc)\n        uprelu = nn.ReLU(True)\n        upnorm = norm_layer(outer_nc)\n\n        if outermost:\n            upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1)\n            down = [downconv]\n            up = [uprelu, upconv, nn.Tanh()]\n            model = down + [submodule] + up\n        elif innermost:\n            upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias)\n            down = [downrelu, downconv]\n            up = [uprelu, upconv, upnorm]\n            model = down + up\n        else:\n            upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias)\n            down = [downrelu, downconv, downnorm]\n            up = [uprelu, upconv, upnorm]\n\n            if use_dropout:\n                model = down + [submodule] + up + [nn.Dropout(0.5)]\n            else:\n                model = down + [submodule] + up\n\n        self.model = nn.Sequential(*model)\n\n    def forward(self, x):\n        if self.outermost:\n            return self.model(x)\n        else:  # add skip connections\n            return torch.cat([x, self.model(x)], 1)\n\n\nclass NLayerDiscriminator(nn.Module):\n    \"\"\"Defines a PatchGAN discriminator\"\"\"\n\n    def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):\n        \"\"\"Construct a PatchGAN discriminator\n\n        Parameters:\n            input_nc (int)  -- the number of channels in input images\n            ndf (int)       -- the number of filters in the last conv layer\n            n_layers (int)  -- the number of conv layers in the discriminator\n            norm_layer      -- normalization layer\n        \"\"\"\n        super(NLayerDiscriminator, self).__init__()\n        if type(norm_layer) == functools.partial:  # no need to use bias as BatchNorm2d has affine parameters\n            use_bias = norm_layer.func == nn.InstanceNorm2d\n        else:\n            use_bias = norm_layer == nn.InstanceNorm2d\n\n        kw = 4\n        padw = 1\n        sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n        nf_mult = 1\n        nf_mult_prev = 1\n        for n in range(1, n_layers):  # gradually increase the number of filters\n            nf_mult_prev = nf_mult\n            nf_mult = min(2**n, 8)\n            sequence += [nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True)]\n\n        nf_mult_prev = nf_mult\n        nf_mult = min(2**n_layers, 8)\n        sequence += [nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True)]\n\n        sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]  # output 1 channel prediction map\n        self.model = nn.Sequential(*sequence)\n\n    def forward(self, input):\n        \"\"\"Standard forward.\"\"\"\n        return self.model(input)\n\n\nclass PixelDiscriminator(nn.Module):\n    \"\"\"Defines a 1x1 PatchGAN discriminator (pixelGAN)\"\"\"\n\n    def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):\n        \"\"\"Construct a 1x1 PatchGAN discriminator\n\n        Parameters:\n            input_nc (int)  -- the number of channels in input images\n            ndf (int)       -- the number of filters in the last conv layer\n            norm_layer      -- normalization layer\n        \"\"\"\n        super(PixelDiscriminator, self).__init__()\n        if type(norm_layer) == functools.partial:  # no need to use bias as BatchNorm2d has affine parameters\n            use_bias = norm_layer.func == nn.InstanceNorm2d\n        else:\n            use_bias = norm_layer == nn.InstanceNorm2d\n\n        self.net = [\n            nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),\n            nn.LeakyReLU(0.2, True),\n            nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),\n            norm_layer(ndf * 2),\n            nn.LeakyReLU(0.2, True),\n            nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias),\n        ]\n\n        self.net = nn.Sequential(*self.net)\n\n    def forward(self, input):\n        \"\"\"Standard forward.\"\"\"\n        return self.net(input)\n"
  },
  {
    "path": "models/pix2pix_model.py",
    "content": "import torch\nfrom .base_model import BaseModel\nfrom . import networks\n\n\nclass Pix2PixModel(BaseModel):\n    \"\"\"This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.\n\n    The model training requires '--dataset_mode aligned' dataset.\n    By default, it uses a '--netG unet256' U-Net generator,\n    a '--netD basic' discriminator (PatchGAN),\n    and a '--gan_mode' vanilla GAN loss (the cross-entropy objective used in the orignal GAN paper).\n\n    pix2pix paper: https://arxiv.org/pdf/1611.07004.pdf\n    \"\"\"\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train=True):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n\n        For pix2pix, we do not use image buffer\n        The training objective is: GAN Loss + lambda_L1 * ||G(A)-B||_1\n        By default, we use vanilla GAN loss, UNet with batchnorm, and aligned datasets.\n        \"\"\"\n        # changing the default values to match the pix2pix paper (https://phillipi.github.io/pix2pix/)\n        parser.set_defaults(norm=\"batch\", netG=\"unet_256\", dataset_mode=\"aligned\")\n        if is_train:\n            parser.set_defaults(pool_size=0, gan_mode=\"vanilla\")\n            parser.add_argument(\"--lambda_L1\", type=float, default=100.0, help=\"weight for L1 loss\")\n\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize the pix2pix class.\n\n        Parameters:\n            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        BaseModel.__init__(self, opt)\n        # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>\n        self.loss_names = [\"G_GAN\", \"G_L1\", \"D_real\", \"D_fake\"]\n        # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>\n        self.visual_names = [\"real_A\", \"fake_B\", \"real_B\"]\n        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>\n        if self.isTrain:\n            self.model_names = [\"G\", \"D\"]\n        else:  # during test time, only load G\n            self.model_names = [\"G\"]\n        self.device = opt.device\n        # define networks (both generator and discriminator)\n        self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain)\n\n        if self.isTrain:  # define a discriminator; conditional GANs need to take both input and output images; Therefore, #channels for D is input_nc + output_nc\n            self.netD = networks.define_D(opt.input_nc + opt.output_nc, opt.ndf, opt.netD, opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain)\n\n        if self.isTrain:\n            # define loss functions\n            self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)  # move to the device for custom loss\n            self.criterionL1 = torch.nn.L1Loss()\n            # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.\n            self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n            self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n            self.optimizers.append(self.optimizer_G)\n            self.optimizers.append(self.optimizer_D)\n\n    def set_input(self, input):\n        \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n        Parameters:\n            input (dict): include the data itself and its metadata information.\n\n        The option 'direction' can be used to swap images in domain A and domain B.\n        \"\"\"\n        AtoB = self.opt.direction == \"AtoB\"\n        self.real_A = input[\"A\" if AtoB else \"B\"].to(self.device)\n        self.real_B = input[\"B\" if AtoB else \"A\"].to(self.device)\n        self.image_paths = input[\"A_paths\" if AtoB else \"B_paths\"]\n\n    def forward(self):\n        \"\"\"Run forward pass; called by both functions <optimize_parameters> and <test>.\"\"\"\n        self.fake_B = self.netG(self.real_A)  # G(A)\n\n    def backward_D(self):\n        \"\"\"Calculate GAN loss for the discriminator\"\"\"\n        # Fake; stop backprop to the generator by detaching fake_B\n        fake_AB = torch.cat((self.real_A, self.fake_B), 1)  # we use conditional GANs; we need to feed both input and output to the discriminator\n        pred_fake = self.netD(fake_AB.detach())\n        self.loss_D_fake = self.criterionGAN(pred_fake, False)\n        # Real\n        real_AB = torch.cat((self.real_A, self.real_B), 1)\n        pred_real = self.netD(real_AB)\n        self.loss_D_real = self.criterionGAN(pred_real, True)\n        # combine loss and calculate gradients\n        self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5\n        self.loss_D.backward()\n\n    def backward_G(self):\n        \"\"\"Calculate GAN and L1 loss for the generator\"\"\"\n        # First, G(A) should fake the discriminator\n        fake_AB = torch.cat((self.real_A, self.fake_B), 1)\n        pred_fake = self.netD(fake_AB)\n        self.loss_G_GAN = self.criterionGAN(pred_fake, True)\n        # Second, G(A) = B\n        self.loss_G_L1 = self.criterionL1(self.fake_B, self.real_B) * self.opt.lambda_L1\n        # combine loss and calculate gradients\n        self.loss_G = self.loss_G_GAN + self.loss_G_L1\n        self.loss_G.backward()\n\n    def optimize_parameters(self):\n        self.forward()  # compute fake images: G(A)\n        # update D\n        self.set_requires_grad(self.netD, True)  # enable backprop for D\n        self.optimizer_D.zero_grad()  # set D's gradients to zero\n        self.backward_D()  # calculate gradients for D\n        self.optimizer_D.step()  # update D's weights\n        # update G\n        self.set_requires_grad(self.netD, False)  # D requires no gradients when optimizing G\n        self.optimizer_G.zero_grad()  # set G's gradients to zero\n        self.backward_G()  # calculate graidents for G\n        self.optimizer_G.step()  # update G's weights\n"
  },
  {
    "path": "models/template_model.py",
    "content": "\"\"\"Model class template\n\nThis module provides a template for users to implement custom models.\nYou can specify '--model template' to use this model.\nThe class name should be consistent with both the filename and its model option.\nThe filename should be <model>_dataset.py\nThe class name should be <Model>Dataset.py\nIt implements a simple image-to-image translation baseline based on regression loss.\nGiven input-output pairs (data_A, data_B), it learns a network netG that can minimize the following L1 loss:\n    min_<netG> ||netG(data_A) - data_B||_1\nYou need to implement the following functions:\n    <modify_commandline_options>:　Add model-specific options and rewrite default values for existing options.\n    <__init__>: Initialize this model class.\n    <set_input>: Unpack input data and perform data pre-processing.\n    <forward>: Run forward pass. This will be called by both <optimize_parameters> and <test>.\n    <optimize_parameters>: Update network weights; it will be called in every training iteration.\n\"\"\"\n\nimport torch\nfrom .base_model import BaseModel\nfrom . import networks\n\n\nclass TemplateModel(BaseModel):\n    @staticmethod\n    def modify_commandline_options(parser, is_train=True):\n        \"\"\"Add new model-specific options and rewrite default values for existing options.\n\n        Parameters:\n            parser -- the option parser\n            is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n        \"\"\"\n        parser.set_defaults(dataset_mode=\"aligned\")  # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset.\n        if is_train:\n            parser.add_argument(\"--lambda_regression\", type=float, default=1.0, help=\"weight for the regression loss\")  # You can define new arguments for this model.\n\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize this model class.\n\n        Parameters:\n            opt -- training/test options\n\n        A few things can be done here.\n        - (required) call the initialization function of BaseModel\n        - define loss function, visualization images, model names, and optimizers\n        \"\"\"\n        BaseModel.__init__(self, opt)  # call the initialization method of BaseModel\n        # specify the training losses you want to print out. The program will call base_model.get_current_losses to plot the losses to the console and save them to the disk.\n        self.loss_names = [\"G\"]\n        # specify the images you want to save and display. The program will call base_model.get_current_visuals to save and display these images.\n        self.visual_names = [\"data_A\", \"data_B\", \"output\"]\n        # specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks to save and load networks.\n        # you can use opt.isTrain to specify different behaviors for training and test. For example, some networks will not be used during test, and you don't need to load them.\n        self.model_names = [\"G\"]\n        # define networks; you can use opt.isTrain to specify different behaviors for training and test.\n        self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG)\n        if self.isTrain:  # only defined during training time\n            # define your loss functions. You can use losses provided by torch.nn such as torch.nn.L1Loss.\n            # We also provide a GANLoss class \"networks.GANLoss\". self.criterionGAN = networks.GANLoss().to(self.device)\n            self.criterionLoss = torch.nn.L1Loss()\n            # define and initialize optimizers. You can define one optimizer for each network.\n            # If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.\n            self.optimizer = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\n            self.optimizers = [self.optimizer]\n\n        # Our program will automatically call <model.setup> to define schedulers, load networks, and print networks\n\n    def set_input(self, input):\n        \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n        Parameters:\n            input: a dictionary that contains the data itself and its metadata information.\n        \"\"\"\n        AtoB = self.opt.direction == \"AtoB\"  # use <direction> to swap data_A and data_B\n        self.data_A = input[\"A\" if AtoB else \"B\"].to(self.device)  # get image data A\n        self.data_B = input[\"B\" if AtoB else \"A\"].to(self.device)  # get image data B\n        self.image_paths = input[\"A_paths\" if AtoB else \"B_paths\"]  # get image paths\n\n    def forward(self):\n        \"\"\"Run forward pass. This will be called by both functions <optimize_parameters> and <test>.\"\"\"\n        self.output = self.netG(self.data_A)  # generate output image given the input data_A\n\n    def backward(self):\n        \"\"\"Calculate losses, gradients, and update network weights; called in every training iteration\"\"\"\n        # caculate the intermediate results if necessary; here self.output has been computed during function <forward>\n        # calculate loss given the input and intermediate results\n        self.loss_G = self.criterionLoss(self.output, self.data_B) * self.opt.lambda_regression\n        self.loss_G.backward()  # calculate gradients of network G w.r.t. loss_G\n\n    def optimize_parameters(self):\n        \"\"\"Update network weights; it will be called in every training iteration.\"\"\"\n        self.forward()  # first call forward to calculate intermediate results\n        self.optimizer.zero_grad()  # clear network G's existing gradients\n        self.backward()  # calculate gradients for network G\n        self.optimizer.step()  # update gradients for network G\n"
  },
  {
    "path": "models/test_model.py",
    "content": "from .base_model import BaseModel\nfrom . import networks\n\n\nclass TestModel(BaseModel):\n    \"\"\"This TesteModel can be used to generate CycleGAN results for only one direction.\n    This model will automatically set '--dataset_mode single', which only loads the images from one collection.\n\n    See the test instruction for more details.\n    \"\"\"\n\n    @staticmethod\n    def modify_commandline_options(parser, is_train=True):\n        \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n        Parameters:\n            parser          -- original option parser\n            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n        Returns:\n            the modified parser.\n\n        The model can only be used during test time. It requires '--dataset_mode single'.\n        You need to specify the network using the option '--model_suffix'.\n        \"\"\"\n        assert not is_train, \"TestModel cannot be used during training time\"\n        parser.set_defaults(dataset_mode=\"single\")\n        parser.add_argument(\"--model_suffix\", type=str, default=\"\", help=\"In checkpoints_dir, [epoch]_net_G[model_suffix].pth will be loaded as the generator.\")\n\n        return parser\n\n    def __init__(self, opt):\n        \"\"\"Initialize the pix2pix class.\n\n        Parameters:\n            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions\n        \"\"\"\n        assert not opt.isTrain\n        BaseModel.__init__(self, opt)\n        # specify the training losses you want to print out. The training/test scripts  will call <BaseModel.get_current_losses>\n        self.loss_names = []\n        # specify the images you want to save/display. The training/test scripts  will call <BaseModel.get_current_visuals>\n        self.visual_names = [\"real\", \"fake\"]\n        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>\n        self.model_names = [\"G\" + opt.model_suffix]  # only generator is needed.\n        self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain)\n\n        # assigns the model to self.netG_[suffix] so that it can be loaded\n        # please see <BaseModel.load_networks>\n        setattr(self, \"netG\" + opt.model_suffix, self.netG)  # store netG in self.\n\n    def set_input(self, input):\n        \"\"\"Unpack input data from the dataloader and perform necessary pre-processing steps.\n\n        Parameters:\n            input: a dictionary that contains the data itself and its metadata information.\n\n        We need to use 'single_dataset' dataset mode. It only load images from one domain.\n        \"\"\"\n        self.real = input[\"A\"].to(self.device)\n        self.image_paths = input[\"A_paths\"]\n\n    def forward(self):\n        \"\"\"Run forward pass.\"\"\"\n        self.fake = self.netG(self.real)  # G(real)\n\n    def optimize_parameters(self):\n        \"\"\"No optimization for test model.\"\"\"\n        pass\n"
  },
  {
    "path": "options/__init__.py",
    "content": "\"\"\"This package options includes option modules: training options, test options, and basic options (used in both training and test).\"\"\"\n"
  },
  {
    "path": "options/base_options.py",
    "content": "import argparse\nfrom pathlib import Path\nfrom util import util\nimport torch\nimport models\nimport data\n\n\nclass BaseOptions:\n    \"\"\"This class defines options used during both training and test time.\n\n    It also implements several helper functions such as parsing, printing, and saving the options.\n    It also gathers additional options defined in <modify_commandline_options> functions in both dataset class and model class.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Reset the class; indicates the class hasn't been initailized\"\"\"\n        self.initialized = False\n\n    def initialize(self, parser):\n        \"\"\"Define the common options that are used in both training and test.\"\"\"\n        # basic parameters\n        parser.add_argument(\"--dataroot\", required=True, help=\"path to images (should have subfolders trainA, trainB, valA, valB, etc)\")\n        parser.add_argument(\"--name\", type=str, default=\"experiment_name\", help=\"name of the experiment. It decides where to store samples and models\")\n        parser.add_argument(\"--checkpoints_dir\", type=str, default=\"./checkpoints\", help=\"models are saved here\")\n        # model parameters\n        parser.add_argument(\"--model\", type=str, default=\"cycle_gan\", help=\"chooses which model to use. [cycle_gan | pix2pix | test | colorization]\")\n        parser.add_argument(\"--input_nc\", type=int, default=3, help=\"# of input image channels: 3 for RGB and 1 for grayscale\")\n        parser.add_argument(\"--output_nc\", type=int, default=3, help=\"# of output image channels: 3 for RGB and 1 for grayscale\")\n        parser.add_argument(\"--ngf\", type=int, default=64, help=\"# of gen filters in the last conv layer\")\n        parser.add_argument(\"--ndf\", type=int, default=64, help=\"# of discrim filters in the first conv layer\")\n        parser.add_argument(\"--netD\", type=str, default=\"basic\", help=\"specify discriminator architecture [basic | n_layers | pixel]. The basic model is a 70x70 PatchGAN. n_layers allows you to specify the layers in the discriminator\")\n        parser.add_argument(\"--netG\", type=str, default=\"resnet_9blocks\", help=\"specify generator architecture [resnet_9blocks | resnet_6blocks | unet_256 | unet_128]\")\n        parser.add_argument(\"--n_layers_D\", type=int, default=3, help=\"only used if netD==n_layers\")\n        parser.add_argument(\"--norm\", type=str, default=\"instance\", help=\"instance normalization or batch normalization [instance | batch | none | syncbatch]\")\n        parser.add_argument(\"--init_type\", type=str, default=\"normal\", help=\"network initialization [normal | xavier | kaiming | orthogonal]\")\n        parser.add_argument(\"--init_gain\", type=float, default=0.02, help=\"scaling factor for normal, xavier and orthogonal.\")\n        parser.add_argument(\"--no_dropout\", action=\"store_true\", help=\"no dropout for the generator\")\n        # dataset parameters\n        parser.add_argument(\"--dataset_mode\", type=str, default=\"unaligned\", help=\"chooses how datasets are loaded. [unaligned | aligned | single | colorization]\")\n        parser.add_argument(\"--direction\", type=str, default=\"AtoB\", help=\"AtoB or BtoA\")\n        parser.add_argument(\"--serial_batches\", action=\"store_true\", help=\"if true, takes images in order to make batches, otherwise takes them randomly\")\n        parser.add_argument(\"--num_threads\", default=4, type=int, help=\"# threads for loading data\")\n        parser.add_argument(\"--batch_size\", type=int, default=1, help=\"input batch size\")\n        parser.add_argument(\"--load_size\", type=int, default=286, help=\"scale images to this size\")\n        parser.add_argument(\"--crop_size\", type=int, default=256, help=\"then crop to this size\")\n        parser.add_argument(\"--max_dataset_size\", type=int, default=float(\"inf\"), help=\"Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.\")\n        parser.add_argument(\"--preprocess\", type=str, default=\"resize_and_crop\", help=\"scaling and cropping of images at load time [resize_and_crop | crop | scale_width | scale_width_and_crop | none]\")\n        parser.add_argument(\"--no_flip\", action=\"store_true\", help=\"if specified, do not flip the images for data augmentation\")\n        parser.add_argument(\"--display_winsize\", type=int, default=256, help=\"display window size for both visdom and HTML\")\n        # additional parameters\n        parser.add_argument(\"--epoch\", type=str, default=\"latest\", help=\"which epoch to load? set to latest to use latest cached model\")\n        parser.add_argument(\"--load_iter\", type=int, default=\"0\", help=\"which iteration to load? if load_iter > 0, the code will load models by iter_[load_iter]; otherwise, the code will load models by [epoch]\")\n        parser.add_argument(\"--verbose\", action=\"store_true\", help=\"if specified, print more debugging information\")\n        parser.add_argument(\"--suffix\", default=\"\", type=str, help=\"customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{load_size}\")\n        # wandb parameters\n        parser.add_argument(\"--use_wandb\", action=\"store_true\", help=\"if specified, then init wandb logging\")\n        parser.add_argument(\"--wandb_project_name\", type=str, default=\"CycleGAN-and-pix2pix\", help=\"specify wandb project name\")\n        self.initialized = True\n        return parser\n\n    def gather_options(self):\n        \"\"\"Initialize our parser with basic options(only once).\n        Add additional model-specific and dataset-specific options.\n        These options are defined in the <modify_commandline_options> function\n        in model and dataset classes.\n        \"\"\"\n        if not self.initialized:  # check if it has been initialized\n            parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n            parser = self.initialize(parser)\n\n        # get the basic options\n        opt, _ = parser.parse_known_args()\n\n        # modify model-related parser options\n        model_name = opt.model\n        model_option_setter = models.get_option_setter(model_name)\n        parser = model_option_setter(parser, self.isTrain)\n        opt, _ = parser.parse_known_args()  # parse again with new defaults\n\n        # modify dataset-related parser options\n        dataset_name = opt.dataset_mode\n        dataset_option_setter = data.get_option_setter(dataset_name)\n        parser = dataset_option_setter(parser, self.isTrain)\n\n        # save and return the parser\n        self.parser = parser\n        return parser.parse_args()\n\n    def print_options(self, opt):\n        \"\"\"Print and save options\n\n        It will print both current options and default values(if different).\n        It will save options into a text file / [checkpoints_dir] / opt.txt\n        \"\"\"\n        message = \"\"\n        message += \"----------------- Options ---------------\\n\"\n        for k, v in sorted(vars(opt).items()):\n            comment = \"\"\n            default = self.parser.get_default(k)\n            if v != default:\n                comment = \"\\t[default: %s]\" % str(default)\n            message += \"{:>25}: {:<30}{}\\n\".format(str(k), str(v), comment)\n        message += \"----------------- End -------------------\"\n        print(message)\n\n        # save to the disk\n        expr_dir = Path(opt.checkpoints_dir) / opt.name\n        util.mkdirs(expr_dir)\n        file_name = expr_dir / f\"{opt.phase}_opt.txt\"\n        with open(file_name, \"wt\") as opt_file:\n            opt_file.write(message)\n            opt_file.write(\"\\n\")\n\n    def parse(self):\n        \"\"\"Parse our options, create checkpoints directory suffix, and set up gpu device.\"\"\"\n        opt = self.gather_options()\n        opt.isTrain = self.isTrain  # train or test\n\n        # process opt.suffix\n        if opt.suffix:\n            suffix = (\"_\" + opt.suffix.format(**vars(opt))) if opt.suffix != \"\" else \"\"\n            opt.name = opt.name + suffix\n\n        self.print_options(opt)\n        self.opt = opt\n        return self.opt\n"
  },
  {
    "path": "options/test_options.py",
    "content": "from .base_options import BaseOptions\n\n\nclass TestOptions(BaseOptions):\n    \"\"\"This class includes test options.\n\n    It also includes shared options defined in BaseOptions.\n    \"\"\"\n\n    def initialize(self, parser):\n        parser = BaseOptions.initialize(self, parser)  # define shared options\n        parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')\n        parser.add_argument('--aspect_ratio', type=float, default=1.0, help='aspect ratio of result images')\n        parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')\n        # Dropout and Batchnorm has different behavioir during training and test.\n        parser.add_argument('--eval', action='store_true', help='use eval mode during test time.')\n        parser.add_argument('--num_test', type=int, default=50, help='how many test images to run')\n        # rewrite devalue values\n        parser.set_defaults(model='test')\n        # To avoid cropping, the load_size should be the same as crop_size\n        parser.set_defaults(load_size=parser.get_default('crop_size'))\n        self.isTrain = False\n        return parser\n"
  },
  {
    "path": "options/train_options.py",
    "content": "from .base_options import BaseOptions\n\n\nclass TrainOptions(BaseOptions):\n    \"\"\"This class includes training options.\n\n    It also includes shared options defined in BaseOptions.\n    \"\"\"\n\n    def initialize(self, parser):\n        parser = BaseOptions.initialize(self, parser)\n        # HTML visualization parameters\n        parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen')\n        parser.add_argument('--update_html_freq', type=int, default=1000, help='frequency of saving training results to html')\n        parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console')\n        parser.add_argument('--no_html', action='store_true', help='do not save intermediate training results to [opt.checkpoints_dir]/[opt.name]/web/')\n        # network saving and loading parameters\n        parser.add_argument('--save_latest_freq', type=int, default=5000, help='frequency of saving the latest results')\n        parser.add_argument('--save_epoch_freq', type=int, default=5, help='frequency of saving checkpoints at the end of epochs')\n        parser.add_argument('--save_by_iter', action='store_true', help='whether saves model by iteration')\n        parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model')\n        parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')\n        parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')\n        # training parameters\n        parser.add_argument('--n_epochs', type=int, default=100, help='number of epochs with the initial learning rate')\n        parser.add_argument('--n_epochs_decay', type=int, default=100, help='number of epochs to linearly decay learning rate to zero')\n        parser.add_argument('--beta1', type=float, default=0.5, help='momentum term of adam')\n        parser.add_argument('--lr', type=float, default=0.0002, help='initial learning rate for adam')\n        parser.add_argument('--gan_mode', type=str, default='lsgan', help='the type of GAN objective. [vanilla| lsgan | wgangp]. vanilla GAN loss is the cross-entropy objective used in the original GAN paper.')\n        parser.add_argument('--pool_size', type=int, default=50, help='the size of image buffer that stores previously generated images')\n        parser.add_argument('--lr_policy', type=str, default='linear', help='learning rate policy. [linear | step | plateau | cosine]')\n        parser.add_argument('--lr_decay_iters', type=int, default=50, help='multiply by a gamma every lr_decay_iters iterations')\n\n        self.isTrain = True\n        return parser\n"
  },
  {
    "path": "pix2pix.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"view-in-github\"\n   },\n   \"source\": [\n    \"<a href=\\\"https://colab.research.google.com/github/bkkaggle/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"7wNjDKdQy35h\"\n   },\n   \"source\": [\n    \"# Install\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"TRm-USlsHgEV\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"Pt3igws3eiVp\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import os\\n\",\n    \"os.chdir('pytorch-CycleGAN-and-pix2pix/')\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"z1EySlOXwwoa\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!pip install -r requirements.txt\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"8daqlgVhw29P\"\n   },\n   \"source\": [\n    \"# Datasets\\n\",\n    \"\\n\",\n    \"Download one of the official datasets with:\\n\",\n    \"\\n\",\n    \"-   `bash ./datasets/download_pix2pix_dataset.sh [cityscapes, night2day, edges2handbags, edges2shoes, facades, maps]`\\n\",\n    \"\\n\",\n    \"Or use your own dataset by creating the appropriate folders and adding in the images. Follow the instructions [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/datasets.md#pix2pix-datasets).\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"vrdOettJxaCc\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!bash ./datasets/download_pix2pix_dataset.sh facades\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"gdUz4116xhpm\"\n   },\n   \"source\": [\n    \"# Pretrained models\\n\",\n    \"\\n\",\n    \"Download one of the official pretrained models with:\\n\",\n    \"\\n\",\n    \"-   `bash ./scripts/download_pix2pix_model.sh [edges2shoes, sat2map, map2sat, facades_label2photo, and day2night]`\\n\",\n    \"\\n\",\n    \"Or add your own pretrained model to `./checkpoints/{NAME}_pretrained/latest_net_G.pt`\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"GC2DEP4M0OsS\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!bash ./scripts/download_pix2pix_model.sh facades_label2photo\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"yFw1kDQBx3LN\"\n   },\n   \"source\": [\n    \"# Training\\n\",\n    \"\\n\",\n    \"-   `python train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA`\\n\",\n    \"\\n\",\n    \"Change the `--dataroot` and `--name` to your own dataset's path and model's name. Use `--gpu_ids 0,1,..` to train on multiple GPUs and `--batch_size` to change the batch size. Add `--direction BtoA` if you want to train a model to transfrom from class B to A.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"0sp7TCT2x9dB\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!python train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA --display_id -1\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"9UkcaFZiyASl\"\n   },\n   \"source\": [\n    \"# Testing\\n\",\n    \"\\n\",\n    \"-   `python test.py --dataroot ./datasets/facades --direction BtoA --model pix2pix --name facades_pix2pix`\\n\",\n    \"\\n\",\n    \"Change the `--dataroot`, `--name`, and `--direction` to be consistent with your trained model's configuration and how you want to transform images.\\n\",\n    \"\\n\",\n    \"> from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix:\\n\",\n    \"> Note that we specified --direction BtoA as Facades dataset's A to B direction is photos to labels.\\n\",\n    \"\\n\",\n    \"> If you would like to apply a pre-trained model to a collection of input images (rather than image pairs), please use --model test option. See ./scripts/test_single.sh for how to apply a model to Facade label maps (stored in the directory facades/testB).\\n\",\n    \"\\n\",\n    \"> See a list of currently available models at ./scripts/download_pix2pix_model.sh\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"mey7o6j-0368\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!ls checkpoints/\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"uCsKkEq0yGh0\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"!python test.py --dataroot ./datasets/facades --direction BtoA --model pix2pix --name facades_label2photo_pretrained --use_wandb\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"colab_type\": \"text\",\n    \"id\": \"OzSKIPUByfiN\"\n   },\n   \"source\": [\n    \"# Visualize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"9Mgg8raPyizq\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"import matplotlib.pyplot as plt\\n\",\n    \"\\n\",\n    \"img = plt.imread('./results/facades_label2photo_pretrained/test_latest/images/100_fake_B.png')\\n\",\n    \"plt.imshow(img)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"0G3oVH9DyqLQ\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"img = plt.imread('./results/facades_label2photo_pretrained/test_latest/images/100_real_A.png')\\n\",\n    \"plt.imshow(img)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"colab\": {},\n    \"colab_type\": \"code\",\n    \"id\": \"ErK5OC1j1LH4\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"img = plt.imread('./results/facades_label2photo_pretrained/test_latest/images/100_real_B.png')\\n\",\n    \"plt.imshow(img)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"accelerator\": \"GPU\",\n  \"colab\": {\n   \"collapsed_sections\": [],\n   \"include_colab_link\": true,\n   \"name\": \"pix2pix\",\n   \"provenance\": []\n  },\n  \"environment\": {\n   \"name\": \"tf2-gpu.2-3.m74\",\n   \"type\": \"gcloud\",\n   \"uri\": \"gcr.io/deeplearning-platform-release/tf2-gpu.2-3:m74\"\n  },\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.7.10\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"
  },
  {
    "path": "scripts/conda_deps.sh",
    "content": "set -ex\nconda install numpy pyyaml mkl mkl-include setuptools cmake cffi typing\nconda install pytorch torchvision -c pytorch # add cuda90 if CUDA 9\nconda install visdom dominate -c conda-forge # install visdom and dominate\n"
  },
  {
    "path": "scripts/download_cyclegan_model.sh",
    "content": "FILE=$1\n\necho \"Note: available models are apple2orange, orange2apple, summer2winter_yosemite, winter2summer_yosemite, horse2zebra, zebra2horse, monet2photo, style_monet, style_cezanne, style_ukiyoe, style_vangogh, sat2map, map2sat, cityscapes_photo2label, cityscapes_label2photo, facades_photo2label, facades_label2photo, iphone2dslr_flower\"\n\necho \"Specified [$FILE]\"\n\nmkdir -p ./checkpoints/${FILE}_pretrained\nMODEL_FILE=./checkpoints/${FILE}_pretrained/latest_net_G.pth\nURL=http://efrosgans.eecs.berkeley.edu/cyclegan/pretrained_models/$FILE.pth\n\nwget -N $URL -O $MODEL_FILE\n"
  },
  {
    "path": "scripts/download_pix2pix_model.sh",
    "content": "FILE=$1\n\necho \"Note: available models are edges2shoes, sat2map, map2sat, facades_label2photo, and day2night\"\necho \"Specified [$FILE]\"\n\nmkdir -p ./checkpoints/${FILE}_pretrained\nMODEL_FILE=./checkpoints/${FILE}_pretrained/latest_net_G.pth\nURL=http://efrosgans.eecs.berkeley.edu/pix2pix/models-pytorch/$FILE.pth\n\nwget -N $URL -O $MODEL_FILE\n"
  },
  {
    "path": "scripts/edges/PostprocessHED.m",
    "content": "%%% Prerequisites\n% You need to get the cpp file edgesNmsMex.cpp from https://raw.githubusercontent.com/pdollar/edges/master/private/edgesNmsMex.cpp\n% and compile it in Matlab: mex edgesNmsMex.cpp\n% You also need to download and install Piotr's Computer Vision Matlab Toolbox:  https://pdollar.github.io/toolbox/\n\n%%% parameters\n% hed_mat_dir: the hed mat file directory (the output of 'batch_hed.py')\n% edge_dir: the output HED edges directory\n% image_width: resize the edge map to [image_width, image_width]\n% threshold: threshold for image binarization (default 25.0/255.0)\n% small_edge: remove small edges (default 5)\n\nfunction [] = PostprocessHED(hed_mat_dir, edge_dir, image_width, threshold, small_edge)\n\nif ~exist(edge_dir, 'dir')\n    mkdir(edge_dir);\nend\nfileList = dir(fullfile(hed_mat_dir, '*.mat'));\nnFiles = numel(fileList);\nfprintf('find %d mat files\\n', nFiles);\n\nfor n = 1 : nFiles\n    if mod(n, 1000) == 0\n        fprintf('process %d/%d images\\n', n, nFiles);\n    end\n    fileName = fileList(n).name;\n    filePath = fullfile(hed_mat_dir, fileName);\n    jpgName = strrep(fileName, '.mat', '.jpg');\n    edge_path = fullfile(edge_dir, jpgName);\n\n    if ~exist(edge_path, 'file')\n        E = GetEdge(filePath);\n        E = imresize(E,[image_width,image_width]);\n        E_simple = SimpleEdge(E, threshold, small_edge);\n        E_simple = uint8(E_simple*255);\n        imwrite(E_simple, edge_path, 'Quality',100);\n    end\nend\nend\n\n\n\n\nfunction [E] = GetEdge(filePath)\nload(filePath);\nE = 1-edge_predict;\nend\n\nfunction [E4] = SimpleEdge(E, threshold, small_edge)\nif nargin <= 1\n    threshold = 25.0/255.0;\nend\n\nif nargin <= 2\n    small_edge = 5;\nend\n\nif ndims(E) == 3\n    E = E(:,:,1);\nend\n\nE1 = 1 - E;\nE2 = EdgeNMS(E1);\nE3 = double(E2>=max(eps,threshold));\nE3 = bwmorph(E3,'thin',inf);\nE4 = bwareaopen(E3, small_edge);\nE4=1-E4;\nend\n\nfunction [E_nms] = EdgeNMS( E )\nE=single(E);\n[Ox,Oy] = gradient2(convTri(E,4));\n[Oxx,~] = gradient2(Ox);\n[Oxy,Oyy] = gradient2(Oy);\nO = mod(atan(Oyy.*sign(-Oxy)./(Oxx+1e-5)),pi);\nE_nms = edgesNmsMex(E,O,1,5,1.01,1);\nend\n"
  },
  {
    "path": "scripts/edges/batch_hed.py",
    "content": "# HED batch processing script; modified from https://github.com/s9xie/hed/blob/master/examples/hed/HED-tutorial.ipynb\n# Step 1: download the hed repo: https://github.com/s9xie/hed\n# Step 2: download the models and protoxt, and put them under {caffe_root}/examples/hed/\n# Step 3: put this script under {caffe_root}/examples/hed/\n# Step 4: run the following script:\n#       python batch_hed.py --images_dir=/data/to/path/photos/ --hed_mat_dir=/data/to/path/hed_mat_files/\n# The code sometimes crashes after computation is done. Error looks like \"Check failed: ... driver shutting down\". You can just kill the job.\n# For large images, it will produce gpu memory issue. Therefore, you better resize the images before running this script.\n# Step 5: run the MATLAB post-processing script \"PostprocessHED.m\"\n\n\nimport caffe\nimport numpy as np\nfrom PIL import Image\nimport os\nimport argparse\nimport sys\nimport scipy.io as sio\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(description='batch proccesing: photos->edges')\n    parser.add_argument('--caffe_root', dest='caffe_root', help='caffe root', default='../../', type=str)\n    parser.add_argument('--caffemodel', dest='caffemodel', help='caffemodel', default='./hed_pretrained_bsds.caffemodel', type=str)\n    parser.add_argument('--prototxt', dest='prototxt', help='caffe prototxt file', default='./deploy.prototxt', type=str)\n    parser.add_argument('--images_dir', dest='images_dir', help='directory to store input photos', type=str)\n    parser.add_argument('--hed_mat_dir', dest='hed_mat_dir', help='directory to store output hed edges in mat file', type=str)\n    parser.add_argument('--border', dest='border', help='padding border', type=int, default=128)\n    parser.add_argument('--gpu_id', dest='gpu_id', help='gpu id', type=int, default=1)\n    args = parser.parse_args()\n    return args\n\n\nargs = parse_args()\nfor arg in vars(args):\n    print('[%s] =' % arg, getattr(args, arg))\n# Make sure that caffe is on the python path:\ncaffe_root = args.caffe_root   # this file is expected to be in {caffe_root}/examples/hed/\nsys.path.insert(0, caffe_root + 'python')\n\n\nif not os.path.exists(args.hed_mat_dir):\n    print('create output directory %s' % args.hed_mat_dir)\n    os.makedirs(args.hed_mat_dir)\n\nimgList = os.listdir(args.images_dir)\nnImgs = len(imgList)\nprint('#images = %d' % nImgs)\n\ncaffe.set_mode_gpu()\ncaffe.set_device(args.gpu_id)\n# load net\nnet = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)\n# pad border\nborder = args.border\n\nfor i in range(nImgs):\n    if i % 500 == 0:\n        print('processing image %d/%d' % (i, nImgs))\n    im = Image.open(os.path.join(args.images_dir, imgList[i]))\n\n    in_ = np.array(im, dtype=np.float32)\n    in_ = np.pad(in_, ((border, border), (border, border), (0, 0)), 'reflect')\n\n    in_ = in_[:, :, 0:3]\n    in_ = in_[:, :, ::-1]\n    in_ -= np.array((104.00698793, 116.66876762, 122.67891434))\n    in_ = in_.transpose((2, 0, 1))\n    # remove the following two lines if testing with cpu\n\n    # shape for input (data blob is N x C x H x W), set data\n    net.blobs['data'].reshape(1, *in_.shape)\n    net.blobs['data'].data[...] = in_\n    # run net and take argmax for prediction\n    net.forward()\n    fuse = net.blobs['sigmoid-fuse'].data[0][0, :, :]\n    # get rid of the border\n    fuse = fuse[(border + 35):(-border + 35), (border + 35):(-border + 35)]\n    # save hed file to the disk\n    name, ext = os.path.splitext(imgList[i])\n    sio.savemat(os.path.join(args.hed_mat_dir, name + '.mat'), {'edge_predict': fuse})\n"
  },
  {
    "path": "scripts/eval_cityscapes/caffemodel/deploy.prototxt",
    "content": "layer {\n  name: \"data\"\n  type: \"Input\"\n  top: \"data\"\n  input_param {\n    shape {\n      dim: 1\n      dim: 3\n      dim: 500\n      dim: 500\n    }\n  }\n}\nlayer {\n  name: \"conv1_1\"\n  type: \"Convolution\"\n  bottom: \"data\"\n  top: \"conv1_1\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 64\n    pad: 100\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu1_1\"\n  type: \"ReLU\"\n  bottom: \"conv1_1\"\n  top: \"conv1_1\"\n}\nlayer {\n  name: \"conv1_2\"\n  type: \"Convolution\"\n  bottom: \"conv1_1\"\n  top: \"conv1_2\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 64\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu1_2\"\n  type: \"ReLU\"\n  bottom: \"conv1_2\"\n  top: \"conv1_2\"\n}\nlayer {\n  name: \"pool1\"\n  type: \"Pooling\"\n  bottom: \"conv1_2\"\n  top: \"pool1\"\n  pooling_param {\n    pool: MAX\n    kernel_size: 2\n    stride: 2\n  }\n}\nlayer {\n  name: \"conv2_1\"\n  type: \"Convolution\"\n  bottom: \"pool1\"\n  top: \"conv2_1\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 128\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu2_1\"\n  type: \"ReLU\"\n  bottom: \"conv2_1\"\n  top: \"conv2_1\"\n}\nlayer {\n  name: \"conv2_2\"\n  type: \"Convolution\"\n  bottom: \"conv2_1\"\n  top: \"conv2_2\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 128\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu2_2\"\n  type: \"ReLU\"\n  bottom: \"conv2_2\"\n  top: \"conv2_2\"\n}\nlayer {\n  name: \"pool2\"\n  type: \"Pooling\"\n  bottom: \"conv2_2\"\n  top: \"pool2\"\n  pooling_param {\n    pool: MAX\n    kernel_size: 2\n    stride: 2\n  }\n}\nlayer {\n  name: \"conv3_1\"\n  type: \"Convolution\"\n  bottom: \"pool2\"\n  top: \"conv3_1\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 256\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu3_1\"\n  type: \"ReLU\"\n  bottom: \"conv3_1\"\n  top: \"conv3_1\"\n}\nlayer {\n  name: \"conv3_2\"\n  type: \"Convolution\"\n  bottom: \"conv3_1\"\n  top: \"conv3_2\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 256\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu3_2\"\n  type: \"ReLU\"\n  bottom: \"conv3_2\"\n  top: \"conv3_2\"\n}\nlayer {\n  name: \"conv3_3\"\n  type: \"Convolution\"\n  bottom: \"conv3_2\"\n  top: \"conv3_3\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 256\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu3_3\"\n  type: \"ReLU\"\n  bottom: \"conv3_3\"\n  top: \"conv3_3\"\n}\nlayer {\n  name: \"pool3\"\n  type: \"Pooling\"\n  bottom: \"conv3_3\"\n  top: \"pool3\"\n  pooling_param {\n    pool: MAX\n    kernel_size: 2\n    stride: 2\n  }\n}\nlayer {\n  name: \"conv4_1\"\n  type: \"Convolution\"\n  bottom: \"pool3\"\n  top: \"conv4_1\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 512\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu4_1\"\n  type: \"ReLU\"\n  bottom: \"conv4_1\"\n  top: \"conv4_1\"\n}\nlayer {\n  name: \"conv4_2\"\n  type: \"Convolution\"\n  bottom: \"conv4_1\"\n  top: \"conv4_2\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 512\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu4_2\"\n  type: \"ReLU\"\n  bottom: \"conv4_2\"\n  top: \"conv4_2\"\n}\nlayer {\n  name: \"conv4_3\"\n  type: \"Convolution\"\n  bottom: \"conv4_2\"\n  top: \"conv4_3\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 512\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu4_3\"\n  type: \"ReLU\"\n  bottom: \"conv4_3\"\n  top: \"conv4_3\"\n}\nlayer {\n  name: \"pool4\"\n  type: \"Pooling\"\n  bottom: \"conv4_3\"\n  top: \"pool4\"\n  pooling_param {\n    pool: MAX\n    kernel_size: 2\n    stride: 2\n  }\n}\nlayer {\n  name: \"conv5_1\"\n  type: \"Convolution\"\n  bottom: \"pool4\"\n  top: \"conv5_1\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 512\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu5_1\"\n  type: \"ReLU\"\n  bottom: \"conv5_1\"\n  top: \"conv5_1\"\n}\nlayer {\n  name: \"conv5_2\"\n  type: \"Convolution\"\n  bottom: \"conv5_1\"\n  top: \"conv5_2\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 512\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu5_2\"\n  type: \"ReLU\"\n  bottom: \"conv5_2\"\n  top: \"conv5_2\"\n}\nlayer {\n  name: \"conv5_3\"\n  type: \"Convolution\"\n  bottom: \"conv5_2\"\n  top: \"conv5_3\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 512\n    pad: 1\n    kernel_size: 3\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu5_3\"\n  type: \"ReLU\"\n  bottom: \"conv5_3\"\n  top: \"conv5_3\"\n}\nlayer {\n  name: \"pool5\"\n  type: \"Pooling\"\n  bottom: \"conv5_3\"\n  top: \"pool5\"\n  pooling_param {\n    pool: MAX\n    kernel_size: 2\n    stride: 2\n  }\n}\nlayer {\n  name: \"fc6_cs\"\n  type: \"Convolution\"\n  bottom: \"pool5\"\n  top: \"fc6_cs\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 4096\n    pad: 0\n    kernel_size: 7\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu6_cs\"\n  type: \"ReLU\"\n  bottom: \"fc6_cs\"\n  top: \"fc6_cs\"\n}\nlayer {\n  name: \"fc7_cs\"\n  type: \"Convolution\"\n  bottom: \"fc6_cs\"\n  top: \"fc7_cs\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 4096\n    pad: 0\n    kernel_size: 1\n    stride: 1\n    weight_filler {\n      type: \"gaussian\"\n      std: 0.01\n    }\n    bias_filler {\n      type: \"constant\"\n      value: 0\n    }\n  }\n}\nlayer {\n  name: \"relu7_cs\"\n  type: \"ReLU\"\n  bottom: \"fc7_cs\"\n  top: \"fc7_cs\"\n}\nlayer {\n  name: \"score_fr\"\n  type: \"Convolution\"\n  bottom: \"fc7_cs\"\n  top: \"score_fr\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 20\n    pad: 0\n    kernel_size: 1\n    weight_filler {\n      type: \"xavier\"\n    }\n    bias_filler {\n      type: \"constant\"\n    }\n  }\n}\nlayer {\n  name: \"upscore2\"\n  type: \"Deconvolution\"\n  bottom: \"score_fr\"\n  top: \"upscore2\"\n  param {\n    lr_mult: 1\n  }\n  convolution_param {\n    num_output: 20\n    bias_term: false\n    kernel_size: 4\n    stride: 2\n    weight_filler {\n      type: \"xavier\"\n    }\n    bias_filler {\n      type: \"constant\"\n    }\n  }\n}\nlayer {\n  name: \"score_pool4\"\n  type: \"Convolution\"\n  bottom: \"pool4\"\n  top: \"score_pool4\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 20\n    pad: 0\n    kernel_size: 1\n    weight_filler {\n      type: \"xavier\"\n    }\n    bias_filler {\n      type: \"constant\"\n    }\n  }\n}\nlayer {\n  name: \"score_pool4c\"\n  type: \"Crop\"\n  bottom: \"score_pool4\"\n  bottom: \"upscore2\"\n  top: \"score_pool4c\"\n  crop_param {\n    axis: 2\n    offset: 5\n  }\n}\nlayer {\n  name: \"fuse_pool4\"\n  type: \"Eltwise\"\n  bottom: \"upscore2\"\n  bottom: \"score_pool4c\"\n  top: \"fuse_pool4\"\n  eltwise_param {\n    operation: SUM\n  }\n}\nlayer {\n  name: \"upscore_pool4\"\n  type: \"Deconvolution\"\n  bottom: \"fuse_pool4\"\n  top: \"upscore_pool4\"\n  param {\n    lr_mult: 1\n  }\n  convolution_param {\n    num_output: 20\n    bias_term: false\n    kernel_size: 4\n    stride: 2\n    weight_filler {\n      type: \"xavier\"\n    }\n    bias_filler {\n      type: \"constant\"\n    }\n  }\n}\nlayer {\n  name: \"score_pool3\"\n  type: \"Convolution\"\n  bottom: \"pool3\"\n  top: \"score_pool3\"\n  param {\n    lr_mult: 1\n    decay_mult: 1\n  }\n  param {\n    lr_mult: 2\n    decay_mult: 0\n  }\n  convolution_param {\n    num_output: 20\n    pad: 0\n    kernel_size: 1\n    weight_filler {\n      type: \"xavier\"\n    }\n    bias_filler {\n      type: \"constant\"\n    }\n  }\n}\nlayer {\n  name: \"score_pool3c\"\n  type: \"Crop\"\n  bottom: \"score_pool3\"\n  bottom: \"upscore_pool4\"\n  top: \"score_pool3c\"\n  crop_param {\n    axis: 2\n    offset: 9\n  }\n}\nlayer {\n  name: \"fuse_pool3\"\n  type: \"Eltwise\"\n  bottom: \"upscore_pool4\"\n  bottom: \"score_pool3c\"\n  top: \"fuse_pool3\"\n  eltwise_param {\n    operation: SUM\n  }\n}\nlayer {\n  name: \"upscore8\"\n  type: \"Deconvolution\"\n  bottom: \"fuse_pool3\"\n  top: \"upscore8\"\n  param {\n    lr_mult: 1\n  }\n  convolution_param {\n    num_output: 20\n    bias_term: false\n    kernel_size: 16\n    stride: 8\n    weight_filler {\n      type: \"xavier\"\n    }\n    bias_filler {\n      type: \"constant\"\n    }\n  }\n}\nlayer {\n  name: \"score\"\n  type: \"Crop\"\n  bottom: \"upscore8\"\n  bottom: \"data\"\n  top: \"score\"\n  crop_param {\n    axis: 2\n    offset: 31\n  }\n}\n"
  },
  {
    "path": "scripts/eval_cityscapes/cityscapes.py",
    "content": "# The following code is modified from https://github.com/shelhamer/clockwork-fcn\nimport sys\nimport os\nimport glob\nimport numpy as np\nfrom PIL import Image\n\n\nclass cityscapes:\n    def __init__(self, data_path):\n        # data_path something like /data2/cityscapes\n        self.dir = data_path\n        self.classes = ['road', 'sidewalk', 'building', 'wall', 'fence',\n                        'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain',\n                        'sky', 'person', 'rider', 'car', 'truck',\n                        'bus', 'train', 'motorcycle', 'bicycle']\n        self.mean = np.array((72.78044, 83.21195, 73.45286), dtype=np.float32)\n        # import cityscapes label helper and set up label mappings\n        sys.path.insert(0, '{}/scripts/helpers/'.format(self.dir))\n        labels = __import__('labels')\n        self.id2trainId = {label.id: label.trainId for label in labels.labels}  # dictionary mapping from raw IDs to train IDs\n        self.trainId2color = {label.trainId: label.color for label in labels.labels}  # dictionary mapping train IDs to colors as 3-tuples\n\n    def get_dset(self, split):\n        '''\n        List images as (city, id) for the specified split\n\n        TODO(shelhamer) generate splits from cityscapes itself, instead of\n        relying on these separately made text files.\n        '''\n        if split == 'train':\n            dataset = open('{}/ImageSets/segFine/train.txt'.format(self.dir)).read().splitlines()\n        else:\n            dataset = open('{}/ImageSets/segFine/val.txt'.format(self.dir)).read().splitlines()\n        return [(item.split('/')[0], item.split('/')[1]) for item in dataset]\n\n    def load_image(self, split, city, idx):\n        im = Image.open('{}/leftImg8bit_sequence/{}/{}/{}_leftImg8bit.png'.format(self.dir, split, city, idx))\n        return im\n\n    def assign_trainIds(self, label):\n        \"\"\"\n        Map the given label IDs to the train IDs appropriate for training\n        Use the label mapping provided in labels.py from the cityscapes scripts\n        \"\"\"\n        label = np.array(label, dtype=np.float32)\n        if sys.version_info[0] < 3:\n            for k, v in self.id2trainId.iteritems():\n                label[label == k] = v\n        else:\n            for k, v in self.id2trainId.items():\n                label[label == k] = v\n        return label\n\n    def load_label(self, split, city, idx):\n        \"\"\"\n        Load label image as 1 x height x width integer array of label indices.\n        The leading singleton dimension is required by the loss.\n        \"\"\"\n        label = Image.open('{}/gtFine/{}/{}/{}_gtFine_labelIds.png'.format(self.dir, split, city, idx))\n        label = self.assign_trainIds(label)  # get proper labels for eval\n        label = np.array(label, dtype=np.uint8)\n        label = label[np.newaxis, ...]\n        return label\n\n    def preprocess(self, im):\n        \"\"\"\n        Preprocess loaded image (by load_image) for Caffe:\n        - cast to float\n        - switch channels RGB -> BGR\n        - subtract mean\n        - transpose to channel x height x width order\n        \"\"\"\n        in_ = np.array(im, dtype=np.float32)\n        in_ = in_[:, :, ::-1]\n        in_ -= self.mean\n        in_ = in_.transpose((2, 0, 1))\n        return in_\n\n    def palette(self, label):\n        '''\n        Map trainIds to colors as specified in labels.py\n        '''\n        if label.ndim == 3:\n            label = label[0]\n        color = np.empty((label.shape[0], label.shape[1], 3))\n        if sys.version_info[0] < 3:\n            for k, v in self.trainId2color.iteritems():\n                color[label == k, :] = v\n        else:\n            for k, v in self.trainId2color.items():\n                color[label == k, :] = v\n        return color\n\n    def make_boundaries(label, thickness=None):\n        \"\"\"\n        Input is an image label, output is a numpy array mask encoding the boundaries of the objects\n        Extract pixels at the true boundary by dilation - erosion of label.\n        Don't just pick the void label as it is not exclusive to the boundaries.\n        \"\"\"\n        assert(thickness is not None)\n        import skimage.morphology as skm\n        void = 255\n        mask = np.logical_and(label > 0, label != void)[0]\n        selem = skm.disk(thickness)\n        boundaries = np.logical_xor(skm.dilation(mask, selem),\n                                    skm.erosion(mask, selem))\n        return boundaries\n\n    def list_label_frames(self, split):\n        \"\"\"\n        Select labeled frames from a split for evaluation\n        collected as (city, shot, idx) tuples\n        \"\"\"\n        def file2idx(f):\n            \"\"\"Helper to convert file path into frame ID\"\"\"\n            city, shot, frame = (os.path.basename(f).split('_')[:3])\n            return \"_\".join([city, shot, frame])\n        frames = []\n        cities = [os.path.basename(f) for f in glob.glob('{}/gtFine/{}/*'.format(self.dir, split))]\n        for c in cities:\n            files = sorted(glob.glob('{}/gtFine/{}/{}/*labelIds.png'.format(self.dir, split, c)))\n            frames.extend([file2idx(f) for f in files])\n        return frames\n\n    def collect_frame_sequence(self, split, idx, length):\n        \"\"\"\n        Collect sequence of frames preceding (and including) a labeled frame\n        as a list of Images.\n\n        Note: 19 preceding frames are provided for each labeled frame.\n        \"\"\"\n        SEQ_LEN = length\n        city, shot, frame = idx.split('_')\n        frame = int(frame)\n        frame_seq = []\n        for i in range(frame - SEQ_LEN, frame + 1):\n            frame_path = '{0}/leftImg8bit_sequence/val/{1}/{1}_{2}_{3:0>6d}_leftImg8bit.png'.format(\n                self.dir, city, shot, i)\n            frame_seq.append(Image.open(frame_path))\n        return frame_seq\n"
  },
  {
    "path": "scripts/eval_cityscapes/download_fcn8s.sh",
    "content": "URL=http://efrosgans.eecs.berkeley.edu/pix2pix_extra/fcn-8s-cityscapes.caffemodel\nOUTPUT_FILE=./scripts/eval_cityscapes/caffemodel/fcn-8s-cityscapes.caffemodel\nwget -N $URL -O $OUTPUT_FILE\n"
  },
  {
    "path": "scripts/eval_cityscapes/evaluate.py",
    "content": "import os\nimport caffe\nimport argparse\nimport numpy as np\nimport scipy.misc\nfrom PIL import Image\nfrom util import segrun, fast_hist, get_scores\nfrom cityscapes import cityscapes\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--cityscapes_dir\", type=str, required=True, help=\"Path to the original cityscapes dataset\")\nparser.add_argument(\"--result_dir\", type=str, required=True, help=\"Path to the generated images to be evaluated\")\nparser.add_argument(\"--output_dir\", type=str, required=True, help=\"Where to save the evaluation results\")\nparser.add_argument(\"--caffemodel_dir\", type=str, default='./scripts/eval_cityscapes/caffemodel/', help=\"Where the FCN-8s caffemodel stored\")\nparser.add_argument(\"--gpu_id\", type=int, default=0, help=\"Which gpu id to use\")\nparser.add_argument(\"--split\", type=str, default='val', help=\"Data split to be evaluated\")\nparser.add_argument(\"--save_output_images\", type=int, default=0, help=\"Whether to save the FCN output images\")\nargs = parser.parse_args()\n\n\ndef main():\n    if not os.path.isdir(args.output_dir):\n        os.makedirs(args.output_dir)\n    if args.save_output_images > 0:\n        output_image_dir = args.output_dir + 'image_outputs/'\n        if not os.path.isdir(output_image_dir):\n            os.makedirs(output_image_dir)\n    CS = cityscapes(args.cityscapes_dir)\n    n_cl = len(CS.classes)\n    label_frames = CS.list_label_frames(args.split)\n    caffe.set_device(args.gpu_id)\n    caffe.set_mode_gpu()\n    net = caffe.Net(args.caffemodel_dir + '/deploy.prototxt',\n                    args.caffemodel_dir + 'fcn-8s-cityscapes.caffemodel',\n                    caffe.TEST)\n\n    hist_perframe = np.zeros((n_cl, n_cl))\n    for i, idx in enumerate(label_frames):\n        if i % 10 == 0:\n            print('Evaluating: %d/%d' % (i, len(label_frames)))\n        city = idx.split('_')[0]\n        # idx is city_shot_frame\n        label = CS.load_label(args.split, city, idx)\n        im_file = args.result_dir + '/' + idx + '_leftImg8bit.png'\n        im = np.array(Image.open(im_file))\n        im = scipy.misc.imresize(im, (label.shape[1], label.shape[2]))\n        # im = np.array(Image.fromarray(im).resize((label.shape[1], label.shape[2])))  # Note: scipy.misc.imresize is deprecated, but we still use it for reproducibility.\n        out = segrun(net, CS.preprocess(im))\n        hist_perframe += fast_hist(label.flatten(), out.flatten(), n_cl)\n        if args.save_output_images > 0:\n            label_im = CS.palette(label)\n            pred_im = CS.palette(out)\n            scipy.misc.imsave(output_image_dir + '/' + str(i) + '_pred.jpg', pred_im)\n            scipy.misc.imsave(output_image_dir + '/' + str(i) + '_gt.jpg', label_im)\n            scipy.misc.imsave(output_image_dir + '/' + str(i) + '_input.jpg', im)\n\n    mean_pixel_acc, mean_class_acc, mean_class_iou, per_class_acc, per_class_iou = get_scores(hist_perframe)\n    with open(args.output_dir + '/evaluation_results.txt', 'w') as f:\n        f.write('Mean pixel accuracy: %f\\n' % mean_pixel_acc)\n        f.write('Mean class accuracy: %f\\n' % mean_class_acc)\n        f.write('Mean class IoU: %f\\n' % mean_class_iou)\n        f.write('************ Per class numbers below ************\\n')\n        for i, cl in enumerate(CS.classes):\n            while len(cl) < 15:\n                cl = cl + ' '\n            f.write('%s: acc = %f, iou = %f\\n' % (cl, per_class_acc[i], per_class_iou[i]))\n\n\nmain()\n"
  },
  {
    "path": "scripts/eval_cityscapes/util.py",
    "content": "# The following code is modified from https://github.com/shelhamer/clockwork-fcn\nimport numpy as np\n\n\ndef get_out_scoremap(net):\n    return net.blobs['score'].data[0].argmax(axis=0).astype(np.uint8)\n\n\ndef feed_net(net, in_):\n    \"\"\"\n    Load prepared input into net.\n    \"\"\"\n    net.blobs['data'].reshape(1, *in_.shape)\n    net.blobs['data'].data[...] = in_\n\n\ndef segrun(net, in_):\n    feed_net(net, in_)\n    net.forward()\n    return get_out_scoremap(net)\n\n\ndef fast_hist(a, b, n):\n    k = np.where((a >= 0) & (a < n))[0]\n    bc = np.bincount(n * a[k].astype(int) + b[k], minlength=n**2)\n    if len(bc) != n**2:\n        # ignore this example if dimension mismatch\n        return 0\n    return bc.reshape(n, n)\n\n\ndef get_scores(hist):\n    # Mean pixel accuracy\n    acc = np.diag(hist).sum() / (hist.sum() + 1e-12)\n\n    # Per class accuracy\n    cl_acc = np.diag(hist) / (hist.sum(1) + 1e-12)\n\n    # Per class IoU\n    iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist) + 1e-12)\n\n    return acc, np.nanmean(cl_acc), np.nanmean(iu), cl_acc, iu\n"
  },
  {
    "path": "scripts/install_deps.sh",
    "content": "set -ex\npip install visdom\npip install dominate\n"
  },
  {
    "path": "scripts/test_before_push.py",
    "content": "import pytest\nimport os\nimport subprocess\nfrom pathlib import Path\n\n\nclass TestBeforePush:\n    \"\"\"Test suite to ensure basic functionality works before pushing code.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_datasets(self):\n        \"\"\"Download required mini datasets if they don't exist.\"\"\"\n        if not Path(\"./datasets/mini\").exists():\n            subprocess.run([\"bash\", \"./datasets/download_cyclegan_dataset.sh\", \"mini\"], check=True)\n        \n        if not Path(\"./datasets/mini_pix2pix\").exists():\n            subprocess.run([\"bash\", \"./datasets/download_cyclegan_dataset.sh\", \"mini_pix2pix\"], check=True)\n        \n        if not Path(\"./datasets/mini_colorization\").exists():\n            subprocess.run([\"bash\", \"./datasets/download_cyclegan_dataset.sh\", \"mini_colorization\"], check=True)\n\n    def test_pretrained_cyclegan_model(self):\n        \"\"\"Test pretrained CycleGAN model download and inference.\"\"\"\n        if not Path(\"./checkpoints/horse2zebra_pretrained/latest_net_G.pth\").exists():\n            subprocess.run([\"bash\", \"./scripts/download_cyclegan_model.sh\", \"horse2zebra\"], check=True)\n        \n        result = subprocess.run([\n            \"python\", \"test.py\", \"--model\", \"test\", \"--dataroot\", \"./datasets/mini\",\n            \"--name\", \"horse2zebra_pretrained\", \"--no_dropout\", \"--num_test\", \"1\"\n        ], capture_output=True, text=True)\n        \n        assert result.returncode == 0, f\"CycleGAN test failed: {result.stderr}\"\n\n    def test_pretrained_pix2pix_model(self):\n        \"\"\"Test pretrained pix2pix model download and inference.\"\"\"\n        if not Path(\"./checkpoints/facades_label2photo_pretrained/latest_net_G.pth\").exists():\n            subprocess.run([\"bash\", \"./scripts/download_pix2pix_model.sh\", \"facades_label2photo\"], check=True)\n        \n        if not Path(\"./datasets/facades\").exists():\n            subprocess.run([\"bash\", \"./datasets/download_pix2pix_dataset.sh\", \"facades\"], check=True)\n        \n        result = subprocess.run([\n            \"python\", \"test.py\", \"--dataroot\", \"./datasets/facades/\", \"--direction\", \"BtoA\",\n            \"--model\", \"pix2pix\", \"--name\", \"facades_label2photo_pretrained\", \"--num_test\", \"1\"\n        ], capture_output=True, text=True)\n        \n        assert result.returncode == 0, f\"Pix2pix test failed: {result.stderr}\"\n\n    def test_cyclegan_train_test(self):\n        \"\"\"Test CycleGAN training and testing pipeline.\"\"\"\n        # Train\n        train_result = subprocess.run([\n            \"python\", \"train.py\", \"--model\", \"cycle_gan\", \"--name\", \"temp_cyclegan\",\n            \"--dataroot\", \"./datasets/mini\", \"--n_epochs\", \"1\", \"--n_epochs_decay\", \"0\",\n            \"--save_latest_freq\", \"10\", \"--print_freq\", \"1\"\n        ], capture_output=True, text=True)\n        \n        assert train_result.returncode == 0, f\"CycleGAN training failed: {train_result.stderr}\"\n        \n        # Test\n        test_result = subprocess.run([\n            \"python\", \"test.py\", \"--model\", \"test\", \"--name\", \"temp_cyclegan\",\n            \"--dataroot\", \"./datasets/mini\", \"--num_test\", \"1\", \"--model_suffix\", \"_A\", \"--no_dropout\"\n        ], capture_output=True, text=True)\n        \n        assert test_result.returncode == 0, f\"CycleGAN testing failed: {test_result.stderr}\"\n\n    def test_pix2pix_train_test(self):\n        \"\"\"Test pix2pix training and testing pipeline.\"\"\"\n        # Train\n        train_result = subprocess.run([\n            \"python\", \"train.py\", \"--model\", \"pix2pix\", \"--name\", \"temp_pix2pix\",\n            \"--dataroot\", \"./datasets/mini_pix2pix\", \"--n_epochs\", \"1\", \"--n_epochs_decay\", \"5\",\n            \"--save_latest_freq\", \"10\"\n        ], capture_output=True, text=True)\n        \n        assert train_result.returncode == 0, f\"Pix2pix training failed: {train_result.stderr}\"\n        \n        # Test\n        test_result = subprocess.run([\n            \"python\", \"test.py\", \"--model\", \"pix2pix\", \"--name\", \"temp_pix2pix\",\n            \"--dataroot\", \"./datasets/mini_pix2pix\", \"--num_test\", \"1\"\n        ], capture_output=True, text=True)\n        \n        assert test_result.returncode == 0, f\"Pix2pix testing failed: {test_result.stderr}\"\n\n    def test_template_train_test(self):\n        \"\"\"Test template model training and testing.\"\"\"\n        # Train\n        train_result = subprocess.run([\n            \"python\", \"train.py\", \"--model\", \"template\", \"--name\", \"temp2\",\n            \"--dataroot\", \"./datasets/mini_pix2pix\", \"--n_epochs\", \"1\", \"--n_epochs_decay\", \"0\",\n            \"--save_latest_freq\", \"10\"\n        ], capture_output=True, text=True)\n        \n        assert train_result.returncode == 0, f\"Template training failed: {train_result.stderr}\"\n        \n        # Test\n        test_result = subprocess.run([\n            \"python\", \"test.py\", \"--model\", \"template\", \"--name\", \"temp2\",\n            \"--dataroot\", \"./datasets/mini_pix2pix\", \"--num_test\", \"1\"\n        ], capture_output=True, text=True)\n        \n        assert test_result.returncode == 0, f\"Template testing failed: {test_result.stderr}\"\n\n    def test_colorization_train_test(self):\n        \"\"\"Test colorization model training and testing.\"\"\"\n        # Train\n        train_result = subprocess.run([\n            \"python\", \"train.py\", \"--model\", \"colorization\", \"--name\", \"temp_color\",\n            \"--dataroot\", \"./datasets/mini_colorization\", \"--n_epochs\", \"1\", \"--n_epochs_decay\", \"0\",\n            \"--save_latest_freq\", \"5\"\n        ], capture_output=True, text=True)\n        \n        assert train_result.returncode == 0, f\"Colorization training failed: {train_result.stderr}\"\n        \n        # Test\n        test_result = subprocess.run([\n            \"python\", \"test.py\", \"--model\", \"colorization\", \"--name\", \"temp_color\",\n            \"--dataroot\", \"./datasets/mini_colorization\", \"--num_test\", \"1\"\n        ], capture_output=True, text=True)\n        \n        assert test_result.returncode == 0, f\"Colorization testing failed: {test_result.stderr}\"\n"
  },
  {
    "path": "scripts/test_colorization.sh",
    "content": "set -ex\npython test.py --dataroot ./datasets/colorization --name color_pix2pix --model colorization\n"
  },
  {
    "path": "scripts/test_cyclegan.sh",
    "content": "set -ex\npython test.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan --phase test --no_dropout\n"
  },
  {
    "path": "scripts/test_pix2pix.sh",
    "content": "set -ex\npython test.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --netG unet_256 --direction BtoA --dataset_mode aligned --norm batch\n"
  },
  {
    "path": "scripts/test_single.sh",
    "content": "set -ex\npython test.py --dataroot ./datasets/facades/testB/ --name facades_pix2pix --model test --netG unet_256 --direction BtoA --dataset_mode single --norm batch\n"
  },
  {
    "path": "scripts/train_colorization.sh",
    "content": "set -ex\npython train.py --dataroot ./datasets/colorization --name color_pix2pix --model colorization  --use_wandb\n```\n"
  },
  {
    "path": "scripts/train_cyclegan.sh",
    "content": "set -ex\npython train.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan --pool_size 50 --no_dropout  --use_wandb\n```\n"
  },
  {
    "path": "scripts/train_pix2pix.sh",
    "content": "set -ex\npython train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --netG unet_256 --direction BtoA --lambda_L1 100 --dataset_mode aligned --norm batch --pool_size 0  --use_wandb\n```\n"
  },
  {
    "path": "test.py",
    "content": "\"\"\"General-purpose test script for image-to-image translation.\n\nOnce you have trained your model with train.py, you can use this script to test the model.\nIt will load a saved model from '--checkpoints_dir' and save the results to '--results_dir'.\n\nIt first creates model and dataset given the option. It will hard-code some parameters.\nIt then runs inference for '--num_test' images and save results to an HTML file.\n\nExample (You need to train models first or download pre-trained models from our website):\n    Test a CycleGAN model (both sides):\n        python test.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan\n\n    Test a CycleGAN model (one side only):\n        python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout\n\n    The option '--model test' is used for generating CycleGAN results only for one side.\n    This option will automatically set '--dataset_mode single', which only loads the images from one set.\n    On the contrary, using '--model cycle_gan' requires loading and generating results in both directions,\n    which is sometimes unnecessary. The results will be saved at ./results/.\n    Use '--results_dir <directory_path_to_save_result>' to specify the results directory.\n\n    Test a pix2pix model:\n        python test.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA\n\nSee options/base_options.py and options/test_options.py for more test options.\nSee training and test tips at: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md\nSee frequently asked questions at: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md\n\"\"\"\n\nimport os\nfrom pathlib import Path\nfrom options.test_options import TestOptions\nfrom data import create_dataset\nfrom models import create_model\nfrom util.visualizer import save_images\nfrom util import html\nimport torch\n\ntry:\n    import wandb\nexcept ImportError:\n    print('Warning: wandb package cannot be found. The option \"--use_wandb\" will result in error.')\n\n\nif __name__ == \"__main__\":\n    opt = TestOptions().parse()  # get test options\n    opt.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n    # hard-code some parameters for test\n    opt.num_threads = 0  # test code only supports num_threads = 0\n    opt.batch_size = 1  # test code only supports batch_size = 1\n    opt.serial_batches = True  # disable data shuffling; comment this line if results on randomly chosen images are needed.\n    opt.no_flip = True  # no flip; comment this line if results on flipped images are needed.\n    \n    dataset = create_dataset(opt)  # create a dataset given opt.dataset_mode and other options\n    model = create_model(opt)  # create a model given opt.model and other options\n    model.setup(opt)  # regular setup: load and print networks; create schedulers\n\n    # create a website\n    web_dir = Path(opt.results_dir) / opt.name / f\"{opt.phase}_{opt.epoch}\"  # define the website directory\n    if opt.load_iter > 0:  # load_iter is 0 by default\n        web_dir = Path(f\"{web_dir}_iter{opt.load_iter}\")\n    print(f\"creating web directory {web_dir}\")\n    webpage = html.HTML(web_dir, f\"Experiment = {opt.name}, Phase = {opt.phase}, Epoch = {opt.epoch}\")\n    # test with eval mode. This only affects layers like batchnorm and dropout.\n    # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode.\n    # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout.\n    if opt.eval:\n        model.eval()\n    for i, data in enumerate(dataset):\n        if i >= opt.num_test:  # only apply our model to opt.num_test images.\n            break\n        model.set_input(data)  # unpack data from data loader\n        model.test()  # run inference\n        visuals = model.get_current_visuals()  # get image results\n        img_path = model.get_image_paths()  # get image paths\n        if i % 5 == 0:  # save images to an HTML file\n            print(f\"processing ({i:04d})-th image... {img_path}\")\n        save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize)\n    webpage.save()  # save the HTML\n"
  },
  {
    "path": "train.py",
    "content": "\"\"\"General-purpose training script for image-to-image translation.\n\nThis script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and\ndifferent datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization).\nYou need to specify the dataset ('--dataroot'), experiment name ('--name'), and model ('--model').\n\nIt first creates model, dataset, and visualizer given the option.\nIt then does standard network training. During the training, it also visualize/save the images, print/save the loss plot, and save models.\nThe script supports continue/resume training. Use '--continue_train' to resume your previous training.\n\nExample:\n    Train a CycleGAN model:\n        python train.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan\n    Train a pix2pix model:\n        python train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA\n\nSee options/base_options.py and options/train_options.py for more training options.\nSee training and test tips at: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md\nSee frequently asked questions at: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md\n\"\"\"\n\nimport time\nfrom options.train_options import TrainOptions\nfrom data import create_dataset\nfrom models import create_model\nfrom util.visualizer import Visualizer\nfrom util.util import init_ddp, cleanup_ddp\n\n\nif __name__ == \"__main__\":\n    opt = TrainOptions().parse()  # get training options\n    opt.device = init_ddp()\n    dataset = create_dataset(opt)  # create a dataset given opt.dataset_mode and other options\n    dataset_size = len(dataset)  # get the number of images in the dataset.\n    print(f\"The number of training images = {dataset_size}\")\n\n    model = create_model(opt)  # create a model given opt.model and other options\n    model.setup(opt)  # regular setup: load and print networks; create schedulers\n    visualizer = Visualizer(opt)  # create a visualizer that display/save images and plots\n    total_iters = 0  # the total number of training iterations\n    for epoch in range(opt.epoch_count, opt.n_epochs + opt.n_epochs_decay + 1):\n        epoch_start_time = time.time()  # timer for entire epoch\n        iter_data_time = time.time()  # timer for data loading per iteration\n        epoch_iter = 0  # the number of training iterations in current epoch, reset to 0 every epoch\n        visualizer.reset()\n        # Set epoch for DistributedSampler\n        if hasattr(dataset, \"set_epoch\"):\n            dataset.set_epoch(epoch)\n\n        for i, data in enumerate(dataset):  # inner loop within one epoch\n            iter_start_time = time.time()  # timer for computation per iteration\n            if total_iters % opt.print_freq == 0:\n                t_data = iter_start_time - iter_data_time\n\n            total_iters += opt.batch_size\n            epoch_iter += opt.batch_size\n            model.set_input(data)  # unpack data from dataset and apply preprocessing\n            model.optimize_parameters()  # calculate loss functions, get gradients, update network weights\n\n            if total_iters % opt.display_freq == 0:  # display images on visdom and save images to a HTML file\n                save_result = total_iters % opt.update_html_freq == 0\n                model.compute_visuals()\n                visualizer.display_current_results(model.get_current_visuals(), epoch, total_iters, save_result)\n\n            if total_iters % opt.print_freq == 0:  # print training losses and save logging information to the disk\n                losses = model.get_current_losses()\n                t_comp = (time.time() - iter_start_time) / opt.batch_size\n                visualizer.print_current_losses(epoch, epoch_iter, losses, t_comp, t_data)\n                visualizer.plot_current_losses(total_iters, losses)\n\n            if total_iters % opt.save_latest_freq == 0:  # cache our latest model every <save_latest_freq> iterations\n                print(f\"saving the latest model (epoch {epoch}, total_iters {total_iters})\")\n                save_suffix = f\"iter_{total_iters}\" if opt.save_by_iter else \"latest\"\n                model.save_networks(save_suffix)\n\n            iter_data_time = time.time()\n\n        model.update_learning_rate()  # update learning rates at the end of every epoch\n\n        if epoch % opt.save_epoch_freq == 0:  # cache our model every <save_epoch_freq> epochs\n            print(f\"saving the model at the end of epoch {epoch}, iters {total_iters}\")\n            model.save_networks(\"latest\")\n            model.save_networks(epoch)\n\n        print(f\"End of epoch {epoch} / {opt.n_epochs + opt.n_epochs_decay} \\t Time Taken: {time.time() - epoch_start_time:.0f} sec\")\n\n    cleanup_ddp()\n"
  },
  {
    "path": "util/__init__.py",
    "content": "\"\"\"This package includes a miscellaneous collection of useful helper functions.\"\"\"\n"
  },
  {
    "path": "util/get_data.py",
    "content": "from __future__ import print_function\nfrom pathlib import Path\nimport tarfile\nimport requests\nfrom warnings import warn\nfrom zipfile import ZipFile\nfrom bs4 import BeautifulSoup\n\n\nclass GetData(object):\n    \"\"\"A Python script for downloading CycleGAN or pix2pix datasets.\n\n    Parameters:\n        technique (str) -- One of: 'cyclegan' or 'pix2pix'.\n        verbose (bool)  -- If True, print additional information.\n\n    Examples:\n        >>> from util.get_data import GetData\n        >>> gd = GetData(technique='cyclegan')\n        >>> new_data_path = gd.get(save_path='./datasets')  # options will be displayed.\n\n    Alternatively, You can use bash scripts: 'scripts/download_pix2pix_model.sh'\n    and 'scripts/download_cyclegan_model.sh'.\n    \"\"\"\n\n    def __init__(self, technique=\"cyclegan\", verbose=True):\n        url_dict = {\n            \"pix2pix\": \"http://efrosgans.eecs.berkeley.edu/pix2pix/datasets/\",\n            \"cyclegan\": \"http://efrosgans.eecs.berkeley.edu/pix2pix/datasets\",\n        }\n        self.url = url_dict.get(technique.lower())\n        self._verbose = verbose\n\n    def _print(self, text):\n        if self._verbose:\n            print(text)\n\n    @staticmethod\n    def _get_options(r):\n        soup = BeautifulSoup(r.text, \"lxml\")\n        options = [h.text for h in soup.find_all(\"a\", href=True) if h.text.endswith((\".zip\", \"tar.gz\"))]\n        return options\n\n    def _present_options(self):\n        r = requests.get(self.url)\n        options = self._get_options(r)\n        print(\"Options:\\n\")\n        for i, o in enumerate(options):\n            print(\"{0}: {1}\".format(i, o))\n        choice = input(\"\\nPlease enter the number of the \" \"dataset above you wish to download:\")\n        return options[int(choice)]\n\n    def _download_data(self, dataset_url, save_path):\n        save_path = Path(save_path)\n        if not save_path.is_dir():\n            save_path.mkdir(parents=True, exist_ok=True)\n\n        base = Path(dataset_url).name\n        temp_save_path = save_path / base\n\n        with open(temp_save_path, \"wb\") as f:\n            r = requests.get(dataset_url)\n            f.write(r.content)\n\n        if base.endswith(\".tar.gz\"):\n            obj = tarfile.open(temp_save_path)\n        elif base.endswith(\".zip\"):\n            obj = ZipFile(temp_save_path, \"r\")\n        else:\n            raise ValueError(\"Unknown File Type: {0}.\".format(base))\n\n        self._print(\"Unpacking Data...\")\n        obj.extractall(save_path)\n        obj.close()\n        temp_save_path.unlink()\n\n    def get(self, save_path, dataset=None):\n        \"\"\"\n\n        Download a dataset.\n\n        Parameters:\n            save_path (str) -- A directory to save the data to.\n            dataset (str)   -- (optional). A specific dataset to download.\n                            Note: this must include the file extension.\n                            If None, options will be presented for you\n                            to choose from.\n\n        Returns:\n            save_path_full (str) -- the absolute path to the downloaded data.\n\n        \"\"\"\n        if dataset is None:\n            selected_dataset = self._present_options()\n        else:\n            selected_dataset = dataset\n\n        save_path_full = Path(save_path) / selected_dataset.split(\".\")[0]\n\n        if save_path_full.is_dir():\n            warn(f\"\\n'{save_path_full}' already exists. Voiding Download.\")\n        else:\n            self._print(\"Downloading Data...\")\n            url = f\"{self.url}/{selected_dataset}\"\n            self._download_data(url, save_path=save_path)\n\n        return save_path_full.resolve()\n"
  },
  {
    "path": "util/html.py",
    "content": "import dominate\nfrom dominate.tags import meta, h3, table, tr, td, p, a, img, br\nfrom pathlib import Path\n\n\nclass HTML:\n    \"\"\"This HTML class allows us to save images and write texts into a single HTML file.\n\n    It consists of functions such as <add_header> (add a text header to the HTML file),\n    <add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk).\n    It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API.\n    \"\"\"\n\n    def __init__(self, web_dir, title, refresh=0):\n        \"\"\"Initialize the HTML classes\n\n        Parameters:\n            web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/\n            title (str)   -- the webpage name\n            refresh (int) -- how often the website refresh itself; if 0; no refreshing\n        \"\"\"\n        self.title = title\n        self.web_dir = Path(web_dir)\n        self.img_dir = self.web_dir / \"images\"\n\n        self.web_dir.mkdir(parents=True, exist_ok=True)\n        self.img_dir.mkdir(parents=True, exist_ok=True)\n\n        self.doc = dominate.document(title=title)\n        if refresh > 0:\n            with self.doc.head:\n                meta(http_equiv=\"refresh\", content=str(refresh))\n\n    def get_image_dir(self):\n        \"\"\"Return the directory that stores images\"\"\"\n        return self.img_dir\n\n    def add_header(self, text):\n        \"\"\"Insert a header to the HTML file\n\n        Parameters:\n            text (str) -- the header text\n        \"\"\"\n        with self.doc:\n            h3(text)\n\n    def add_images(self, ims, txts, links, width=400):\n        \"\"\"add images to the HTML file\n\n        Parameters:\n            ims (str list)   -- a list of image paths\n            txts (str list)  -- a list of image names shown on the website\n            links (str list) --  a list of hyperref links; when you click an image, it will redirect you to a new page\n        \"\"\"\n        self.t = table(border=1, style=\"table-layout: fixed;\")  # Insert a table\n        self.doc.add(self.t)\n        with self.t:\n            with tr():\n                for im, txt, link in zip(ims, txts, links):\n                    with td(style=\"word-wrap: break-word;\", halign=\"center\", valign=\"top\"):\n                        with p():\n                            with a(href=Path(\"images\") / link):\n                                img(style=f\"width:{width}px\", src=Path(\"images\") / im)\n                            br()\n                            p(txt)\n\n    def save(self):\n        \"\"\"save the current content to the HMTL file\"\"\"\n        html_file = self.web_dir / \"index.html\"\n        with open(html_file, \"wt\") as f:\n            f.write(self.doc.render())\n\n\nif __name__ == \"__main__\":  # we show an example usage here.\n    html = HTML(\"web/\", \"test_html\")\n    html.add_header(\"hello world\")\n\n    ims, txts, links = [], [], []\n    for n in range(4):\n        ims.append(f\"image_{n}.png\")\n        txts.append(f\"text_{n}\")\n        links.append(f\"image_{n}.png\")\n    html.add_images(ims, txts, links)\n    html.save()\n"
  },
  {
    "path": "util/image_pool.py",
    "content": "import random\nimport torch\n\n\nclass ImagePool:\n    \"\"\"This class implements an image buffer that stores previously generated images.\n\n    This buffer enables us to update discriminators using a history of generated images\n    rather than the ones produced by the latest generators.\n    \"\"\"\n\n    def __init__(self, pool_size):\n        \"\"\"Initialize the ImagePool class\n\n        Parameters:\n            pool_size (int) -- the size of image buffer, if pool_size=0, no buffer will be created\n        \"\"\"\n        self.pool_size = pool_size\n        if self.pool_size > 0:  # create an empty pool\n            self.num_imgs = 0\n            self.images = []\n\n    def query(self, images):\n        \"\"\"Return an image from the pool.\n\n        Parameters:\n            images: the latest generated images from the generator\n\n        Returns images from the buffer.\n\n        By 50/100, the buffer will return input images.\n        By 50/100, the buffer will return images previously stored in the buffer,\n        and insert the current images to the buffer.\n        \"\"\"\n        if self.pool_size == 0:  # if the buffer size is 0, do nothing\n            return images\n        return_images = []\n        for image in images:\n            image = torch.unsqueeze(image.data, 0)\n            if self.num_imgs < self.pool_size:  # if the buffer is not full; keep inserting current images to the buffer\n                self.num_imgs = self.num_imgs + 1\n                self.images.append(image)\n                return_images.append(image)\n            else:\n                p = random.uniform(0, 1)\n                if p > 0.5:  # by 50% chance, the buffer will return a previously stored image, and insert the current image into the buffer\n                    random_id = random.randint(0, self.pool_size - 1)  # randint is inclusive\n                    tmp = self.images[random_id].clone()\n                    self.images[random_id] = image\n                    return_images.append(tmp)\n                else:  # by another 50% chance, the buffer will return the current image\n                    return_images.append(image)\n        return_images = torch.cat(return_images, 0)  # collect all the images and return\n        return return_images\n"
  },
  {
    "path": "util/util.py",
    "content": "\"\"\"This module contains simple helper functions\"\"\"\n\nfrom __future__ import print_function\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom pathlib import Path\nimport torch.distributed as dist\nimport os\n\n\ndef tensor2im(input_image, imtype=np.uint8):\n    \"\"\" \"Converts a Tensor array into a numpy image array.\n\n    Parameters:\n        input_image (tensor) --  the input image tensor array\n        imtype (type)        --  the desired type of the converted numpy array\n    \"\"\"\n    if not isinstance(input_image, np.ndarray):\n        if isinstance(input_image, torch.Tensor):  # get the data from a variable\n            image_tensor = input_image.data\n        else:\n            return input_image\n        image_numpy = image_tensor[0].cpu().float().numpy()  # convert it into a numpy array\n        if image_numpy.shape[0] == 1:  # grayscale to RGB\n            image_numpy = np.tile(image_numpy, (3, 1, 1))\n        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0  # post-processing: tranpose and scaling\n    else:  # if it is a numpy array, do nothing\n        image_numpy = input_image\n    return image_numpy.astype(imtype)\n\n\ndef diagnose_network(net, name=\"network\"):\n    \"\"\"Calculate and print the mean of average absolute(gradients)\n\n    Parameters:\n        net (torch network) -- Torch network\n        name (str) -- the name of the network\n    \"\"\"\n    mean = 0.0\n    count = 0\n    for param in net.parameters():\n        if param.grad is not None:\n            mean += torch.mean(torch.abs(param.grad.data))\n            count += 1\n    if count > 0:\n        mean = mean / count\n    print(name)\n    print(mean)\n\n\n# initialize ddp\ndef init_ddp():\n    # Initialize DDP if LOCAL_RANK is set\n    is_ddp = \"WORLD_SIZE\" in os.environ and int(os.environ[\"WORLD_SIZE\"]) > 1\n\n    if is_ddp:\n        if not dist.is_initialized():\n            dist.init_process_group(backend=\"nccl\")\n        local_rank = int(os.environ[\"LOCAL_RANK\"])\n        device = torch.device(f\"cuda:{local_rank}\")\n        torch.cuda.set_device(local_rank)\n    elif torch.cuda.is_available():\n        device = torch.device(\"cuda:0\")\n        torch.cuda.set_device(0)\n    else:\n        device = torch.device(\"cpu\")\n    print(f\"Initialized with device {device}\")\n    return device\n\n\n# cleanup ddp\ndef cleanup_ddp():\n    if dist.is_initialized():\n        dist.destroy_process_group()\n\n\ndef save_image(image_numpy, image_path, aspect_ratio=1.0):\n    \"\"\"Save a numpy image to the disk\n\n    Parameters:\n        image_numpy (numpy array) -- input numpy array\n        image_path (str)          -- the path of the image\n    \"\"\"\n\n    image_pil = Image.fromarray(image_numpy)\n    h, w, _ = image_numpy.shape\n\n    if aspect_ratio > 1.0:\n        image_pil = image_pil.resize((h, int(w * aspect_ratio)), Image.BICUBIC)\n    if aspect_ratio < 1.0:\n        image_pil = image_pil.resize((int(h / aspect_ratio), w), Image.BICUBIC)\n    image_pil.save(image_path)\n\n\ndef print_numpy(x, val=True, shp=False):\n    \"\"\"Print the mean, min, max, median, std, and size of a numpy array\n\n    Parameters:\n        val (bool) -- if print the values of the numpy array\n        shp (bool) -- if print the shape of the numpy array\n    \"\"\"\n    x = x.astype(np.float64)\n    if shp:\n        print(\"shape,\", x.shape)\n    if val:\n        x = x.flatten()\n        print(\"mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f\" % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))\n\n\ndef mkdirs(paths):\n    \"\"\"create empty directories if they don't exist\n\n    Parameters:\n        paths (str list) -- a list of directory paths\n    \"\"\"\n    if isinstance(paths, list) and not isinstance(paths, str):\n        for path in paths:\n            mkdir(path)\n    else:\n        mkdir(paths)\n\n\ndef mkdir(path):\n    \"\"\"create a single empty directory if it didn't exist\n\n    Parameters:\n        path (str) -- a single directory path\n    \"\"\"\n    Path(path).mkdir(parents=True, exist_ok=True)\n"
  },
  {
    "path": "util/visualizer.py",
    "content": "import numpy as np\nimport sys\nimport ntpath\nimport time\nfrom . import util, html\nfrom pathlib import Path\nimport wandb\nimport os\nimport torch.distributed as dist\n\n\ndef save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256):\n    \"\"\"Save images to the disk.\n\n    Parameters:\n        webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)\n        visuals (OrderedDict)    -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs\n        image_path (str)         -- the string is used to create image paths\n        aspect_ratio (float)     -- the aspect ratio of saved images\n        width (int)              -- the images will be resized to width x width\n\n    This function will save images stored in 'visuals' to the HTML file specified by 'webpage'.\n    \"\"\"\n    image_dir = webpage.get_image_dir()\n    name = Path(image_path[0]).stem\n\n    webpage.add_header(name)\n    ims, txts, links = [], [], []\n    for label, im_data in visuals.items():\n        im = util.tensor2im(im_data)\n        image_name = f\"{name}_{label}.png\"\n        save_path = image_dir / image_name\n        util.save_image(im, save_path, aspect_ratio=aspect_ratio)\n        ims.append(image_name)\n        txts.append(label)\n        links.append(image_name)\n    webpage.add_images(ims, txts, links, width=width)\n\n\nclass Visualizer:\n    \"\"\"This class includes several functions that can display/save images and print/save logging information.\n\n    It uses wandb for logging (optional) and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.\n    \"\"\"\n\n    def __init__(self, opt):\n        \"\"\"Initialize the Visualizer class\n\n        Parameters:\n            opt -- stores all the experiment flags; needs to be a subclass of BaseOptions\n        Step 1: Cache the training/test options\n        Step 2: Initialize wandb (if enabled)\n        Step 3: create an HTML object for saving HTML files\n        Step 4: create a logging file to store training losses\n        \"\"\"\n        self.opt = opt  # cache the option\n        self.use_html = opt.isTrain and not opt.no_html\n        self.win_size = opt.display_winsize\n        self.name = opt.name\n        self.saved = False\n        self.use_wandb = opt.use_wandb\n        self.current_epoch = 0\n\n        # Initialize wandb if enabled\n        if self.use_wandb:\n            # Only initialize wandb on main process (rank 0)\n            if not dist.is_initialized() or dist.get_rank() == 0:\n                self.wandb_project_name = getattr(opt, \"wandb_project_name\", \"CycleGAN-and-pix2pix\")\n                self.wandb_run = wandb.init(project=self.wandb_project_name, name=opt.name, config=opt) if not wandb.run else wandb.run\n                self.wandb_run._label(repo=\"CycleGAN-and-pix2pix\")\n            else:\n                self.wandb_run = None\n\n        if self.use_html:  # create an HTML object at <checkpoints_dir>/web/; images will be saved under <checkpoints_dir>/web/images/\n            self.web_dir = Path(opt.checkpoints_dir) / opt.name / \"web\"\n            self.img_dir = self.web_dir / \"images\"\n            print(f\"create web directory {self.web_dir}...\")\n            util.mkdirs([self.web_dir, self.img_dir])\n        # create a logging file to store training losses\n        self.log_name = Path(opt.checkpoints_dir) / opt.name / \"loss_log.txt\"\n        with open(self.log_name, \"a\") as log_file:\n            now = time.strftime(\"%c\")\n            log_file.write(f\"================ Training Loss ({now}) ================\\n\")\n\n    def reset(self):\n        \"\"\"Reset the self.saved status\"\"\"\n        self.saved = False\n\n    def set_dataset_size(self, dataset_size):\n        \"\"\"Set the dataset size for global step calculation\"\"\"\n        self.dataset_size = dataset_size\n\n    def _calculate_global_step(self, epoch, epoch_iter):\n        \"\"\"Calculate global step from epoch and epoch_iter\"\"\"\n        # Assuming epoch starts from 1 and epoch_iter is cumulative within epoch\n        return (epoch - 1) * self.dataset_size + epoch_iter\n\n    def display_current_results(self, visuals, epoch: int, total_iters: int, save_result=False):\n        \"\"\"Save current results to wandb and HTML file.\"\"\"\n        # Only display results on main process (rank 0)\n        if \"LOCAL_RANK\" in os.environ and dist.is_initialized() and dist.get_rank() != 0:\n            return\n\n        if self.use_wandb:\n            ims_dict = {}\n            for label, image in visuals.items():\n                image_numpy = util.tensor2im(image)\n                wandb_image = wandb.Image(image_numpy, caption=f\"{label} - Step {total_iters}\")\n                ims_dict[f\"results/{label}\"] = wandb_image\n            self.wandb_run.log(ims_dict, step=total_iters)\n\n        if self.use_html and (save_result or not self.saved):  # save images to an HTML file if they haven't been saved.\n            self.saved = True\n            # save images to the disk\n            for label, image in visuals.items():\n                image_numpy = util.tensor2im(image)\n                img_path = self.img_dir / f\"epoch{epoch:03d}_{label}.png\"\n                util.save_image(image_numpy, img_path)\n\n            # update website\n            webpage = html.HTML(self.web_dir, f\"Experiment name = {self.name}\", refresh=1)\n            for n in range(epoch, 0, -1):\n                webpage.add_header(f\"epoch [{n}]\")\n                ims, txts, links = [], [], []\n\n                for label, image in visuals.items():\n                    img_path = f\"epoch{n:03d}_{label}.png\"\n                    ims.append(img_path)\n                    txts.append(label)\n                    links.append(img_path)\n                webpage.add_images(ims, txts, links, width=self.win_size)\n            webpage.save()\n\n    def plot_current_losses(self, total_iters, losses):\n        \"\"\"Log current losses to wandb\n\n        Parameters:\n            total_iters (int)     -- current training iteration during this epoch\n            losses (OrderedDict)  -- training losses stored in the format of (name, float) pairs\n        \"\"\"\n        # Only plot losses on main process (rank 0)\n        if dist.is_initialized() and dist.get_rank() != 0:\n            return\n\n        if self.use_wandb:\n            self.wandb_run.log(losses, step=total_iters)\n\n    def print_current_losses(self, epoch, iters, losses, t_comp, t_data):\n        \"\"\"print current losses on console; also save the losses to the disk\n\n        Parameters:\n            epoch (int) -- current epoch\n            iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)\n            losses (OrderedDict) -- training losses stored in the format of (name, float) pairs\n            t_comp (float) -- computational time per data point (normalized by batch_size)\n            t_data (float) -- data loading time per data point (normalized by batch_size)\n        \"\"\"\n        local_rank = int(os.environ.get(\"LOCAL_RANK\", 0))\n        message = f\"[Rank {local_rank}] (epoch: {epoch}, iters: {iters}, time: {t_comp:.3f}, data: {t_data:.3f}) \"\n        for k, v in losses.items():\n            message += f\", {k}: {v:.3f}\"\n        message += \"\\n\"\n        print(message)  # print the message on ALL ranks with rank info\n\n        # Only save to log file on main process (rank 0)\n        if local_rank == 0:\n            with open(self.log_name, \"a\") as log_file:\n                log_file.write(f\"{message}\\n\")  # save the message\n"
  }
]