{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Resource:\n\n* [CS109B Data Science 2(Harvard) Generative Adversarial Networks (GANs) Vincent Casser, Pavlos Protopapas](https://harvard-iacs.github.io/2019-CS109B/a-sections/a-section8/presentation/cs109b_asec8_slides_gan.pdf)\n* [How to Develop a CycleGAN for Image-to-Image Translation with Keras](https://machinelearningmastery.com/cyclegan-tutorial-with-keras/)\n* [Image2Art Translation Using CycleGAN](https://sahiltinky94.medium.com/image2art-translation-using-cyclegan-e1bc096b7315)\n* [Transforming the World Into Paintings with CycleGAN](https://medium.com/analytics-vidhya/transforming-the-world-into-paintings-with-cyclegan-6748c0b85632)\n* [Tensorflow CycleGAN](https://www.tensorflow.org/tutorials/generative/cyclegan)\n* [Keras CycleGAN](https://keras.io/examples/generative/cyclegan/)  \n* [CycleGAN-Tensorflow-2](https://github.com/LynnHo/CycleGAN-Tensorflow-2)  ","metadata":{}},{"cell_type":"code","source":"import os, random, time, math, datetime, glob, sys, warnings\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras.optimizers import Adam, SGD, RMSprop\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, LeakyReLU, Concatenate, Input,  ReLU, Layer, Dropout, ZeroPadding2D\nfrom tensorflow_addons.layers import InstanceNormalization\nimport tensorflow_addons as tfa\nimport tensorflow.keras as keras\n\nAUTO = tf.data.experimental.AUTOTUNE \nwarnings.filterwarnings(\"ignore\")","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:08.057557Z","iopub.execute_input":"2021-10-05T12:43:08.057954Z","iopub.status.idle":"2021-10-05T12:43:08.067725Z","shell.execute_reply.started":"2021-10-05T12:43:08.057917Z","shell.execute_reply":"2021-10-05T12:43:08.066563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\nexcept ValueError:\n    tpu = None\n    gpus = tf.config.experimental.list_logical_devices(\"GPU\")\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\n    print('Running on TPU ', tpu.master())  \nelif len(gpus) > 0:\n    strategy = tf.distribute.MirroredStrategy(gpus)\n    print('Running on ', len(gpus), ' GPU(s) ')\nelse:\n    strategy = tf.distribute.get_strategy()\n    print('Running on CPU')\nprint(\"Number of accelerators: \", strategy.num_replicas_in_sync)","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:08.069636Z","iopub.execute_input":"2021-10-05T12:43:08.069933Z","iopub.status.idle":"2021-10-05T12:43:19.032839Z","shell.execute_reply.started":"2021-10-05T12:43:08.069882Z","shell.execute_reply":"2021-10-05T12:43:19.032178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('gan-getting-started') \nMONET_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH+'/monet_jpg/*.jpg') # monet_tfrec monet_jpg\nPHOTO_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH+'/photo_jpg/*.jpg') # photo_tfrec photo_jpg\n\nrandom.shuffle(MONET_FILENAMES)\nrandom.shuffle(PHOTO_FILENAMES)\n\nPHOTO_FILENAMES_TFREC = tf.io.gfile.glob(GCS_DS_PATH+'/photo_tfrec/*.tfrec')\nMONET_FILENAMES_TFREC = tf.io.gfile.glob(GCS_DS_PATH+'/monet_tfrec/*.tfrec')\n\nrandom.shuffle(PHOTO_FILENAMES_TFREC)\nrandom.shuffle(MONET_FILENAMES_TFREC)\n\nBATCH_SIZE = 1 * strategy.num_replicas_in_sync\nSTEPS_PER_EPOCH = 200\nEPOCHS = 150\n\nBUFFER_SIZE = 300\nIMAGE_HEIGHT = 256\nIMAGE_WIDTH  = 256\n\nDATA_SIZE = BATCH_SIZE*STEPS_PER_EPOCH\nIMAGE_SIZE = [IMAGE_HEIGHT, IMAGE_WIDTH]\nSAVE_FREQ = STEPS_PER_EPOCH * int(EPOCHS*0.2)\nif K.image_data_format() == 'channels_first':\n    SHAPE = (3,*IMAGE_SIZE)\nelse:\n    SHAPE = (*IMAGE_SIZE, 3)\n    \nDIM = 64  # 64\nSIZE = 4 # 4\nEPSILON = 1e-12 # 1e-5\nSTART_LEARNING_RATE=5e-4\nSTART_LEARNING_RATE_DISC=3e-4","metadata":{"execution":{"iopub.status.busy":"2021-10-05T12:43:19.033987Z","iopub.execute_input":"2021-10-05T12:43:19.034675Z","iopub.status.idle":"2021-10-05T12:43:20.393801Z","shell.execute_reply.started":"2021-10-05T12:43:19.034639Z","shell.execute_reply":"2021-10-05T12:43:20.392845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = (tf.cast(image, tf.float32) / 127.5) - 1\n    return tf.reshape(image, SHAPE)\n\n@tf.function\ndef _map_fn(img):  # preprocessing\n    img = tf.image.resize(img, [286, 286])  # or img = tf.image.resize(img, [load_size, load_size]); img = tl.center_crop(img, crop_size)\n    img = tf.clip_by_value(img, 0, 255) / 255.0  # or img = tl.minmax_norm(img)\n    img = img * 2 - 1\n    return img\n\n@tf.function\ndef augmentation(image):\n    aug_size = IMAGE_WIDTH+int(IMAGE_WIDTH*0.15)\n    image = tf.image.resize(image, [aug_size, aug_size], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n    image = tf.image.random_crop(image, size=[IMAGE_WIDTH, IMAGE_HEIGHT, 3])\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_flip_left_right(image)\n    return image\n\ndef read_tfrecord(example):\n    tfrecord_format = { \"image\": tf.io.FixedLenFeature([], tf.string) }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    return decode_image(example['image'])\n     \ndef load_dataset(filenames):\n    dataset = tf.data.TFRecordDataset(filenames)\n    return dataset.map(read_tfrecord, num_parallel_calls=AUTO)\n\n\nfast_photo_ds = load_dataset(PHOTO_FILENAMES_TFREC).shuffle(BUFFER_SIZE).batch(32*strategy.num_replicas_in_sync, drop_remainder=True).prefetch(AUTO)\nfid_photo_ds = load_dataset(PHOTO_FILENAMES_TFREC).shuffle(BUFFER_SIZE).take(1024).batch(32*strategy.num_replicas_in_sync, drop_remainder=True).prefetch(AUTO)\nfid_monet_ds = load_dataset(MONET_FILENAMES_TFREC).shuffle(BUFFER_SIZE).batch(32*strategy.num_replicas_in_sync, drop_remainder=True).prefetch(AUTO)\n\ndef get_gan_dataset():\n    monet_ds = load_dataset(MONET_FILENAMES_TFREC)\n    photo_ds = load_dataset(PHOTO_FILENAMES_TFREC)\n    monet_ds = monet_ds.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).cache().shuffle(BUFFER_SIZE).repeat().prefetch(AUTO)\n    photo_ds = photo_ds.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True).cache().shuffle(BUFFER_SIZE).repeat().prefetch(AUTO)\n    return tf.data.Dataset.zip((monet_ds, photo_ds))","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.395610Z","iopub.execute_input":"2021-10-05T12:43:20.395862Z","iopub.status.idle":"2021-10-05T12:43:20.548195Z","shell.execute_reply.started":"2021-10-05T12:43:20.395834Z","shell.execute_reply":"2021-10-05T12:43:20.547356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import multiprocessing\ndef batch_dataset(dataset,\n                  batch_size,\n                  drop_remainder=True,\n                  n_prefetch_batch=1,\n                  filter_fn=None,\n                  map_fn=None,\n                  n_map_threads=None,\n                  filter_after_map=False,\n                  shuffle=True,\n                  shuffle_buffer_size=None,\n                  repeat=AUTO):\n    # set defaults\n    if n_map_threads is None:\n        n_map_threads = multiprocessing.cpu_count()\n    if shuffle and shuffle_buffer_size is None:\n        shuffle_buffer_size = max(batch_size * 128, 2048)  # set the minimum buffer size as 2048\n\n    # [*] it is efficient to conduct `shuffle` before `map`/`filter` because `map`/`filter` is sometimes costly\n    if shuffle:\n        dataset = dataset.shuffle(shuffle_buffer_size)\n\n    if not filter_after_map:\n        if filter_fn:\n            dataset = dataset.filter(filter_fn)\n\n        if map_fn:\n            dataset = dataset.map(map_fn, num_parallel_calls=n_map_threads)\n\n    else:  # [*] this is slower\n        if map_fn:\n            dataset = dataset.map(map_fn, num_parallel_calls=n_map_threads)\n\n        if filter_fn:\n            dataset = dataset.filter(filter_fn)\n\n    dataset = dataset.batch(batch_size, drop_remainder=drop_remainder)\n\n    dataset = dataset.repeat().prefetch(n_prefetch_batch)\n\n    return dataset\n\n\ndef memory_data_batch_dataset(memory_data,\n                              batch_size,\n                              drop_remainder=True,\n                              n_prefetch_batch=1,\n                              filter_fn=None,\n                              map_fn=None,\n                              n_map_threads=None,\n                              filter_after_map=False,\n                              shuffle=True,\n                              shuffle_buffer_size=None,\n                              repeat=AUTO):\n    \"\"\"Batch dataset of memory data.\n    Parameters\n    ----------\n    memory_data : nested structure of tensors/ndarrays/lists\n    \"\"\"\n    dataset = tf.data.Dataset.from_tensor_slices(memory_data)\n    dataset = batch_dataset(dataset,\n                            batch_size,\n                            drop_remainder=drop_remainder,\n                            n_prefetch_batch=n_prefetch_batch,\n                            filter_fn=filter_fn,\n                            map_fn=map_fn,\n                            n_map_threads=n_map_threads,\n                            filter_after_map=filter_after_map,\n                            shuffle=shuffle,\n                            shuffle_buffer_size=shuffle_buffer_size,\n                            repeat=repeat)\n    return dataset\n\n\ndef disk_image_batch_dataset(img_paths,\n                             batch_size,\n                             labels=None,\n                             drop_remainder=True,\n                             n_prefetch_batch=1,\n                             filter_fn=None,\n                             map_fn=None,\n                             n_map_threads=None,\n                             filter_after_map=False,\n                             shuffle=True,\n                             shuffle_buffer_size=None,\n                             repeat=AUTO):\n    \"\"\"Batch dataset of disk image for PNG and JPEG.\n    Parameters\n    ----------\n    img_paths : 1d-tensor/ndarray/list of str\n    labels : nested structure of tensors/ndarrays/lists\n    \"\"\"\n    if labels is None:\n        memory_data = img_paths\n    else:\n        memory_data = (img_paths, labels)\n\n    def parse_fn(path):\n        img = tf.io.read_file(path)\n        img = tf.image.decode_jpeg(img, 3)  # fix channels to 3\n        img = tf.cast(img, tf.float32)\n        return (img,)\n\n    if map_fn:  # fuse `map_fn` and `parse_fn`\n        def map_fn_(*args):\n            return map_fn(*parse_fn(*args))\n    else:\n        map_fn_ = parse_fn\n\n    dataset = memory_data_batch_dataset(memory_data,\n                                        batch_size,\n                                        drop_remainder=drop_remainder,\n                                        n_prefetch_batch=n_prefetch_batch,\n                                        filter_fn=filter_fn,\n                                        map_fn=map_fn_,\n                                        n_map_threads=n_map_threads,\n                                        filter_after_map=filter_after_map,\n                                        shuffle=shuffle,\n                                        shuffle_buffer_size=shuffle_buffer_size,\n                                        repeat=repeat)\n\n    return dataset\n\ndef make_dataset(img_paths, batch_size, load_size, crop_size, training, drop_remainder=True, shuffle=True, repeat=AUTO):\n    if training:\n        @tf.function\n        def _map_fn(img):  # preprocessing\n            img = tf.image.random_flip_left_right(img)\n            img = tf.image.resize(img, [load_size, load_size])\n            img = tf.image.random_crop(img, [crop_size, crop_size, tf.shape(img)[-1]])\n            img = tf.clip_by_value(img, 0, 255)\n            img = img / 127.5 - 1\n            return img\n    else:\n        @tf.function\n        def _map_fn(img):  # preprocessing\n            img = tf.image.resize(img, [crop_size, crop_size]) \n            img = tf.clip_by_value(img, 0, 255)\n            img = img / 127.5 - 1\n            return img\n\n    return disk_image_batch_dataset(img_paths,\n                                       batch_size,\n                                       drop_remainder=drop_remainder,\n                                       map_fn=_map_fn,\n                                       shuffle=shuffle,\n                                       repeat=repeat)\n\n\ndef make_zip_dataset(A_img_paths=MONET_FILENAMES, B_img_paths=PHOTO_FILENAMES, batch_size=BATCH_SIZE, load_size=IMAGE_WIDTH+int(IMAGE_WIDTH*0.15), crop_size=IMAGE_WIDTH, training=True, shuffle=True, repeat=AUTO):\n    # zip two datasets aligned by the longer one\n    if repeat:\n        A_repeat = B_repeat = None  # cycle both\n    else:\n        if len(A_img_paths) >= len(B_img_paths):\n            A_repeat = 1\n            B_repeat = None  # cycle the shorter one\n        else:\n            A_repeat = None  # cycle the shorter one\n            B_repeat = 1\n\n    A_dataset = make_dataset(A_img_paths, batch_size, load_size, crop_size, training, drop_remainder=True, shuffle=shuffle, repeat=A_repeat)\n    B_dataset = make_dataset(B_img_paths, batch_size, load_size, crop_size, training, drop_remainder=True, shuffle=shuffle, repeat=B_repeat)\n\n    A_B_dataset = tf.data.Dataset.zip((A_dataset, B_dataset))\n    len_dataset = max(len(A_img_paths), len(B_img_paths)) // batch_size\n\n    return A_B_dataset, len_dataset\n\n\nclass ItemPool:\n    def __init__(self, pool_size=50):\n        self.pool_size = pool_size\n        self.items = []\n\n    def __call__(self, in_items):\n        # `in_items` should be a batch tensor\n\n        if self.pool_size == 0:\n            return in_items\n\n        out_items = []\n        for in_item in in_items:\n            if len(self.items) < self.pool_size:\n                self.items.append(in_item)\n                out_items.append(in_item)\n            else:\n                if np.random.rand() > 0.5:\n                    idx = np.random.randint(0, len(self.items))\n                    out_item, self.items[idx] = self.items[idx], in_item\n                    out_items.append(out_item)\n                else:\n                    out_items.append(in_item)\n        return tf.stack(out_items, axis=0)","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.550230Z","iopub.execute_input":"2021-10-05T12:43:20.550550Z","iopub.status.idle":"2021-10-05T12:43:20.588523Z","shell.execute_reply.started":"2021-10-05T12:43:20.550510Z","shell.execute_reply":"2021-10-05T12:43:20.587520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset, len_dataset = make_zip_dataset()\ntest_dataset=get_gan_dataset()","metadata":{"execution":{"iopub.status.busy":"2021-10-05T12:43:20.590051Z","iopub.execute_input":"2021-10-05T12:43:20.590355Z","iopub.status.idle":"2021-10-05T12:43:20.821657Z","shell.execute_reply.started":"2021-10-05T12:43:20.590316Z","shell.execute_reply":"2021-10-05T12:43:20.820778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def plot_images(sample_monet1, sample_monet2):\n#     plt.figure(figsize=(16, 816))\n#     display_list = [sample_monet2[0], sample_monet1[0]]\n#     title = [f'Input Image', f'Result']\n\n#     for i in range(2):\n#         plt.subplot(1, 2, i+1)\n#         plt.title(title[i])\n#         plt.imshow(display_list[i] * 0.5 + 0.5)\n#         plt.axis('off')\n#     plt.show()\n    \n# for monet, photo in dataset.take(2):\n#     plot_images(monet, photo)","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.822886Z","iopub.execute_input":"2021-10-05T12:43:20.823163Z","iopub.status.idle":"2021-10-05T12:43:20.827500Z","shell.execute_reply.started":"2021-10-05T12:43:20.823130Z","shell.execute_reply":"2021-10-05T12:43:20.826380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Pix2Pix define model","metadata":{}},{"cell_type":"code","source":"initializer = tf.random_normal_initializer(0., 0.02)\n\ndef _get_norm_layer(norm):\n    if norm == 'none':\n        return lambda: lambda x: x\n    elif norm == 'batch_norm':\n        return keras.layers.BatchNormalization\n    elif norm == 'instance_norm':\n        return tfa.layers.InstanceNormalization\n    elif norm == 'layer_norm':\n        return keras.layers.LayerNormalization\n\ndef downsample(filters, size, apply_norm=True, norm='instance_norm', strides=4):\n    result = Sequential()\n    result.add(Conv2D(filters, size, strides=strides, padding='same',kernel_initializer=initializer, use_bias=False))\n    if apply_norm:\n        Norm = _get_norm_layer(norm)\n        result.add(Norm())\n    result.add(LeakyReLU(alpha=0.2))\n    return result\n\n\ndef upsample(filters, size, apply_dropout=False, norm='instance_norm', strides=4):\n    result = Sequential()\n    result.add(Conv2DTranspose(filters, size, strides=strides, padding='same', kernel_initializer=initializer, use_bias=False))\n    Norm = _get_norm_layer(norm)\n    result.add(Norm())\n\n    if apply_dropout:\n        result.add(Dropout(0.5))\n\n    result.add(ReLU())\n    return result\n\n\ndef get_generator(output_channels=3, norm='instance_norm'):\n    down_stack = [\n      downsample(DIM, SIZE, apply_norm=False, norm=norm),  \n      downsample(DIM*2, SIZE, norm=norm), \n      downsample(DIM*4, SIZE, norm=norm), \n#       downsample(DIM*8, SIZE, norm=norm),\n#       downsample(DIM*8, SIZE, norm=norm), \n#       downsample(DIM*8, SIZE, norm=norm),\n#       downsample(DIM*8, SIZE, norm=norm),\n      downsample(DIM*8, SIZE, norm=norm),\n    ]\n\n    up_stack = [\n#       upsample(DIM*8, SIZE, apply_dropout=True, norm=norm),\n#       upsample(DIM*8, SIZE, apply_dropout=True, norm=norm), \n      upsample(DIM*8, SIZE, apply_dropout=True, norm=norm),\n#       upsample(DIM*8, SIZE, norm=norm),\n#       upsample(DIM*8, SIZE, norm=norm),\n      upsample(DIM*4, SIZE, norm=norm),\n      upsample(DIM*2, SIZE, norm=norm),\n    ]\n\n    last = Conv2DTranspose(output_channels, SIZE, strides=4, padding='same', kernel_initializer=initializer,activation='tanh')\n\n    concat = Concatenate()\n\n    inputs = Input(shape=[None, None, 3])\n    x = inputs\n\n    # Downsampling through the model\n    skips = []\n    for down in down_stack:\n        x = down(x)\n        skips.append(x)\n\n    skips = reversed(skips[:-1])\n\n    # Upsampling and establishing the skip connections\n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = concat([x, skip])\n\n    x = last(x)\n\n    return tf.keras.Model(inputs=inputs, outputs=x)\n\ndef get_discriminator(norm='instance_norm'):\n    inp = Input(shape=[None, None, 3], name='input_image')\n    x = inp\n    down1 = downsample(DIM, SIZE, apply_norm=False, norm=norm)(x)\n    down2 = downsample(DIM*2, SIZE, norm=norm)(down1)\n    down3 = downsample(DIM*4, SIZE, norm=norm)(down2)\n    zero_pad1 = ZeroPadding2D()(down3) \n    conv = Conv2D(DIM*8, SIZE, strides=1, kernel_initializer=initializer,use_bias=False)(zero_pad1) \n    Norm = _get_norm_layer(norm)\n    norm1 = Norm()(conv)\n    leaky_relu = LeakyReLU(alpha=0.2)(norm1)\n    zero_pad2 = ZeroPadding2D()(leaky_relu)\n    last = Conv2D(1, SIZE, strides=1, kernel_initializer=initializer)(zero_pad2) \n    return Model(inputs=inp, outputs=last)","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.829382Z","iopub.execute_input":"2021-10-05T12:43:20.829745Z","iopub.status.idle":"2021-10-05T12:43:20.855506Z","shell.execute_reply.started":"2021-10-05T12:43:20.829702Z","shell.execute_reply":"2021-10-05T12:43:20.854570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Plot lr","metadata":{}},{"cell_type":"code","source":"# Matplotlib config\nplt.ioff()\nplt.rc('image', cmap='gray_r')\nplt.rc('grid', linewidth=1)\nplt.rc('xtick', top=False, bottom=False, labelsize='large')\nplt.rc('ytick', left=False, right=False, labelsize='large')\nplt.rc('axes', facecolor='F8F8F8', titlesize=\"large\", edgecolor='white')\nplt.rc('text', color='a8151a')\nplt.rc('figure', facecolor='F0F0F0', figsize=(16,9))\n# Matplotlib fonts\nMATPLOTLIB_FONT_DIR = os.path.join(os.path.dirname(plt.__file__), \"mpl-data/fonts/ttf\")\n\ndef display_epoch_predict(photo2monet, photo, monet, monet2photo):\n    plt.figure(figsize=(16, 816))\n    display_list = [photo[0], photo2monet[0]]\n    title = [f'photo', f'photo2monet']\n    for i in range(2):\n        plt.subplot(1, 2, i+1)\n        plt.title(title[i])\n        plt.imshow(display_list[i] * 0.5 + 0.5)\n        plt.axis('off')\n    plt.show()\n    \n    plt.figure(figsize=(16, 816))\n    display_list = [monet[0], monet2photo[0]]\n    title = ['monet', 'monet2photo']\n    for i in range(2):\n        plt.subplot(1, 2, i+1)\n        plt.title(title[i])\n        plt.imshow(display_list[i] * 0.5 + 0.5)\n        plt.axis('off')\n    plt.show()\n         \nclass PlotTraining(tf.keras.callbacks.Callback):\n    def __init__(self, sample_rate=10, zoom=16):\n        self.sample_rate = sample_rate\n        self.step = 0\n        self.zoom = zoom\n        self.steps_per_epoch = STEPS_PER_EPOCH*BATCH_SIZE\n        \n    def on_train_begin(self, logs={}):\n        self.batch_history = {}\n        self.batch_step = []\n        self.epoch_history = {}\n        self.epoch_step = []\n        self.fig, self.axes = plt.subplots(1, 2, figsize=(16, 7))\n        self.fig.subplots_adjust(wspace=0.12, hspace=0.12)\n        plt.ioff()\n       \n    def on_batch_end(self, batch, logs={}):\n        if (batch % self.sample_rate) == 0:\n            self.batch_step.append(self.step)\n            for k,v in logs.items():\n                # do not log \"batch\" and \"size\" metrics that do not change\n                # do not log training accuracy \"acc\"\n                if k=='batch' or k=='size' or k.endswith('gen_loss'): # or k=='acc':\n                    continue\n                self.batch_history.setdefault(k, []).append(v[-1][-1][-1])\n                self.step += 1\n \n    def on_epoch_end(self, epoch, logs={}):\n        plt.close(self.fig)\n        self.axes[0].cla()\n        self.axes[1].cla()\n    \n        self.axes[0].set_ylim(0, 2)\n        self.axes[1].set_ylim(0, 10)\n\n        self.epoch_step.append(self.step)\n     \n        for k,v in logs.items():\n          # only log validation metrics\n            if k.endswith('disc_loss'):\n                  continue\n            self.epoch_history.setdefault(k, []).append(v[-1][-1][-1])\n        \n        for k,v in self.batch_history.items():\n            self.axes[0 if k.endswith('disc_loss') else 1].plot(np.array(self.batch_step) / self.steps_per_epoch, v, label=k)\n\n        for k,v in self.epoch_history.items():\n            self.axes[0 if k.endswith('disc_loss') else 1].plot(np.array(self.epoch_step) / self.steps_per_epoch, v, label=k, linewidth=3)\n\n        self.axes[0].legend()\n        self.axes[1].legend()\n        self.axes[0].set_xlabel('epochs')\n        self.axes[1].set_xlabel('epochs')\n        self.axes[0].minorticks_on()\n        self.axes[0].grid(True, which='major', axis='both', linestyle='-', linewidth=1)\n        self.axes[0].grid(True, which='minor', axis='both', linestyle=':', linewidth=0.5)\n        self.axes[1].minorticks_on()\n        self.axes[1].grid(True, which='major', axis='both', linestyle='-', linewidth=1)\n        self.axes[1].grid(True, which='minor', axis='both', linestyle=':', linewidth=0.5)\n        display(self.fig)","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.858732Z","iopub.execute_input":"2021-10-05T12:43:20.859065Z","iopub.status.idle":"2021-10-05T12:43:20.895341Z","shell.execute_reply.started":"2021-10-05T12:43:20.859032Z","shell.execute_reply":"2021-10-05T12:43:20.894342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    LAMBDA = 10\n    loss_obj = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n\n    def discriminator_loss(real, generated):\n        real_loss = loss_obj(tf.ones_like(real), real)\n        generated_loss = loss_obj(tf.zeros_like(generated), generated)\n        total_disc_loss = real_loss + generated_loss\n        return total_disc_loss * 0.5\n\n    def generator_loss(generated):\n        return loss_obj(tf.ones_like(generated), generated)\n\n    def calc_cycle_loss(real_image, cycled_image):\n        loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))\n        return LAMBDA * loss1\n\n    def identity_loss(real_image, same_image):\n        loss = tf.reduce_mean(tf.abs(real_image - same_image))\n        return LAMBDA * 0.5 * loss\n","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.896649Z","iopub.execute_input":"2021-10-05T12:43:20.897812Z","iopub.status.idle":"2021-10-05T12:43:20.908975Z","shell.execute_reply.started":"2021-10-05T12:43:20.897761Z","shell.execute_reply":"2021-10-05T12:43:20.908132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Define optimizers","metadata":{}},{"cell_type":"code","source":"class LinearDecay(tf.keras.optimizers.schedules.LearningRateSchedule):\n    # if `step` < `step_decay`: use fixed learning rate\n    # else: linearly decay the learning rate to zero\n\n    def __init__(self, initial_learning_rate, total_steps, step_decay):\n        super(LinearDecay, self).__init__()\n        self._initial_learning_rate = initial_learning_rate\n        self._steps = total_steps\n        self._step_decay = step_decay\n        self.current_learning_rate = tf.Variable(initial_value=initial_learning_rate, trainable=False, dtype=tf.float32)\n\n    def __call__(self, step):\n        self.current_learning_rate.assign(tf.cond(\n            step >= self._step_decay,\n            true_fn=lambda: self._initial_learning_rate * (1 - 1 / (self._steps - self._step_decay) * (step - self._step_decay)),\n            false_fn=lambda: self._initial_learning_rate\n        ))\n        return self.current_learning_rate\n    \nwith strategy.scope():\n    lr_schedule_gen = LinearDecay(START_LEARNING_RATE, EPOCHS * STEPS_PER_EPOCH, STEPS_PER_EPOCH)\n    lr_schedule_disc = LinearDecay(START_LEARNING_RATE_DISC, EPOCHS * STEPS_PER_EPOCH, STEPS_PER_EPOCH)\n    \n    monet_generator_optimizer = Adam(learning_rate=lr_schedule_gen, beta_1=0.5)\n    photo_generator_optimizer = Adam(learning_rate=lr_schedule_gen, beta_1=0.5)\n    monet_discriminator_optimizer = Adam(learning_rate=lr_schedule_disc, beta_1=0.5)\n    photo_discriminator_optimizer = Adam(learning_rate=lr_schedule_disc, beta_1=0.5)\n\n    monet_generator = get_generator(norm='instance_norm') # layer_norm batch_norm instance_norm\n    photo_generator = get_generator(norm='instance_norm') # layer_norm batch_norm instance_norm\n    monet_discriminator = get_discriminator(norm='instance_norm') # layer_norm batch_norm instance_norm\n    photo_discriminator = get_discriminator(norm='instance_norm') # layer_norm batch_norm instance_norm","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:20.910465Z","iopub.execute_input":"2021-10-05T12:43:20.911561Z","iopub.status.idle":"2021-10-05T12:43:24.209758Z","shell.execute_reply.started":"2021-10-05T12:43:20.911528Z","shell.execute_reply":"2021-10-05T12:43:24.208860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CycleGan(tf.keras.Model):\n    def __init__(self, m_gen, p_gen, m_disc, p_disc):\n        super(CycleGan, self).__init__()\n        self.m_gen = m_gen\n        self.p_gen = p_gen\n        self.m_disc = m_disc\n        self.p_disc = p_disc\n      \n    def compile(\n            self, \n            m_gen_optimizer, \n            p_gen_optimizer,\n            m_disc_optimizer, \n            p_disc_optimizer, \n            disc_loss_fn, \n            gen_loss_fn, \n            calc_cycle_loss_fn, \n            identity_loss_fn,\n            steps_per_execution\n        ):\n        super(CycleGan, self).compile()\n        self.m_gen_optimizer = m_gen_optimizer\n        self.p_gen_optimizer = p_gen_optimizer\n        self.m_disc_optimizer = m_disc_optimizer\n        self.p_disc_optimizer = p_disc_optimizer\n        self.disc_loss_fn = disc_loss_fn\n        self.gen_loss_fn = gen_loss_fn\n        self.calc_cycle_loss = calc_cycle_loss_fn\n        self.identity_loss = identity_loss_fn\n        self.steps_per_execution = steps_per_execution\n        \n    def call(self, inputs, training=False):\n        return self.m_gen(inputs)\n    \n    def train_step(self, input_batch):\n        real_monet, real_photo = input_batch\n        with tf.GradientTape(persistent=True) as tape:\n            # photo to monet back to photo\n            fake_monet = self.m_gen(real_photo, training=True)\n            cycled_photo = self.p_gen(fake_monet, training=True)\n\n            # monet to photo back to monet\n            fake_photo = self.p_gen(real_monet, training=True)\n            cycled_monet = self.m_gen(fake_photo, training=True)\n\n            # generating itself\n            same_monet = self.m_gen(real_monet, training=True)\n            same_photo = self.p_gen(real_photo, training=True)\n\n            # discriminator used to check, inputing real images\n            disc_real_monet = self.m_disc(real_monet, training=True)\n            disc_real_photo = self.p_disc(real_photo, training=True)\n\n            # discriminator used to check, inputing fake images\n            disc_fake_monet = self.m_disc(fake_monet, training=True)\n            disc_fake_photo = self.p_disc(fake_photo, training=True)\n\n            # evaluates generator loss\n            monet_gen_loss = self.gen_loss_fn(disc_fake_monet)\n            photo_gen_loss = self.gen_loss_fn(disc_fake_photo)\n\n            # evaluates total cycle consistency loss\n            total_cycle_loss =  self.calc_cycle_loss(real_monet, cycled_monet) + self.calc_cycle_loss(real_photo, cycled_photo)\n\n            # evaluates total generator loss \n            total_monet_gen_loss = monet_gen_loss + total_cycle_loss + self.identity_loss(real_monet, same_monet)\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss + self.identity_loss(real_photo, same_photo)\n\n            # evaluates discriminator loss\n            monet_disc_loss = self.disc_loss_fn(disc_real_monet, disc_fake_monet)\n            photo_disc_loss = self.disc_loss_fn(disc_real_photo, disc_fake_photo)\n\n        # Calculate the gradients for generator and discriminator\n        monet_generator_gradients = tape.gradient(total_monet_gen_loss, self.m_gen.trainable_variables)\n        photo_generator_gradients = tape.gradient(total_photo_gen_loss, self.p_gen.trainable_variables)\n\n        monet_discriminator_gradients = tape.gradient(monet_disc_loss, self.m_disc.trainable_variables)\n        photo_discriminator_gradients = tape.gradient(photo_disc_loss, self.p_disc.trainable_variables)\n\n        # Apply the gradients to the optimizer\n        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients, self.m_gen.trainable_variables))\n        self.p_gen_optimizer.apply_gradients(zip(photo_generator_gradients, self.p_gen.trainable_variables))\n\n        self.m_disc_optimizer.apply_gradients(zip(monet_discriminator_gradients, self.m_disc.trainable_variables))\n        self.p_disc_optimizer.apply_gradients(zip(photo_discriminator_gradients, self.p_disc.trainable_variables))\n        \n        return {\n            \"monet_gen_loss\": total_monet_gen_loss,\n            \"photo_gen_loss\": total_photo_gen_loss,\n            \"monet_disc_loss\": monet_disc_loss,\n            \"photo_disc_loss\": photo_disc_loss\n        }","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:24.211322Z","iopub.execute_input":"2021-10-05T12:43:24.211798Z","iopub.status.idle":"2021-10-05T12:43:24.231237Z","shell.execute_reply.started":"2021-10-05T12:43:24.211764Z","shell.execute_reply":"2021-10-05T12:43:24.230379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():    \n    model = CycleGan(\n        m_gen=monet_generator,\n        p_gen=photo_generator,\n        m_disc=monet_discriminator,\n        p_disc=photo_discriminator\n    )\n    model.compile(\n        m_gen_optimizer=monet_generator_optimizer,\n        p_gen_optimizer=photo_generator_optimizer,\n        m_disc_optimizer=monet_discriminator_optimizer,\n        p_disc_optimizer=photo_discriminator_optimizer,\n        disc_loss_fn = discriminator_loss, \n        gen_loss_fn = generator_loss, \n        calc_cycle_loss_fn = calc_cycle_loss, \n        identity_loss_fn = identity_loss,\n        steps_per_execution = STEPS_PER_EPOCH//strategy.num_replicas_in_sync\n    )","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:24.232550Z","iopub.execute_input":"2021-10-05T12:43:24.232939Z","iopub.status.idle":"2021-10-05T12:43:24.299022Z","shell.execute_reply.started":"2021-10-05T12:43:24.232907Z","shell.execute_reply":"2021-10-05T12:43:24.298173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint_path = \"/kaggle/working/cp-last-tpu.h5\"\ncp_callback = tf.keras.callbacks.ModelCheckpoint(\n    filepath=checkpoint_path, \n    monitor='monet_gen_loss', \n    verbose=1, \n    mode='min', \n    save_weights_only=True,\n    save_freq=SAVE_FREQ\n)\n\n\nplot_training = PlotTraining(sample_rate=8, zoom=12)\n\nclass DisplayCallback(tf.keras.callbacks.Callback):\n    def __init__(self):\n        super().__init__()\n        self._supports_tf_logs = True\n    def on_epoch_end(self, epoch, logs=None):\n        clear_output(wait=True)\n        monet, photo = next(iter(test_dataset))\n        display_epoch_predict(monet_generator.predict(photo), photo, monet, photo_generator.predict(monet))\n        print(f'gen lr: {self.model.m_gen_optimizer._decayed_lr(tf.float32)}')\n        print(f'disc lr: {self.model.m_disc_optimizer._decayed_lr(tf.float32)}')\n\nclass SaveModelsWeightsCallback(tf.keras.callbacks.Callback):\n    def __init__(self):\n        super().__init__()\n    def on_epoch_end(self, epoch, logs=None):\n        monet_generator.save_weights('./monet_generator-tpu.h5')\n        photo_generator.save_weights('./photo_generator-tpu.h5')\n\ncallbacks_list = [DisplayCallback(), cp_callback, plot_training, SaveModelsWeightsCallback()] # lr_decay_callback, cp_callback plot_training, , plot_training","metadata":{"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2021-10-05T12:43:24.300394Z","iopub.execute_input":"2021-10-05T12:43:24.301022Z","iopub.status.idle":"2021-10-05T12:43:24.311853Z","shell.execute_reply.started":"2021-10-05T12:43:24.300985Z","shell.execute_reply":"2021-10-05T12:43:24.310761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.built = True\n# model.predict(next(iter(dataset))[0])\n# model.load_weights('../input/checkpoints/cp-last-tpu.h5')","metadata":{"execution":{"iopub.status.busy":"2021-10-05T12:43:24.313231Z","iopub.execute_input":"2021-10-05T12:43:24.313498Z","iopub.status.idle":"2021-10-05T12:43:24.330098Z","shell.execute_reply.started":"2021-10-05T12:43:24.313468Z","shell.execute_reply":"2021-10-05T12:43:24.329333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(dataset, epochs=EPOCHS, steps_per_epoch=STEPS_PER_EPOCH, callbacks=callbacks_list)","metadata":{"execution":{"iopub.status.busy":"2021-10-05T12:43:24.331407Z","iopub.execute_input":"2021-10-05T12:43:24.331696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights('./cp-last-tpu.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import layers\n\nwith strategy.scope():\n    inception_model = tf.keras.applications.InceptionV3(input_shape=(256,256,3),pooling=\"avg\",include_top=False)\n    mix3  = inception_model.get_layer(\"mixed9\").output\n    f0 = tf.keras.layers.GlobalAveragePooling2D()(mix3)\n    inception_model = tf.keras.Model(inputs=inception_model.input, outputs=f0)\n    inception_model.trainable = False\n    \n    def calculate_activation_statistics_mod(images,fid_model):\n            act=tf.cast(fid_model.predict(images), tf.float32)\n            mu = tf.reduce_mean(act, axis=0)\n            mean_x = tf.reduce_mean(act, axis=0, keepdims=True)\n            mx = tf.matmul(tf.transpose(mean_x), mean_x)\n            vx = tf.matmul(tf.transpose(act), act)/tf.cast(tf.shape(act)[0], tf.float32)\n            sigma = vx - mx\n            return mu, sigma\n    myFID_mu2, myFID_sigma2 = calculate_activation_statistics_mod(fid_monet_ds,inception_model)        \n    fids=[]\nwith strategy.scope():\n    def calculate_frechet_distance(mu1,sigma1,mu2,sigma2):\n        fid_epsilon = 1e-14\n        covmean = tf.linalg.sqrtm(tf.cast(tf.matmul(sigma1,sigma2),tf.complex64))\n        covmean = tf.cast(tf.math.real(covmean),tf.float32)\n        tr_covmean = tf.linalg.trace(covmean)\n        return tf.matmul(tf.expand_dims(mu1 - mu2, axis=0),tf.expand_dims(mu1 - mu2, axis=1)) + tf.linalg.trace(sigma1) + tf.linalg.trace(sigma2) - 2 * tr_covmean\n    \n    def FID(images,gen_model,inception_model=inception_model,myFID_mu2=myFID_mu2, myFID_sigma2=myFID_sigma2):\n                inp = layers.Input(shape=[256, 256, 3], name='input_image')\n                x  = gen_model(inp)\n                x=inception_model(x)\n                fid_model = tf.keras.Model(inputs=inp, outputs=x)\n                mu1, sigma1= calculate_activation_statistics_mod(images,fid_model)\n                fid_value = calculate_frechet_distance(mu1, sigma1,myFID_mu2, myFID_sigma2)\n                return fid_value","metadata":{"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FID(test_dataset.take(300), monet_generator) \n# 35 Score for FID 9.726887","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.built = True\n# model.call(next(iter(test_photo)))\n# model.predict(next(iter(test_photo)))\n# model.load_weights('./cp-138-loss1.11.h5')\n\nfor inp in test_photo.take(15):\n    plot_images(model.predict(inp), inp)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}