{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Tutorial 5: Custom Augmentations\n\nIn this tutorial, we will train a model on chest X-ray images in a self-supervised manner.\nIn self-supervised learning, X-ray images can pose some problems: They are often more\nthan eight bits deep which makes them incompatible with certain standard torchvision\ntransforms such as, for example, random-resized cropping. Additionally, some augmentations\nwhich are often used in self-supervised learning are ineffective on X-ray images.\nFor example, applying color jitter to an X-ray image with a single color channel\ndoes not make sense.\n\nWe will show how to address these problems and how to train a ResNet-18 with MoCo\non a set of 16-bit X-ray images in TIFF format.\n\nThe original dataset this tutorial is based on can be found [on Kaggle](https://www.kaggle.com/c/vinbigdata-chest-xray-abnormalities-detection/overview).\nThese images are in the DICOM format. For simplicity and efficiency reasons,\nwe randomly selected ~4000 images from the above dataset, resized them such that the\nmaximum of the width and height of each image is no larger than 512, and converted\nthem to the 16-bit TIFF format. To do so, we used ImageMagick which is preinstalled\non most Linux systems.\n\n.. code::\n\n    mogrify -path path/to/new/dataset -resize 512x512 -format tiff \"*.dicom\"\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Imports\n\nImport the Python frameworks we need for this tutorial.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import copy\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom PIL import Image\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import normalize\n\nfrom lightly.data import LightlyDataset\nfrom lightly.loss import NTXentLoss\nfrom lightly.models.modules.heads import MoCoProjectionHead\nfrom lightly.models.utils import (\n    batch_shuffle,\n    batch_unshuffle,\n    deactivate_requires_grad,\n    update_momentum,\n)\nfrom lightly.transforms.multi_view_transform import MultiViewTransform"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Configuration\nLet's set the configuration parameters for our experiments.\n\nWe will use eight workers to fetch the data from disc and a batch size of 128.\nThe input size of the images is set to 128. With these settings, the training\nrequires 2.5GB of GPU memory.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "num_workers = 8\nbatch_size = 128\ninput_size = 128\nseed = 1\nmax_epochs = 50"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's set the seed for our experiments.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "pl.seed_everything(seed)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Set the path to our dataset.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "path_to_data = \"/datasets/vinbigdata/train_small\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Setup custom data augmentations\n\nThe key to working with 16-bit X-ray images is to convert them to 8-bit images\nwhich are compatible with the torchvision augmentations without creating harmful\nartifacts. A good way to do so, is to use histogram normalization as described in\n[this paper](https://arxiv.org/pdf/2101.04909.pdf) about Covid-19 prognosis.\n\nLet's write an augmentation, which takes as input a numpy array with 16-bit input\ndepth and returns a histogram normalized 8-bit PIL image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class HistogramNormalize:\n    \"\"\"Performs histogram normalization on numpy array and returns 8-bit image.\n\n    Code was taken and adapted from Facebook:\n    https://github.com/facebookresearch/CovidPrognosis\n\n    \"\"\"\n\n    def __init__(self, number_bins: int = 256):\n        self.number_bins = number_bins\n\n    def __call__(self, image: np.array) -> Image:\n        # Get the image histogram.\n        image_histogram, bins = np.histogram(\n            image.flatten(), self.number_bins, density=True\n        )\n        cdf = image_histogram.cumsum()  # cumulative distribution function\n        cdf = 255 * cdf / cdf[-1]  # normalize\n\n        # Use linear interpolation of cdf to find new pixel values.\n        image_equalized = np.interp(image.flatten(), bins[:-1], cdf)\n        return Image.fromarray(image_equalized.reshape(image.shape))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Since we can't use color jitter on X-ray images, let's replace it and add some\nGaussian noise instead. It's easiest to apply this after the image has been\nconverted to a PyTorch tensor.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class GaussianNoise:\n    \"\"\"Applies random Gaussian noise to a tensor.\n\n    The intensity of the noise is dependent on the mean of the pixel values.\n    See https://arxiv.org/pdf/2101.04909.pdf for more information.\n\n    \"\"\"\n\n    def __call__(self, sample: torch.Tensor) -> torch.Tensor:\n        mu = sample.mean()\n        snr = np.random.randint(low=4, high=8)\n        sigma = mu / snr\n        noise = torch.normal(torch.zeros(sample.shape), sigma)\n        return sample + noise"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now that we have implemented our custom augmentations, we can combine them\nwith available augmentations from the torchvision library to get to the same\nset of augmentations as used in the aforementioned paper. Make sure, that\nthe first augmentation is the histogram normalization, and that the Gaussian\nnoise is applied after converting the image to a tensor.\n\nNote that we also transform the image from grayscale to RGB by simply repeating\nthe single color channel three times. The reason for this is that our ResNet expects\na three color channel input. This step can be skipped if a different backbone network\nis used.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Compose the custom augmentations with available augmentations.\nview_transform = torchvision.transforms.Compose(\n    [\n        HistogramNormalize(),\n        torchvision.transforms.Grayscale(num_output_channels=3),\n        torchvision.transforms.RandomResizedCrop(size=input_size, scale=(0.2, 1.0)),\n        torchvision.transforms.RandomHorizontalFlip(p=0.5),\n        torchvision.transforms.RandomVerticalFlip(p=0.5),\n        torchvision.transforms.GaussianBlur(21),\n        torchvision.transforms.ToTensor(),\n        GaussianNoise(),\n    ]\n)\n\n# Create a multiview transform that returns two different augmentations of each image.\ntransform = MultiViewTransform(transforms=[view_transform, view_transform])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's take a look at what our augmentation pipeline does to an image!\nWe plot the original image on the left and two random augmentations on the\nright.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "example_image_name = \"55e8e3db7309febee415515d06418171.tiff\"\nexample_image_path = os.path.join(path_to_data, example_image_name)\nexample_image = np.array(Image.open(example_image_path))\n\n# Torch transform returns a 3 x W x H image, we only show one color channel.\naugmented_image_1 = view_transform(example_image).numpy()[0]\naugmented_image_2 = view_transform(example_image).numpy()[0]\n\nfig, axs = plt.subplots(1, 3)\n\naxs[0].imshow(example_image)\naxs[0].set_axis_off()\naxs[0].set_title(\"Original Image\")\n\naxs[1].imshow(augmented_image_1)\naxs[1].set_axis_off()\n\naxs[2].imshow(augmented_image_2)\naxs[2].set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Setup dataset and dataloader\n\nWe create a dataset which loads the images in the input directory. Since the\ninput images are 16 bits deep, we need to overwrite the image loader such that\nit doesn't convert the images to RGB (and hence to 8-bit) automatically.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>The `LightlyDataset` uses a torchvision dataset underneath, which in turn uses\n  an image loader which transforms the input image to an 8-bit RGB image. If a 16-bit\n  grayscale image is loaded that way, all pixel values above 255 are simply clamped.\n  Therefore, we overwrite the default image loader with our custom one.</p></div>\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def tiff_loader(f):\n    \"\"\"Loads a 16-bit tiff image and returns it as a numpy array.\"\"\"\n    with open(f, \"rb\") as f:\n        image = Image.open(f)\n        return np.array(image)\n\n\n# Create the dataset with the custom transform and overwrite the image loader.\ndataset_train = LightlyDataset(input_dir=path_to_data, transform=transform)\ndataset_train.dataset.loader = tiff_loader\n\n# Setup the dataloader for training.\ndataloader_train = torch.utils.data.DataLoader(\n    dataset_train,\n    batch_size=batch_size,\n    shuffle=True,\n    drop_last=True,\n    num_workers=num_workers,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create the MoCo model\nUsing the building blocks provided by lightly we can write our MoCo model.\nWe implement it as a PyTorch Lightning module. For the criterion, we use\nthe NTXentLoss which should always be used with MoCo.\n\nMoCo also requires a memory bank - we set its size to 4096 which is approximately\nthe size of the input dataset. The temperature parameter of the loss is set to 0.1.\nThis smoothens the cross entropy term in the loss function.\n\nThe choice of the optimizer is left to the user. Here, we go with simple stochastic\ngradient descent with momentum.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class MoCoModel(pl.LightningModule):\n    def __init__(self):\n        super().__init__()\n\n        # Create a ResNet backbone and remove the classification head.\n        resnet = torchvision.models.resnet18()\n        self.backbone = nn.Sequential(\n            *list(resnet.children())[:-1],\n        )\n\n        # The backbone has output dimension 512 which also defines the size of\n        # the hidden dimension. We select 128 for the output dimension.\n        self.projection_head = MoCoProjectionHead(512, 512, 128)\n\n        # Add the momentum network.\n        self.backbone_momentum = copy.deepcopy(self.backbone)\n        self.projection_head_momentum = copy.deepcopy(self.projection_head)\n        deactivate_requires_grad(self.backbone_momentum)\n        deactivate_requires_grad(self.projection_head_momentum)\n\n        # Create the loss function with memory bank.\n        self.criterion = NTXentLoss(temperature=0.1, memory_bank_size=(4096, 128))\n\n    def training_step(self, batch, batch_idx):\n        (x_q, x_k), _, _ = batch\n\n        # Momentum update\n        update_momentum(self.backbone, self.backbone_momentum, 0.99)\n        update_momentum(self.projection_head, self.projection_head_momentum, 0.99)\n\n        # Get the queries.\n        q = self.backbone(x_q).flatten(start_dim=1)\n        q = self.projection_head(q)\n\n        # Get the keys.\n        k, shuffle = batch_shuffle(x_k)\n        k = self.backbone_momentum(k).flatten(start_dim=1)\n        k = self.projection_head_momentum(k)\n        k = batch_unshuffle(k, shuffle)\n\n        loss = self.criterion(q, k)\n        self.log(\"train_loss_ssl\", loss)\n        return loss\n\n    def configure_optimizers(self):\n        # Use SGD optimizer with momentum and weight decay.\n        optim = torch.optim.SGD(\n            self.parameters(),\n            lr=0.1,\n            momentum=0.9,\n            weight_decay=1e-4,\n        )\n        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optim, max_epochs)\n        return [optim], [scheduler]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Train MoCo with custom augmentations\nTraining the self-supervised model is now very easy. We can create a new\nMoCoModel instance and pass it to the PyTorch Lightning trainer.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "model = MoCoModel()\n\ntrainer = pl.Trainer(\n    max_epochs=max_epochs,\n    devices=1,\n    accelerator=\"gpu\",\n    precision=16,\n)\ntrainer.fit(model, dataloader_train)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Evaluate the results\nIt's always a good idea to evaluate how good the learned representations really\nare. How to do this depends on the available data and metadata. Luckily, in our case,\nwe have annotations of critical findings on the X-ray images. We can use this information\nto see, whether images with similar annotations are grouped together.\n\nWe start by getting a vector representation of each image in the dataset. For this,\nwe create a new dataloader. This time, we can pass the transform directly to the dataset.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# test transforms differ from training transforms as they do not introduce\n# additional noise\ntest_transforms = torchvision.transforms.Compose(\n    [\n        HistogramNormalize(),\n        torchvision.transforms.Grayscale(num_output_channels=3),\n        torchvision.transforms.Resize(input_size),\n        torchvision.transforms.ToTensor(),\n    ]\n)\n\n# Create the dataset and overwrite the image loader as before.\ndataset_test = LightlyDataset(input_dir=path_to_data, transform=test_transforms)\ndataset_test.dataset.loader = tiff_loader\n\n# Create the test dataloader.\ndataloader_test = torch.utils.data.DataLoader(\n    dataset_test, batch_size=1, shuffle=False, drop_last=False, num_workers=num_workers\n)\n\n\n# Next, we add a small helper function to generate embeddings of our images\ndef generate_embeddings(model, dataloader):\n    \"\"\"Generates representations for all images in the dataloader\"\"\"\n    embeddings = []\n    filenames = []\n    with torch.no_grad():\n        for img, label, fnames in dataloader:\n            img = img.to(model.device)\n            emb = model.backbone(img).flatten(start_dim=1)\n            embeddings.append(emb)\n            filenames.extend(fnames)\n\n    embeddings = torch.cat(embeddings, 0)\n    embeddings = normalize(embeddings)\n    return embeddings, filenames\n\n\n# Generate the embeddings (remember to put the model in eval mode).\nmodel.eval()\nembeddings, fnames = generate_embeddings(model, dataloader_test)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now, we can use the embeddings to search for nearest neighbors.\n\nWe choose three example images. For each example image, we find 50 nearest neighbors.\nThen, we plot the critical findings in the example image (dark blue) and the distribution\nof the critical findings in the nearest neighbor images (light blue) as bar plots.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Transform the original bounding box annotations to multiclass labels.\nfnames = [fname.split(\".\")[0] for fname in fnames]\n\ndf = pandas.read_csv(\"/datasets/vinbigdata/train.csv\")\nclasses = list(np.unique(df.class_name))\nfilenames = list(np.unique(df.image_id))\n\n# Iterate over all bounding boxes and add a one-hot label if an image contains\n# a bounding box of a given class, after that, the array \"multilabels\" will\n# contain a row for every image in the input dataset and each row of the\n# array contains a one-hot vector of critical findings for this image.\nmultilabels = np.zeros((len(dataset_test.get_filenames()), len(classes)))\nfor filename, label in zip(df.image_id, df.class_name):\n    try:\n        i = fnames.index(filename.split(\".\")[0])\n        j = classes.index(label)\n        multilabels[i, j] = 1.0\n    except Exception:\n        pass\n\n\ndef plot_knn_multilabels(\n    embeddings, multilabels, samples_idx, filenames, n_neighbors=50\n):\n    \"\"\"Plots multiple rows of random images with their nearest neighbors\"\"\"\n    # Let0s look at the nearest neighbors for some samples using the sklearn library.\n    nbrs = NearestNeighbors(n_neighbors=n_neighbors).fit(embeddings)\n    _, indices = nbrs.kneighbors(embeddings)\n\n    # Position the bars.\n    bar_width = 0.4\n    r1 = np.arange(multilabels.shape[1])\n    r2 = r1 + bar_width\n\n    # Loop through our randomly picked samples.\n    for idx in samples_idx:\n        fig = plt.figure()\n\n        bars1 = multilabels[idx]\n        bars2 = np.mean(multilabels[indices[idx]], axis=0)\n\n        plt.title(filenames[idx])\n        plt.bar(r1, bars1, color=\"steelblue\", edgecolor=\"black\", width=bar_width)\n        plt.bar(r2, bars2, color=\"lightsteelblue\", edgecolor=\"black\", width=bar_width)\n        plt.xticks(0.5 * (r1 + r2), classes, rotation=90)\n        plt.tight_layout()\n\n\n# Plot the distribution of the multilabels of the k nearest neighbors of\n# the three example images at indices 4111, 3340, and 1796.\nk = 20\nplot_knn_multilabels(embeddings, multilabels, [4111, 3340, 1796], fnames, n_neighbors=k)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The dark blue bars show the findings of the example image, while the light\nblue bars show how often each finding occurs among its nearest neighbors. A\nuseful embedding should give high light blue bars at the same findings as the\nexample and low bars elsewhere.\n\nThe first two examples have no critical finding, and ``No finding`` also\ndominates their neighborhoods. The embeddings therefore group these normal\nX-rays well. The third example has several findings. Each of its annotated\nfindings does show up among its neighbors to some degree, but the fractions\nare small and the neighborhood is dominated by a ``No finding`` majority.\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}