{"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":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport tensorflow_addons as tfa\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of replicas:', strategy.num_replicas_in_sync)\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n    \nprint(tf.__version__)\n\n\n#test lalalalalalalala","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-07T17:55:07.360702Z","iopub.execute_input":"2022-05-07T17:55:07.361008Z","iopub.status.idle":"2022-05-07T17:55:12.435946Z","shell.execute_reply.started":"2022-05-07T17:55:07.360925Z","shell.execute_reply":"2022-05-07T17:55:12.435054Z"}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test lalalalalalalala\n\nHEIGHT = 256\nWIDTH = 256\nCHANNELS = 3\nBATCH_SIZE = 1\nOUTPUT_CHANNELS = 3\nIMAGE_SIZE = [WIDTH, HEIGHT]\nWINDOW_SIZE = 4\n\nmonet_adress = \"../input/tif-project-data/Albrecht_Durer_256.tfrecords\"\nphoto_adress = \"../input/gan-getting-started/photo_tfrec/*.tfrec\"\n\nlearning_rate1 = 2e-4\ninitial_learning_rate2 = 1e-4\nend_learning_rate2 = 2e-5\nlearning_rate3 = 2e-5\n\nsteps_per_epoch = 1000\nepochs1 = 1 #6\nepochs2 = 0 #21 \nepochs3 = 0 #4\nrepeat_factor = 15\n","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:12.43766Z","iopub.execute_input":"2022-05-07T17:55:12.437886Z","iopub.status.idle":"2022-05-07T17:55:12.444986Z","shell.execute_reply.started":"2022-05-07T17:55:12.437853Z","shell.execute_reply":"2022-05-07T17:55:12.444201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Load data and  display  \n\n#images(string) -> images(tensor)  \ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, CHANNELS)\n    image = (tf.cast(image, tf.float32) / 127.5) - 1\n    image = tf.reshape(image, [*IMAGE_SIZE, CHANNELS])\n    return image\n\n#tfrec -> images(string)  \ndef read_tfrecord(example):\n    tfrecord_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example['image'])\n    return image\n\n#filenamn -> tfrec\ndef load_dataset(filenames, labeled=True, ordered=False):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset\n\nMONET_FILENAMES = tf.io.gfile.glob(monet_adress)\nprint('Monet TFRecord Files:', len(MONET_FILENAMES))\n\nPHOTO_FILENAMES = tf.io.gfile.glob(str(photo_adress))\nprint('Photo TFRecord Files:', len(PHOTO_FILENAMES))\n\nmonet_ds = load_dataset(MONET_FILENAMES).batch(1)\nphoto_ds = load_dataset(PHOTO_FILENAMES).batch(1)\nexample_monet = next(iter(monet_ds))\nexample_photo = next(iter(photo_ds))\n\nplt.subplot(121)\nplt.title('Photo')\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(122)\nplt.title('Monet')\nplt.imshow(example_monet[0] * 0.5 + 0.5)\n","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:12.446692Z","iopub.execute_input":"2022-05-07T17:55:12.447169Z","iopub.status.idle":"2022-05-07T17:55:15.409977Z","shell.execute_reply.started":"2022-05-07T17:55:12.447132Z","shell.execute_reply":"2022-05-07T17:55:15.409271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# reduces the 2D dimensions by the stride.\ndef downsample(filters, size, apply_instancenorm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2D(filters, size, strides=2, padding='same',\n                             kernel_initializer=initializer, use_bias=False))\n\n    if apply_instancenorm:\n        result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    result.add(layers.LeakyReLU())\n    return result\n\ndef upsample(filters, size, apply_dropout=False):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2DTranspose(filters, size, strides=2,\n                                      padding='same',\n                                      kernel_initializer=initializer,\n                                      use_bias=False))\n\n    result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n\n    result.add(layers.ReLU())\n\n    return result","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.411646Z","iopub.execute_input":"2022-05-07T17:55:15.412472Z","iopub.status.idle":"2022-05-07T17:55:15.423127Z","shell.execute_reply.started":"2022-05-07T17:55:15.412423Z","shell.execute_reply":"2022-05-07T17:55:15.422034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input(shape=[HEIGHT,WIDTH,CHANNELS])\n\n    # bs = batch size\n    down_stack = [\n        downsample(64, WINDOW_SIZE, apply_instancenorm=False), # (bs, 128, 128, 64)\n        downsample(128, WINDOW_SIZE), # (bs, 64, 64, 128)\n        downsample(256, WINDOW_SIZE), # (bs, 32, 32, 256)\n        downsample(512, WINDOW_SIZE), # (bs, 16, 16, 512)\n        downsample(512, WINDOW_SIZE), # (bs, 8, 8, 512)\n        downsample(512, WINDOW_SIZE), # (bs, 4, 4, 512)\n        downsample(512, WINDOW_SIZE), # (bs, 2, 2, 512)\n        downsample(512, WINDOW_SIZE), # (bs, 1, 1, 512)\n    ]\n\n    up_stack = [\n        upsample(512, WINDOW_SIZE, apply_dropout=True), # (bs, 2, 2, 1024)\n        upsample(512, WINDOW_SIZE, apply_dropout=True), # (bs, 4, 4, 1024)\n        upsample(512, WINDOW_SIZE, apply_dropout=True), # (bs, 8, 8, 1024)\n        upsample(512, WINDOW_SIZE), # (bs, 16, 16, 1024)\n        upsample(256, WINDOW_SIZE), # (bs, 32, 32, 512)\n        upsample(128, WINDOW_SIZE), # (bs, 64, 64, 256)\n        upsample(64, WINDOW_SIZE), # (bs, 128, 128, 128)\n    ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last = layers.Conv2DTranspose(CHANNELS, WINDOW_SIZE,\n                                  strides=2,\n                                  padding='same',\n                                  kernel_initializer=initializer,\n                                  activation='tanh') # (bs, 256, 256, 3)\n\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 = layers.Concatenate()([x, skip])\n\n    x = last(x)\n\n    return keras.Model(inputs=inputs, outputs=x)","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.424777Z","iopub.execute_input":"2022-05-07T17:55:15.425087Z","iopub.status.idle":"2022-05-07T17:55:15.438403Z","shell.execute_reply.started":"2022-05-07T17:55:15.425022Z","shell.execute_reply":"2022-05-07T17:55:15.437709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    inp = layers.Input(shape=[HEIGHT,WIDTH,CHANNELS], name='input_image')\n\n    x = inp\n\n    down1 = downsample(64, WINDOW_SIZE, False)(x) # (bs, 128, 128, 64)\n    down2 = downsample(128, WINDOW_SIZE)(down1) # (bs, 64, 64, 128)\n    down3 = downsample(256, WINDOW_SIZE)(down2) # (bs, 32, 32, 256)\n\n    zero_pad1 = layers.ZeroPadding2D()(down3) # (bs, 34, 34, 256)\n    conv = layers.Conv2D(512, WINDOW_SIZE, strides=1,\n                         kernel_initializer=initializer,\n                         use_bias=False)(zero_pad1) # (bs, 31, 31, 512)\n\n    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n\n    leaky_relu = layers.LeakyReLU()(norm1)\n\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu) # (bs, 33, 33, 512)\n\n    last = layers.Conv2D(1, WINDOW_SIZE, strides=1,\n                         kernel_initializer=initializer)(zero_pad2) # (bs, 30, 30, 1)\n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.439765Z","iopub.execute_input":"2022-05-07T17:55:15.440079Z","iopub.status.idle":"2022-05-07T17:55:15.451228Z","shell.execute_reply.started":"2022-05-07T17:55:15.440041Z","shell.execute_reply":"2022-05-07T17:55:15.450438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CycleGan(keras.Model):\n    def __init__(\n        self,\n        monet_generator,\n        photo_generator,\n        monet_discriminator,\n        photo_discriminator,\n        example_photo,\n        loss_obj,\n        lambda_cycle= tf.Variable(8.0),\n        lambda_id = tf.Variable(1.)\n        \n        ):\n        super(CycleGan, self).__init__()\n        self.m_gen = monet_generator\n        self.p_gen = photo_generator\n        self.m_disc = monet_discriminator\n        self.p_disc = photo_discriminator\n        self.e_photo = example_photo\n        self.loss_obj = loss_obj\n        self.lambda_cycle = lambda_cycle\n        self.lambda_id = lambda_id\n        \n    def compile(\n        self,\n        m_gen_optimizer,\n        p_gen_optimizer,\n        m_disc_optimizer,\n        p_disc_optimizer,\n        gen_loss_fn,\n        disc_loss_fn,\n        cycle_loss_fn,\n        identity_loss_fn,\n        diff_aug, \n        \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.gen_loss_fn = gen_loss_fn\n        self.disc_loss_fn = disc_loss_fn\n        self.cycle_loss_fn = cycle_loss_fn\n        self.identity_loss_fn = identity_loss_fn\n        self.diff_aug = diff_aug\n    \n    def train_step(self, batch_data):\n        real_monet, real_photo = batch_data\n        batch_size = tf.shape(real_monet)[0]\n        with tf.GradientTape(persistent=True) as tape:\n            \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            # Diffaugment monet and photo\n            both_monet = tf.concat([real_monet, fake_monet], axis=0)            \n            aug_monet = self.diff_aug(both_monet)\n            aug_real_monet = aug_monet[:batch_size]\n            aug_fake_monet = aug_monet[batch_size:]\n            \n            \n            both_photo = tf.concat([real_photo, fake_photo], axis=0)            \n            aug_photo = self.diff_aug(both_photo)\n            aug_real_photo = aug_photo[:batch_size]\n            aug_fake_photo = aug_photo[batch_size:]\n            \n            # discriminator used to check, inputing real images\n            disc_real_monet = self.m_disc(aug_real_monet, training=True)\n            disc_real_photo = self.p_disc(aug_real_photo, training=True)\n\n            # discriminator used to check, inputing fake images\n            disc_fake_monet = self.m_disc(aug_fake_monet, training=True)\n            disc_fake_photo = self.p_disc(aug_fake_photo, training=True)\n\n            # evaluates generator loss\n            monet_gen_loss = self.gen_loss_fn(disc_fake_monet, self.loss_obj)\n            photo_gen_loss = self.gen_loss_fn(disc_fake_photo, self.loss_obj)\n\n            # evaluates total cycle consistency loss\n            total_cycle_loss = self.cycle_loss_fn(real_monet, cycled_monet, self.lambda_cycle) + self.cycle_loss_fn(real_photo, cycled_photo, self.lambda_cycle)\n            #evaluate identity loss\n            monet_idloss = self.identity_loss_fn(real_monet, same_monet, self.lambda_id)\n            photo_idloss = self.identity_loss_fn(real_photo, same_photo, self.lambda_id)\n            # evaluates total generator loss\n            total_monet_gen_loss = monet_gen_loss + total_cycle_loss + monet_idloss\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss + photo_idloss\n\n            # evaluates discriminator loss  \n            monet_disc_loss = self.disc_loss_fn(disc_real_monet, disc_fake_monet, self.loss_obj)\n            photo_disc_loss = self.disc_loss_fn(disc_real_photo, disc_fake_photo, self.loss_obj)\n\n        # Calculate the gradients for generator and discriminator\n        monet_generator_gradients = tape.gradient(total_monet_gen_loss,\n                                                  self.m_gen.trainable_variables)\n        photo_generator_gradients = tape.gradient(total_photo_gen_loss,\n                                                  self.p_gen.trainable_variables)\n\n        monet_discriminator_gradients = tape.gradient(monet_disc_loss,\n                                                      self.m_disc.trainable_variables)\n        photo_discriminator_gradients = tape.gradient(photo_disc_loss,\n                                                      self.p_disc.trainable_variables)\n\n        # Apply the gradients to the optimizer\n        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients,\n                                                 self.m_gen.trainable_variables))\n\n        self.p_gen_optimizer.apply_gradients(zip(photo_generator_gradients,\n                                                 self.p_gen.trainable_variables))\n\n        self.m_disc_optimizer.apply_gradients(zip(monet_discriminator_gradients,\n                                                  self.m_disc.trainable_variables))\n\n        self.p_disc_optimizer.apply_gradients(zip(photo_discriminator_gradients,\n                                                  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            \"total_cycle_loss\": total_cycle_loss,\n            \"monet_gen_loss_disc\": monet_gen_loss,\n            \"monet_id_loss\": monet_idloss\n        }","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.452845Z","iopub.execute_input":"2022-05-07T17:55:15.453162Z","iopub.status.idle":"2022-05-07T17:55:15.480654Z","shell.execute_reply.started":"2022-05-07T17:55:15.453125Z","shell.execute_reply":"2022-05-07T17:55:15.479905Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CustomCallback(keras.callbacks.Callback):\n    def on_epoch_begin(self, epoch, logs=None):\n        new_val=tf.math.scalar_mul(0.7,self.model.lambda_cycle)\n        val = tf.math.maximum(tf.Variable(0.0005), new_val)\n        self.model.lambda_cycle.assign(val)  \n        \n        new_id=tf.math.scalar_mul(0.7,self.model.lambda_id)\n        new_id = tf.math.maximum(new_id, tf.Variable(0.005))\n        self.model.lambda_id.assign(new_id)\n        \n    def on_epoch_end(self, epoch, logs=None):\n        image = self.model.m_gen(self.model.e_photo)\n        plt.figure(figsize=(6,6))\n        plt.title(\"Monet-esque Photo\")\n        plt.imshow(image[0] * 0.5 + 0.5)\n        plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.484104Z","iopub.execute_input":"2022-05-07T17:55:15.484358Z","iopub.status.idle":"2022-05-07T17:55:15.494025Z","shell.execute_reply.started":"2022-05-07T17:55:15.484331Z","shell.execute_reply":"2022-05-07T17:55:15.493288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n  def discriminator_loss(real, generated, loss_obj):\n    ones = tf.ones_like(real)\n    smooth = tf.random.uniform([1],0.9,1)\n    ones = tf.math.scalar_mul(smooth[0], ones)\n    zeros = tf.zeros_like(real)\n\n    real_loss = loss_obj(ones, real)\n    generated_loss = loss_obj(zeros, generated)\n\n    total_disc_loss = real_loss + generated_loss\n    return total_disc_loss * 0.5\n\nwith strategy.scope():\n  def generator_loss(generated, loss_obj):\n    return loss_obj(tf.ones_like(generated), generated)\n\nwith strategy.scope():\n  def calc_cycle_loss(real_image, cycled_image, LAMBDA):\n    loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))\n    return LAMBDA * loss1\n\nwith strategy.scope():\n  def identity_loss(real_image, same_image, LAMBDA):\n    loss = tf.reduce_mean(tf.abs(real_image - same_image))\n    return LAMBDA * 0.5 * loss","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.495427Z","iopub.execute_input":"2022-05-07T17:55:15.495731Z","iopub.status.idle":"2022-05-07T17:55:15.506981Z","shell.execute_reply.started":"2022-05-07T17:55:15.495696Z","shell.execute_reply":"2022-05-07T17:55:15.506201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Differentiable Augmentation taken from: https://github.com/mit-han-lab/data-efficient-gans/blob/master/DiffAugment_tf.py\nwith strategy.scope():\n    def DiffAugment(x, policy='color,translation,cutout', channels_first=False):\n        if policy:\n            if channels_first:\n                x = tf.transpose(x, [0, 2, 3, 1])\n            for p in policy.split(','):\n                for f in AUGMENT_FNS[p]:\n                    x = f(x)\n            if channels_first:\n                x = tf.transpose(x, [0, 3, 1, 2])\n        return x\n\n    def rand_brightness(x):\n        magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) - 0.5\n        x = x + magnitude\n        return x\n\n\n    def rand_saturation(x):\n        magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) * 2\n        x_mean = tf.reduce_mean(x, axis=3, keepdims=True)\n        x = (x - x_mean) * magnitude + x_mean\n        return x\n\n\n    def rand_contrast(x):\n        magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) + 0.5\n        x_mean = tf.reduce_mean(x, axis=[1, 2, 3], keepdims=True)\n        x = (x - x_mean) * magnitude + x_mean\n        return x\n\n\n    def rand_translation(x, ratio=0.125):\n        batch_size = tf.shape(x)[0]\n        image_size = tf.shape(x)[1:3]\n        shift = tf.cast(tf.cast(image_size, tf.float32) * ratio + 0.5, tf.int32)\n        translation_x = tf.random.uniform([batch_size, 1], -shift[0], shift[0] + 1, dtype=tf.int32)\n        translation_y = tf.random.uniform([batch_size, 1], -shift[1], shift[1] + 1, dtype=tf.int32)\n        grid_x = tf.clip_by_value(tf.expand_dims(tf.range(image_size[0], dtype=tf.int32), 0) + translation_x + 1, 0, image_size[0] + 1)\n        grid_y = tf.clip_by_value(tf.expand_dims(tf.range(image_size[1], dtype=tf.int32), 0) + translation_y + 1, 0, image_size[1] + 1)\n        x = tf.gather_nd(tf.pad(x, [[0, 0], [1, 1], [0, 0], [0, 0]]), tf.expand_dims(grid_x, -1), batch_dims=1)\n        x = tf.transpose(tf.gather_nd(tf.pad(tf.transpose(x, [0, 2, 1, 3]), [[0, 0], [1, 1], [0, 0], [0, 0]]), tf.expand_dims(grid_y, -1), batch_dims=1), [0, 2, 1, 3])\n        return x\n\n\n    def rand_cutout(x, ratio=0.5):\n        batch_size = tf.shape(x)[0]\n        image_size = tf.shape(x)[1:3]\n        cutout_size = tf.cast(tf.cast(image_size, tf.float32) * ratio + 0.5, tf.int32)\n        offset_x = tf.random.uniform([tf.shape(x)[0], 1, 1], maxval=image_size[0] + (1 - cutout_size[0] % 2), dtype=tf.int32)\n        offset_y = tf.random.uniform([tf.shape(x)[0], 1, 1], maxval=image_size[1] + (1 - cutout_size[1] % 2), dtype=tf.int32)\n        grid_batch, grid_x, grid_y = tf.meshgrid(tf.range(batch_size, dtype=tf.int32), tf.range(cutout_size[0], dtype=tf.int32), tf.range(cutout_size[1], dtype=tf.int32), indexing='ij')\n        cutout_grid = tf.stack([grid_batch, grid_x + offset_x - cutout_size[0] // 2, grid_y + offset_y - cutout_size[1] // 2], axis=-1)\n        mask_shape = tf.stack([batch_size, image_size[0], image_size[1]])\n        cutout_grid = tf.maximum(cutout_grid, 0)\n        cutout_grid = tf.minimum(cutout_grid, tf.reshape(mask_shape - 1, [1, 1, 1, 3]))\n        mask = tf.maximum(1 - tf.scatter_nd(cutout_grid, tf.ones([batch_size, cutout_size[0], cutout_size[1]], dtype=tf.float32), mask_shape), 0)\n        x = x * tf.expand_dims(mask, axis=3)\n        return x\n\n\n    AUGMENT_FNS = {\n        'color': [rand_brightness, rand_saturation, rand_contrast],\n        'translation': [rand_translation],\n        'cutout': [rand_cutout],\n    }","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.510926Z","iopub.execute_input":"2022-05-07T17:55:15.511139Z","iopub.status.idle":"2022-05-07T17:55:15.535541Z","shell.execute_reply.started":"2022-05-07T17:55:15.511114Z","shell.execute_reply":"2022-05-07T17:55:15.534631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **TRAINING **","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator() # transforms photos to Monet-esque paintings\n    photo_generator = Generator() # transforms Monet paintings to be more like photos\n\n    monet_discriminator = Discriminator() # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = Discriminator() # differentiates real photos and generated photos","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:15.537154Z","iopub.execute_input":"2022-05-07T17:55:15.537754Z","iopub.status.idle":"2022-05-07T17:55:17.88108Z","shell.execute_reply.started":"2022-05-07T17:55:15.537595Z","shell.execute_reply":"2022-05-07T17:55:17.880289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator_optimizer = tf.keras.optimizers.Adam(learning_rate1, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.Adam(learning_rate1, beta_1=0.5)\n\n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate1, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate1, beta_1=0.5)\n   \n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, monet_discriminator, photo_discriminator, example_photo, \n        tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n    )\n\n    cycle_gan_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        gen_loss_fn = generator_loss,\n        disc_loss_fn = discriminator_loss,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss,\n        diff_aug = DiffAugment,\n    )\n\n    my_dataset = tf.data.Dataset.zip((monet_ds, photo_ds)) \n    my_dataset = my_dataset.repeat(epochs1*repeat_factor)\n    cycle_gan_model.fit(\n        my_dataset, steps_per_epoch=steps_per_epoch, epochs=epochs1, callbacks=[CustomCallback()]\n    )","metadata":{"execution":{"iopub.status.busy":"2022-05-07T17:55:17.882527Z","iopub.execute_input":"2022-05-07T17:55:17.882779Z","iopub.status.idle":"2022-05-07T19:57:37.915033Z","shell.execute_reply.started":"2022-05-07T17:55:17.882742Z","shell.execute_reply":"2022-05-07T19:57:37.914315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    decay_steps = epochs2*steps_per_epoch\n    lr_schedule_g = tf.keras.optimizers.schedules.PolynomialDecay(\n        initial_learning_rate2, decay_steps, end_learning_rate2, power=1,\n        cycle=False, name=None\n    )\n    lr_schedule_d = tf.keras.optimizers.schedules.PolynomialDecay(\n        initial_learning_rate2, decay_steps, end_learning_rate2, power=1,\n        cycle=False, name=None\n    )\n\n    monet_generator_optimizer = tf.keras.optimizers.Adam(lr_schedule_g, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.Adam(lr_schedule_g, beta_1=0.5)\n\n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(lr_schedule_d, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(lr_schedule_d, beta_1=0.5)\n\n    cycle_gan_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        gen_loss_fn = generator_loss,\n        disc_loss_fn = discriminator_loss,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss,\n        diff_aug = DiffAugment,\n    )\n    my_dataset = tf.data.Dataset.zip((monet_ds, photo_ds)) \n    my_dataset = my_dataset.repeat(epochs2*repeat_factor)\n    \n    cycle_gan_model.fit(\n        my_dataset,\n        steps_per_epoch=steps_per_epoch,\n        epochs=epochs2,\n        callbacks=[CustomCallback()]\n    )","metadata":{"execution":{"iopub.status.busy":"2022-05-07T19:57:37.916509Z","iopub.execute_input":"2022-05-07T19:57:37.916929Z","iopub.status.idle":"2022-05-08T03:04:41.521481Z","shell.execute_reply.started":"2022-05-07T19:57:37.916892Z","shell.execute_reply":"2022-05-08T03:04:41.520615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator_optimizer = tf.keras.optimizers.Adam(learning_rate3, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.Adam(learning_rate3, beta_1=0.5)\n\n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate3, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate3, beta_1=0.5)\n   \n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, monet_discriminator, photo_discriminator, example_photo, \n        tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)\n    )\n\n    cycle_gan_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        gen_loss_fn = generator_loss,\n        disc_loss_fn = discriminator_loss,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss,\n        diff_aug = DiffAugment,\n    )\n\n    my_dataset = tf.data.Dataset.zip((monet_ds, photo_ds)) \n    my_dataset = my_dataset.repeat(epochs3*repeat_factor)\n    cycle_gan_model.fit(\n        my_dataset, steps_per_epoch=steps_per_epoch, epochs=epochs3, callbacks=[CustomCallback()]\n    )\n    monet_generator.save(\"/kaggle/working/monet_generator_3.h5\")\n    photo_generator.save(\"/kaggle/working/photo_generator_3.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-05-08T03:04:41.523746Z","iopub.execute_input":"2022-05-08T03:04:41.524034Z","iopub.status.idle":"2022-05-08T04:26:47.795927Z","shell.execute_reply.started":"2022-05-08T03:04:41.523996Z","shell.execute_reply":"2022-05-08T04:26:47.779488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for img in photo_ds.take(5):\n    prediction = monet_generator(img, training=False)\n    anti_prediction = photo_generator(prediction, training=False)\n    for i in range(prediction.shape[0]):\n        plt.figure(figsize=(12,12))\n\n        plt.subplot(1, 3, 1)\n        plt.imshow(img[i] * 0.5 + 0.5)\n\n        plt.subplot(1, 3, 2)\n        plt.imshow(prediction[i] * 0.5 + 0.5)\n        \n        plt.subplot(1, 3, 3)\n        plt.imshow(anti_prediction[i] * 0.5 + 0.5)\n\n        plt.axis('off')","metadata":{"execution":{"iopub.status.busy":"2022-05-08T04:26:47.799382Z","iopub.execute_input":"2022-05-08T04:26:47.799724Z","iopub.status.idle":"2022-05-08T04:26:51.31919Z","shell.execute_reply.started":"2022-05-08T04:26:47.799677Z","shell.execute_reply":"2022-05-08T04:26:51.31838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import FileLink \n%cd /kaggle/working\nFileLink(\"photo_generator_3.h5\")\n#FileLink(\"/kaggle/working/photo_generator_3.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-05-08T04:26:51.320724Z","iopub.execute_input":"2022-05-08T04:26:51.320985Z","iopub.status.idle":"2022-05-08T04:26:51.329912Z","shell.execute_reply.started":"2022-05-08T04:26:51.320952Z","shell.execute_reply":"2022-05-08T04:26:51.329202Z"},"trusted":true},"execution_count":null,"outputs":[]}]}