{
  "cells": [
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "EBL97zOSNOUb"
      },
      "source": [
        "<img width=\"800px\" src=\"../fidle/img/header.svg\"></img>\n",
        "\n",
        "# <!-- TITLE --> [OPT1] - Training setup optimization\n",
        "<!-- DESC --> The goal of this notebook is to go through a typical deep learning model training\n",
        "\n",
        "<!-- AUTHOR : Kamel Guerda (CNRS/IDRIS), Léo Hunout (CNRS/IDRIS) -->\n",
        "\n",
        "## Objectives :\n",
        "\n",
        "\n",
        "**Practice lab : Optimize your training process**"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wmsmK2lGelCE"
      },
      "source": [
        "## Introduction\n",
        "\n",
        "This Lab takes place as a pratical exercice of the [fidle](https://fidle.cnrs.fr/) online course N°16.\n",
        "\n",
        "\n",
        "The goal of this notebook is to go through a typical deep learning model training. We will see what can be changed to optimize this training setup but also good practices to make more efficient experiments.\n",
        "\n",
        "\n",
        "This notebook makes use of:\n",
        "- The CIFAR10 dataset\n",
        "- A Resnet model\n",
        "- Pytorch\n",
        "- A GPU (the notebook can be ran on Jean-Zay if you have an account, on Google collab with a 16go gpu or at home with a dedicated gpu by scaling down the batch_size)\n",
        "\n",
        "In particular we will work on:\n",
        "- the dataloader strategy used to load data\n",
        "- the model initial weights, in particular using a pretrained model\n",
        "- the learning rate and learning rate scheduler\n",
        "- the optimizer\n",
        "- visualizing and comparing results using python, tensorboard\n",
        "- various good practices/reminders\n",
        "\n",
        "> First, you can do a complete execution of the notebook.\n",
        "\n",
        "> **Then comeback from the start and follow the instructions to edit various components for better performance. You can also change them during the first execution if you have some intuitions about what should be changed and how.**\n",
        "\n",
        "> **In order to compare performance, only change the xxx_optim variables which are the one you will use in your optimized training**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UrJW8d_lqZ-l"
      },
      "outputs": [],
      "source": [
        "!nvidia-smi"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "527LDYwLf9gB"
      },
      "source": [
        "## Few imports"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mPEZLMywejMG"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import time\n",
        "import random\n",
        "import numpy as np\n",
        "\n",
        "import torch\n",
        "from torch.cuda.amp import autocast, GradScaler\n",
        "from torch.optim.lr_scheduler import _LRScheduler\n",
        "\n",
        "import torchvision\n",
        "import torchvision.transforms as transforms\n",
        "import torchvision.models as models\n",
        "from torchvision.models.resnet import ResNet18_Weights\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "from datetime import datetime\n",
        "from torch.utils.tensorboard import SummaryWriter"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G_DozO12fv8o"
      },
      "source": [
        "## Fix random seeds\n",
        "In order to have experiment reproductibility, it is a good practice to fix the random number generators seeds.\n",
        "\n",
        "Warning : there might be more seeds to set than you expect! Maths,visualization,transformations libraries, ..."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Y9jOl-D8ejWw"
      },
      "outputs": [],
      "source": [
        "random.seed(123)\n",
        "np.random.seed(123)\n",
        "torch.manual_seed(123)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9nZlyar5NOUr"
      },
      "source": [
        "## Some functions\n",
        "\n",
        "Below we define a few functions that will be used further in the notebook. \n",
        "\n",
        "**Do not change them unless you know what and why you are doing it.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JFQtFuDWNOUt"
      },
      "outputs": [],
      "source": [
        "def iter_dataloader(dataloader, epochs, args):\n",
        "    for epoch in range(epochs):\n",
        "        for i, (images, labels) in enumerate(dataloader):\n",
        "            # distribution of images and labels to all GPUs\n",
        "            images = images.to(args['device'], non_blocking=True)\n",
        "            labels = labels.to(args['device'], non_blocking=True)\n",
        "            \n",
        "def evaluate(dataloader, model, criterion, args):\n",
        "    '''\n",
        "    A simple loop for evaluation\n",
        "    '''\n",
        "    loss = 0\n",
        "    correct = 0\n",
        "    total = 0\n",
        "    with torch.no_grad():\n",
        "        for i, (images, labels) in enumerate(dataloader):\n",
        "            # distribution of images and labels to all GPUs\n",
        "            images = images.to(args['device'], non_blocking=True)\n",
        "            labels = labels.to(args['device'], non_blocking=True)\n",
        "            outputs = model(images)\n",
        "            loss = criterion(outputs,labels)\n",
        "            _, predicted = torch.max(outputs.data, 1)\n",
        "\n",
        "            loss += loss\n",
        "            total += labels.size(0)\n",
        "            correct += (predicted == labels).sum().item()\n",
        "    loss = (loss/total).item()\n",
        "    accuracy = (correct/total)*100\n",
        "    return loss, accuracy\n",
        "\n",
        "def train_default(train_loader, val_loader, model, optimizer, criterion, args):\n",
        "    '''\n",
        "    The default simple training loop\n",
        "    '''\n",
        "    train_losses = []\n",
        "    train_accuracies = []\n",
        "    val_losses = []\n",
        "    val_accuracies = []\n",
        "    time_start = time.time()\n",
        "    for epoch in range(args['epochs']):\n",
        "        print(\"Epoch \", epoch)\n",
        "        for i, (images, labels) in enumerate(train_loader):\n",
        "            # distribution of images and labels to all GPUs\n",
        "            images = images.to(args['device'], non_blocking=True)\n",
        "            labels = labels.to(args['device'], non_blocking=True)\n",
        "            \n",
        "            # Zero the parameter gradients\n",
        "            optimizer.zero_grad()\n",
        "\n",
        "            # Forward pass\n",
        "            outputs = model(images)\n",
        "            loss = criterion(outputs, labels)\n",
        "\n",
        "            # Backward pass\n",
        "            loss.backward()\n",
        "\n",
        "            # Optimize\n",
        "            optimizer.step()\n",
        "\n",
        "        # Evaluate at the end of the epoch on the train set\n",
        "        train_loss, train_accuracy = evaluate(train_loader, model, criterion, args)\n",
        "        print(\"\\t Train loss : \", train_loss, \"& Train accuracy : \", train_accuracy)\n",
        "        train_losses.append(train_loss)\n",
        "        train_accuracies.append(train_accuracy)                \n",
        "                \n",
        "        # Evaluate at the end of the epoch on the val set\n",
        "        val_loss, val_accuracy = evaluate(val_loader, model, criterion, args)\n",
        "        print(\"\\t Validation loss : \", val_loss, \"& Validation accuracy : \", val_accuracy)\n",
        "        val_losses.append(val_loss)\n",
        "        val_accuracies.append(val_accuracy)\n",
        "        \n",
        "    duration = time.time() - time_start\n",
        "    print('Finished Training in:', duration, 'seconds with mean epoch duration:', duration/args['epochs'], ' seconds')\n",
        "    results = {'model':model,\n",
        "               'train_losses': train_losses,\n",
        "               'train_accuracies': train_accuracies,\n",
        "               'val_losses': val_losses,\n",
        "               'val_accuracies': val_accuracies,\n",
        "               'duration':duration}\n",
        "    return results\n",
        "\n",
        "def explore_lrs(dataloader, \n",
        "                model, \n",
        "                optimizer,\n",
        "                args,\n",
        "                min_learning_rate_power=-8, \n",
        "                max_learning_rate_power = 1,\n",
        "                num_lrs=10,\n",
        "                steps_per_lr=50):\n",
        "  \n",
        "    lrs = np.logspace(min_learning_rate_power, max_learning_rate_power, num=num_lrs)\n",
        "    print(\"Learning rate space : \", lrs)\n",
        "    model_init_state = model.state_dict()\n",
        "\n",
        "    lrs_losses, lrs_metric_avg, lrs_metric_var =[], [],[]\n",
        "  \n",
        "    # Iterate through learning rates to test\n",
        "    for lr in lrs:\n",
        "        print(\"Testing lr:\", '{:.2e}'.format(lr))\n",
        "        # Reset model\n",
        "        model.load_state_dict(model_init_state)\n",
        "\n",
        "        # Change learning rate in optimizer\n",
        "        for group in optimizer.param_groups:\n",
        "            group['lr'] = lr\n",
        "\n",
        "        # Reset metric tracking\n",
        "        lr_losses =[]\n",
        "\n",
        "        # Training steps\n",
        "        for step in range(steps_per_lr):\n",
        "            images, labels = next(iter(dataloader))\n",
        "            # distribution of images and labels to all GPUs\n",
        "            images = images.to(args['device'], non_blocking=True)\n",
        "            labels = labels.to(args['device'], non_blocking=True)\n",
        "            optimizer.zero_grad()\n",
        "            outputs = model(images)\n",
        "            loss = criterion(outputs, labels)\n",
        "            loss.backward()\n",
        "            optimizer.step()\n",
        "            lr_losses.append(loss.item())\n",
        "        print(lr_losses)\n",
        "\n",
        "        # Compute loss average for lr\n",
        "        lr_loss_avg = np.mean(lr_losses) \n",
        "        lr_loss_avg = lr_losses[-1]\n",
        "\n",
        "        lrs_losses.append(lr_loss_avg)\n",
        "\n",
        "        # Compute metric (discounted average gradient of the loss)\n",
        "        lr_gradients = np.gradient(lr_losses)\n",
        "        lr_metric_avg = np.mean(lr_gradients)\n",
        "        lr_metric_var = np.var(lr_gradients)\n",
        "        lrs_metric_avg.append(lr_metric_avg)    \n",
        "        lrs_metric_var.append(lr_metric_var)\n",
        "        model.load_state_dict(model_init_state)\n",
        "\n",
        "    return lrs, lrs_losses, lrs_metric_avg, lrs_metric_var\n",
        "\n",
        "def plot_eval(lrs, lrs_losses, lrs_metric_avg, lrs_metric_var):\n",
        "    print(\"lrs: \", lrs)\n",
        "    print(\"lrs_losses: \", lrs_losses)\n",
        "    print(\"lrs_metric_avg: \", lrs_metric_avg)\n",
        "    print(\"lrs_metric_var: \", lrs_metric_var)\n",
        "    fig, axs = plt.subplots(3, figsize=(10,15))\n",
        "\n",
        "    axs[0].plot(lrs, lrs_losses, color='blue', label=\"losses_avg\")\n",
        "    axs[0].set_xlabel('learning rate', fontsize=15)\n",
        "    axs[0].set_ylabel('Loss', fontsize=15)\n",
        "    axs[0].set_xscale('log')\n",
        "    axs[0].set_yscale('symlog')\n",
        "    axs[0].set_ylim([0,  min(lrs_losses)*100])\n",
        "\n",
        "    axs[1].plot(lrs, lrs_metric_avg, color='red', label=\"discounted_metric_avg\")\n",
        "    axs[1].hlines(y=0, xmin=lrs[0], xmax=lrs[-1], linewidth=2, color='black')\n",
        "    axs[1].set_xlabel('learning rate', fontsize=15)\n",
        "    axs[1].set_ylabel('Metric average', fontsize=15)\n",
        "    axs[1].set_xscale('log')\n",
        "    axs[1].set_yscale('symlog')\n",
        "    axs[1].set_ylim([-abs(lrs_metric_avg[0])*100, abs(lrs_metric_avg[0])*100])\n",
        "\n",
        "    axs[2].plot(lrs, lrs_metric_var, color='green', label=\"discounted_metric_var\")\n",
        "    axs[2].set_xlabel('learning rate', fontsize=15)\n",
        "    axs[2].set_ylabel('Metric variance', fontsize=15)\n",
        "    axs[2].set_xscale('log')\n",
        "    axs[2].set_yscale('symlog')\n",
        "    axs[2].set_ylim([0, min(lrs_metric_var)*1000])\n",
        "\n",
        "    plt.show()\n",
        "    \n",
        "def compare_trainings(results_default, results_optim):\n",
        "    fig, axs = plt.subplots(2, figsize=(10,10))\n",
        "    fig.suptitle('Performance comparison', fontsize=18)    \n",
        "    \n",
        "    train_alpha = 0.5\n",
        "    \n",
        "    # Validation losses    \n",
        "    axs[0].plot(range(len(results_default['val_losses'])), results_default['val_losses'], color='blue', label=\"default val\")\n",
        "    axs[0].plot(range(len(results_optim['val_losses'])), results_optim['val_losses'], color='red', label=\"optim val\")\n",
        "\n",
        "    # Training losses    \n",
        "    axs[0].plot(range(len(results_default['train_losses'])), results_default['train_losses'], color='blue', label=\"default train\", linestyle='--', alpha = train_alpha)\n",
        "    axs[0].plot(range(len(results_optim['train_losses'])), results_optim['train_losses'], color='red', label=\"optim train\", linestyle='--', alpha = train_alpha)\n",
        "       \n",
        "    axs[0].set_xlabel('Epochs', fontsize=14)\n",
        "    axs[0].set_ylabel('Loss', fontsize=14)\n",
        "    axs[0].set_xscale('linear')\n",
        "    axs[0].set_yscale('linear')\n",
        "    max_loss = max(results_default['train_losses']+results_default['val_losses']+results_optim['train_losses']+results_optim['val_losses'])\n",
        "    axs[0].set_ylim([0,  max_loss])\n",
        "    axs[0].legend(loc=\"upper right\")\n",
        "    \n",
        "    # Validation accuracies\n",
        "    axs[1].plot(range(len(results_default['val_accuracies'])), results_default['val_accuracies'], color='blue', label=\"default val\")\n",
        "    axs[1].plot(range(len(results_optim['val_accuracies'])), results_optim['val_accuracies'], color='red', label=\"optim val\")\n",
        "\n",
        "    # Training default accuracies\n",
        "    axs[1].plot(range(len(results_default['train_accuracies'])), results_default['train_accuracies'], color='blue', label=\"default train\", linestyle='--', alpha=train_alpha)\n",
        "    axs[1].plot(range(len(results_optim['train_accuracies'])), results_optim['train_accuracies'], color='red', label=\"optim train\", linestyle='--', alpha=train_alpha)\n",
        "    \n",
        "    axs[1].set_xlabel('Epochs', fontsize=15)\n",
        "    axs[1].set_ylabel('Accuracy', fontsize=15)\n",
        "    axs[1].set_xscale('linear')\n",
        "    axs[1].set_yscale('linear')\n",
        "    axs[1].set_ylim([0,  100])\n",
        "    axs[1].legend(loc=\"lower right\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "USjwbaqvfvT9"
      },
      "source": [
        "## Training configuration variables\n",
        "For the first run, you can let all the values given by default.\n",
        "For the optimized run, you could changing some parameters. \n",
        ">In particular, you will have to change :\n",
        ">- the batch_size\n",
        ">- the learning rate"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vJRP94hFejjg"
      },
      "outputs": [],
      "source": [
        "args = {\n",
        "    'batch_size':64,\n",
        "    'epochs': 10,\n",
        "    'image_size': 224,\n",
        "    'learning_rate': 0.001,\n",
        "    'momentum': 0.9,\n",
        "    'weight_decay': 0.0001,\n",
        "    'download': True,\n",
        "    'device': torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\"),\n",
        "    'dataset_root_dir': os.getcwd(),\n",
        "}\n",
        "\n",
        "#################################################\n",
        "############# Modify the code below #############\n",
        "#################################################\n",
        "args_optim = {\n",
        "    'batch_size':64,\n",
        "    'epochs': 10,\n",
        "    'image_size': 224,\n",
        "    'learning_rate': 0.001,\n",
        "    'momentum': 0.9,\n",
        "    'weight_decay': 0.0001,\n",
        "    'download': True,\n",
        "    'device': torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\"),\n",
        "    'dataset_root_dir': os.getcwd(), \n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pfQP_RbKAU6N"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler (click to reveal)</summary>\n",
        "\n",
        "```python\n",
        "args_optim = {\n",
        "    'batch_size':512,\n",
        "    'epochs': 10,\n",
        "    'image_size': 224,\n",
        "    'learning_rate': 0.001,\n",
        "    'momentum': 0.9,\n",
        "    'weight_decay': 0.01,\n",
        "    'download': True,\n",
        "    'device': torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\"),\n",
        "    'dataset_root_dir': os.getcwd(), \n",
        "}\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b5CbvfOAfnQ9"
      },
      "source": [
        "## Data transformation and augmentation\n",
        "Below, we define the transformations to apply to each image when loaded.\n",
        "It can serve three main purposes:\n",
        "- having the data in the desired format for the model (systematic transformation)\n",
        "- correcting/normalizing the data (systematic transformation)\n",
        "- artificially increasing the amount of data by transforming the data  (random transformation)\n",
        "\n",
        "Warning : the evaluation dataset should always be the same so you should not apply random transformations to it.\n",
        "\n",
        "> Enrich the transformations by using the provided by torchvision : https://pytorch.org/vision/0.12/transforms.html\n",
        "\n",
        "> **Change transform_optim and val_transform_optim only**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I8d51hBifiDH"
      },
      "outputs": [],
      "source": [
        "transform = transforms.Compose([transforms.ToTensor()])     # convert the PIL Image to a tensor\n",
        "val_transform = transforms.Compose([transforms.ToTensor()]) # convert the PIL Image to a tensor\n",
        "                \n",
        "#################################################\n",
        "############# Modify the code below #############\n",
        "#################################################\n",
        "transform_optim = transforms.Compose([transforms.ToTensor()])     # convert the PIL Image to a tensor\n",
        "val_transform_optim = transforms.Compose([transforms.ToTensor()]) # convert the PIL Image to a tensor"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VZp4xMdxrJs9"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "\n",
        "    \n",
        "```python\n",
        "transform_optim = transforms.Compose([ \n",
        "    transforms.RandomHorizontalFlip(),              # Horizontal Flip - Data Augmentation\n",
        "    transforms.ToTensor()                          # convert the PIL Image to a tensor\n",
        "    ])\n",
        "\n",
        "val_transform_optim = transforms.Compose([\n",
        "                transforms.ToTensor()                           # convert the PIL Image to a tensor\n",
        "                ])\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rYIkzw02fqnd"
      },
      "source": [
        "## Dataset\n",
        "In the cell below, we define the dataset.\n",
        "Here we have two subset:\n",
        "- a training subset for model optimization\n",
        "- a test subset for model evaluation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RImKrDEwe-Y7"
      },
      "outputs": [],
      "source": [
        "train_dataset = torchvision.datasets.CIFAR10(root=args['dataset_root_dir']+'/CIFAR_10', train=True, download=args['download'], transform=transform)\n",
        "\n",
        "val_dataset = torchvision.datasets.CIFAR10(root=args['dataset_root_dir']+'/CIFAR_10', train=False, download=args['download'], transform=val_transform)\n",
        "\n",
        "train_dataset_optim = torchvision.datasets.CIFAR10(root=args_optim['dataset_root_dir']+'/CIFAR_10', train=True, download=args_optim['download'], transform=transform_optim)\n",
        "\n",
        "val_dataset_optim = torchvision.datasets.CIFAR10(root=args_optim['dataset_root_dir']+'/CIFAR_10', train=False, download=args_optim['download'], transform=val_transform_optim)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tFMn2WRHgDko"
      },
      "source": [
        "## Dataloader\n",
        "The DataLoader class in PyTorch is responsible for loading and batching data from a dataset object, such as a PyTorch tensor or a NumPy array.\n",
        "It works by creating a Python iterable over the dataset and yielding a batch of data at each iteration.\n",
        "\n",
        "Those batches will be fed to the model for training or inference.\n",
        "\n",
        "The DataLoader class also provides various options for shuffling, batching, and parallelizing the data loading process, making it a useful tool for efficient and flexible data handling in PyTorch.\n",
        "> Take a look at the DataLoader documentation : https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader\n",
        "\n",
        "> Optimize the dataloader by taking advantage of parallelism and smart use of computational ressources :\n",
        ">- batch_size\n",
        ">- pin_memory\n",
        ">- prefetch_factor \n",
        ">- persistent_workers \n",
        ">- num_workers"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "r9Mp67_fgIGN"
      },
      "outputs": [],
      "source": [
        "train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n",
        "                                           batch_size=args['batch_size'],\n",
        "                                           shuffle=True,\n",
        "                                           drop_last=True)\n",
        "\n",
        "val_loader = torch.utils.data.DataLoader(dataset=val_dataset,    \n",
        "                                         batch_size=args['batch_size'],\n",
        "                                         shuffle=False,\n",
        "                                         drop_last=True)\n",
        "\n",
        "#################################################\n",
        "############# Modify the code below #############\n",
        "#################################################\n",
        "train_loader_optim = torch.utils.data.DataLoader(dataset=train_dataset,\n",
        "                                           batch_size=args_optim['batch_size'],\n",
        "                                           shuffle=True,\n",
        "                                           drop_last=True)\n",
        "\n",
        "val_loader_optim = torch.utils.data.DataLoader(dataset=val_dataset,    \n",
        "                                         batch_size=args_optim['batch_size'],\n",
        "                                         shuffle=False,\n",
        "                                         drop_last=True)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mvMxD20VNOU8"
      },
      "outputs": [],
      "source": [
        "%timeit -r 1 -n 1 iter_dataloader(train_loader, 1, args)\n",
        "%timeit -r 1 -n 1 iter_dataloader(train_loader_optim, 1, args_optim)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Vegex5s0gIVF"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "WIP : Quelques explications\n",
        "\n",
        "```python\n",
        "train_loader_optim = torch.utils.data.DataLoader(dataset=train_dataset_optim,\n",
        "                                                 batch_size=args_optim['batch_size'],\n",
        "                                                 shuffle=True,\n",
        "                                                 drop_last=True,\n",
        "                                                 num_workers=10,\n",
        "                                                 persistent_workers=True,\n",
        "                                                 pin_memory=True,\n",
        "                                                 prefetch_factor=10)\n",
        "\n",
        "val_loader_optim = torch.utils.data.DataLoader(dataset=val_dataset_optim,    \n",
        "                                               batch_size=args_optim['batch_size'],\n",
        "                                               shuffle=False,\n",
        "                                               drop_last=True,\n",
        "                                               num_workers=10,\n",
        "                                               persistent_workers=True,\n",
        "                                               pin_memory=True,\n",
        "                                               prefetch_factor=10)\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2_yVrvKvgIt0"
      },
      "source": [
        "## Model\n",
        "\n",
        "> Do not forget to verify that you use the right compute ressources for your model\n",
        "\n",
        "> By default, the model resnet18 is initialized with random weights but you could try using a pretrained model : https://pytorch.org/vision/main/models/generated/torchvision.models.resnet18.html#torchvision.models.ResNet18_Weights"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NCQgZOx6gI6Q"
      },
      "outputs": [],
      "source": [
        "model = models.resnet18()\n",
        "model = model.to(args['device'])\n",
        "model.name = 'Resnet-18'\n",
        "print(\"Stock model on device:\", next(model.parameters()).device)\n",
        "#################################################\n",
        "############# Modify the code below #############\n",
        "#################################################\n",
        "model_optim = models.resnet18()\n",
        "model_optim = model_optim.to(args_optim['device'])\n",
        "model_optim.name = 'Resnet-18'\n",
        "print(\"Optimized model on device:\", next(model_optim.parameters()).device)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "p4umlBOmghZX"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "    \n",
        "```python\n",
        "model_optim = models.resnet18(ResNet18_Weights)\n",
        "model_optim = model_optim.to(args_optim['device'])\n",
        "model_optim.name = 'Resnet-18'\n",
        "print(\"Optimized model on device:\", next(model_optim.parameters()).device)\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ur1uA38ugiBl"
      },
      "source": [
        "## Loss\n",
        "We use a standart loss for classification.\n",
        "\n",
        "For the comparison, if you change the loss, change it for both.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sxSZEKKogiJe"
      },
      "outputs": [],
      "source": [
        "criterion = torch.nn.CrossEntropyLoss()\n",
        "criterion_optim = torch.nn.CrossEntropyLoss()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qJadxpf_giT4"
      },
      "source": [
        "## Optimizer\n",
        "\n",
        "> In order to speed up the training, you can try to use a different optimizer: https://pytorch.org/docs/stable/optim.html#base-class"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3fsqrktLgiaJ"
      },
      "outputs": [],
      "source": [
        "optimizer = torch.optim.SGD(model.parameters(), args['learning_rate'], args['momentum'], args['weight_decay'])\n",
        "#################################################\n",
        "############# Modify the code below #############\n",
        "#################################################\n",
        "optimizer_optim = torch.optim.SGD(model.parameters(), args_optim['learning_rate'], args_optim['momentum'], args_optim['weight_decay'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZEcyEt1Ig21T"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "\n",
        "```python\n",
        "optimizer_optim = torch.optim.AdamW(model_optim.parameters(), lr = args_optim['learning_rate'], weight_decay=args_optim['weight_decay'])\n",
        "```\n",
        "</details>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3wcKevBct--P"
      },
      "source": [
        "## Learning rate scheduler\n",
        "In order to adjust the learning rate over iterations/epochs, we can make use of a learning rate scheduler.\n",
        "\n",
        "To use a LR scheduler, you will need to :\n",
        "- instantiate the scheduler (in the coding cell below)\n",
        "- adapt the training loop (in the \"Training\" section)\n",
        "\n",
        "Take a look at this page : https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate which: \n",
        "- describes how to use a scheduler (warning : some scheduler are updated at a step level and others at an epoch level)\n",
        "- lists the available schedulers (you could also create your own starting from the _LRScheduler class)\n",
        "\n",
        "> **You can define your scheduler here.**\n",
        "\n",
        "> **You will have to modify the training loop later on.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ISanTSFWuBps"
      },
      "outputs": [],
      "source": [
        "scheduler = None\n",
        "#################################################\n",
        "############# Modify the code below #############\n",
        "#################################################\n",
        "scheduler_optim = None"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KvnPRnuJvjVx"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "    \n",
        "```python\n",
        "scheduler_optim = torch.optim.lr_scheduler.OneCycleLR(optimizer_optim, \n",
        "                                                      max_lr=args_optim['learning_rate'], \n",
        "                                                      steps_per_epoch = len(train_loader_optim), \n",
        "                                                      epochs=args_optim['epochs'])\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YxPlz4U3g9Yv"
      },
      "source": [
        "## Model training (reference performances)\n",
        "Once we have all our main actors, we can setup the stage that is our training loop.\n",
        "\n",
        "Below is used a typical loop as you can find in https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html\n",
        "> **Run it a first time to have a performance baseline with all the default values.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cy1QzZxwNOVH"
      },
      "outputs": [],
      "source": [
        "results_default = train_default(train_loader, val_loader, model, optimizer, criterion, args)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7vU3uot9v3hc"
      },
      "source": [
        "## Speeding up the hyperparameter search : Learning Rate Finder\n",
        "Wether we are using a scheduler or not, we need to determine either : \n",
        "- the constant learning rate you want to use, \n",
        "- or the maximum learning rate used by the scheduler.\n",
        "\n",
        "If you are in the first situation, you just want a good all-rounder learning rate to have a relatively fast conversion and minimize the oscillations at the end of the convergence.\n",
        "\n",
        "In the second situation, you can focus more on having the fastest inital convergence as the oscillations will be generally taken care by a decreasing learning rate strategy. Thus, we want the highest maximum learning rate possible.\n",
        "\n",
        "It would be ideal to find the best learning rate quickly in order to speedup our hyperparameter search.\n",
        "Various strategy more or less complex exists to find an estimate of this value.\n",
        "Below, we try to find the learning rate by doing a few steps on a range of learning rates. We evaluate each learning rate to determine the best one to choose for our full training.\n",
        "\n",
        "> **As this step can take quite some time, we provided you with some values for the default config which you are not supposed to change anyway. You can find them in the next spoiler**\n",
        "\n",
        "> **Uncomment explore_lrs to rerun the exploration, otherwise you can reuse the given values.**\n",
        "\n",
        "> **Be careful to re-run this cell to reset the model and optimizer,...  to have a \"fresh\" exploration each time**\n",
        "\n",
        "> **Also if you change the optimizer for the optimized run, change it also here to find the best learning rate for that optimizer.** Or rerun the cell where you defined it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kG45YwwY5Hut"
      },
      "outputs": [],
      "source": [
        "lrs, lrs_losses, lrs_metric_avg, lrs_metric_var = explore_lrs(train_loader_optim,\n",
        "                                                              model_optim, \n",
        "                                                              optimizer_optim,\n",
        "                                                              args_optim,\n",
        "                                                              min_learning_rate_power=-6, \n",
        "                                                              max_learning_rate_power = 1,\n",
        "                                                              num_lrs=8,\n",
        "                                                              steps_per_lr=100) "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pDmkRbleNOVL"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "    \n",
        "```python\n",
        "lrs=[1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01]\n",
        "lrs_losses=  [7.502097129821777, 7.22658634185791, 5.24326229095459, 1.7600191831588745, 1.4037541151046753, 2.136382579803467, 2.1029751300811768, 446.49951171875]\n",
        "lrs_metric_avg=[0.0017601490020751954, -0.005245075225830078, -0.041641921997070314, -0.07478624820709229, -0.007052739858627319, 0.04763659238815308, 0.03924872875213623, 9.939403522014619]\n",
        "lrs_metric_var=[0.0006510000222988311, 0.0004144988674492198, 0.000668689274974986, 0.013876865854565344, 0.001481160611942387, 0.3384368026131311, 0.8817071610439394, 2157852536609.2454]\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gpFPWNZXv670"
      },
      "outputs": [],
      "source": [
        "plot_eval(lrs, lrs_losses, lrs_metric_avg, lrs_metric_var)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pVw14RZ9NOVO"
      },
      "source": [
        "## Optimize the training loop\n",
        "\n",
        "> Adapt the dataset transformations, batch_size & dataloader, lr & lr_scheduler, and optimizer in order to achieve better classification results in less time. \n",
        "\n",
        "> Change this training loop to include:\n",
        "> - a learning rate scheduler : https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate\n",
        "> - a strategy such as early stopping or patience : https://www.kaggle.com/code/akhileshrai/tutorial-early-stopping-vanilla-rnn-pytorch?scriptVersionId=26440051&cellId=10#4.-Early-Stopping\n",
        "\n",
        "> **Also think about changing the call to the function if you added arguments.**\n",
        "\n",
        "> For you, we added automatic mixed precision which will be seen in the next course\n",
        "\n",
        "> **BEFORE RUNNING, WE NEED TO REINITIALIZE THE MODEL, OPTIMIZER AND SCHEDULER FOR A FAIR FIGHT. Rewrite below the changes you have brought to them.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "hF-p2CCsNOVO"
      },
      "outputs": [],
      "source": [
        "model_optim = models.resnet18().to(args_optim['device'])\n",
        "model_optim.name = 'Resnet-18'\n",
        "optimizer_optim = torch.optim.SGD(model_optim.parameters(), args_optim['learning_rate'], args_optim['momentum'], args_optim['weight_decay'])\n",
        "scheduler_optim = None"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "q79Y1wzENOVQ"
      },
      "outputs": [],
      "source": [
        "def train_optim(train_loader, val_loader, model, optimizer, criterion, args):\n",
        "    '''\n",
        "    The default simple training loop\n",
        "    '''\n",
        "    train_losses = []\n",
        "    train_accuracies = []\n",
        "    val_losses = []\n",
        "    val_accuracies = []\n",
        "    time_start = time.time()\n",
        "    for epoch in range(args['epochs']):\n",
        "        print(\"Epoch \", epoch)\n",
        "        for i, (images, labels) in enumerate(train_loader):\n",
        "            # distribution of images and labels to all GPUs\n",
        "            images = images.to(args['device'], non_blocking=True)\n",
        "            labels = labels.to(args['device'], non_blocking=True)\n",
        "            \n",
        "            # Zero the parameter gradients\n",
        "            optimizer.zero_grad()\n",
        "\n",
        "            # Forward pass\n",
        "            outputs = model(images)\n",
        "            loss = criterion(outputs, labels)\n",
        "\n",
        "            # Backward pass\n",
        "            loss.backward()\n",
        "\n",
        "            # Optimize\n",
        "            optimizer.step()\n",
        "\n",
        "        # Evaluate at the end of the epoch on the train set\n",
        "        train_loss, train_accuracy = evaluate(train_loader, model, criterion, args)\n",
        "        print(\"\\t Train loss : \", train_loss, \"& Train accuracy : \", train_accuracy)\n",
        "        train_losses.append(train_loss)\n",
        "        train_accuracies.append(train_accuracy)                \n",
        "                \n",
        "        # Evaluate at the end of the epoch on the val set\n",
        "        val_loss, val_accuracy = evaluate(val_loader, model, criterion, args)\n",
        "        print(\"\\t Validation loss : \", val_loss, \"& Validation accuracy : \", val_accuracy)\n",
        "        val_losses.append(val_loss)\n",
        "        val_accuracies.append(val_accuracy)\n",
        "    duration = time.time() - time_start\n",
        "    print('Finished Training in:', duration, 'seconds with mean epoch duration:', duration/args['epochs'], ' seconds')\n",
        "    results = {'model':model,\n",
        "               'train_losses': train_losses,\n",
        "               'train_accuracies': train_accuracies,\n",
        "               'val_losses': val_losses,\n",
        "               'val_accuracies': val_accuracies,\n",
        "               'duration':duration}\n",
        "    return results\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z_T19pdUNOVR"
      },
      "source": [
        "<details>\n",
        "<summary>Spoiler</summary>\n",
        "    \n",
        "```python\n",
        "def train_optim(train_loader, val_loader, model, optimizer, criterion, scheduler, args):\n",
        "    '''\n",
        "    The default simple training loop\n",
        "    '''\n",
        "    train_losses = []\n",
        "    train_accuracies = []\n",
        "    val_losses = []\n",
        "    val_accuracies = []\n",
        "    time_start = time.time()\n",
        "    scaler = GradScaler()\n",
        "    for epoch in range(args['epochs']):\n",
        "        print(\"Epoch \", epoch)\n",
        "        for i, (images, labels) in enumerate(train_loader):\n",
        "            # distribution of images and labels to all GPUs\n",
        "            images = images.to(args['device'], non_blocking=True)\n",
        "            labels = labels.to(args['device'], non_blocking=True)\n",
        "            \n",
        "            # Zero the parameter gradients\n",
        "            optimizer.zero_grad()\n",
        "\n",
        "            # Forward pass\n",
        "            with autocast():\n",
        "                outputs = model(images)\n",
        "                loss = criterion(outputs, labels)\n",
        "\n",
        "            # Backward pass\n",
        "            scaler.scale(loss).backward()\n",
        "            \n",
        "            # Optimize\n",
        "            scaler.step(optimizer)\n",
        "            \n",
        "            # Updates the scale for next iteration.\n",
        "            scaler.update()\n",
        "            \n",
        "            # Update Learning Rate scheduler, warning some schedulers are updated every epoch and not step.\n",
        "            if scheduler is not None:\n",
        "                scheduler.step()\n",
        "\n",
        "        # Evaluate at the end of the epoch\n",
        "        train_loss, train_accuracy = evaluate(train_loader, model, criterion, args)\n",
        "        print(\"\\t Train loss : \", train_loss, \"& Train accuracy : \", train_accuracy)\n",
        "        train_losses.append(train_loss)\n",
        "        train_accuracies.append(train_accuracy)                \n",
        "                \n",
        "        # Evaluate at the end of the epoch\n",
        "        val_loss, val_accuracy = evaluate(val_loader, model, criterion, args)\n",
        "        print(\"\\t Validation loss : \", val_loss, \"& Validation accuracy : \", val_accuracy)\n",
        "        val_losses.append(val_loss)\n",
        "        val_accuracies.append(val_accuracy)\n",
        "    duration = time.time() - time_start\n",
        "    print('Finished Training in:', duration, 'seconds with mean epoch duration:', duration/args['epochs'], ' seconds')\n",
        "    results = {'model':model,\n",
        "               'train_losses': train_losses,\n",
        "               'train_accuracies': train_accuracies,\n",
        "               'val_losses': val_losses,\n",
        "               'val_accuracies': val_accuracies,\n",
        "               'duration':duration}\n",
        "    return results\n",
        "```    \n",
        "</details>"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Xodf9IltNOVT"
      },
      "outputs": [],
      "source": [
        "results_optim = train_optim(train_loader_optim, val_loader_optim, model_optim, optimizer_optim, criterion_optim, args_optim)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MqMatOlMhO8X"
      },
      "source": [
        "## Classification performances comparison\n",
        "\n",
        "> Take a look at\n",
        ">- the loss and accuracy evolution\n",
        ">- the difference in timings between the two runs"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_ICf-vY3NOVU"
      },
      "outputs": [],
      "source": [
        "print(\"Duration for default setup training:\", results_default[\"duration\"])\n",
        "print(\"Duration for optim setup training:\", results_optim[\"duration\"])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "upDC963kNOVV"
      },
      "outputs": [],
      "source": [
        "compare_trainings(results_default, results_optim)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "weOLNx69hQh6"
      },
      "source": [
        "## Tensorboard\n",
        "Below we added a profiler and a logger for tensorboard. If you want to do it yourself in future codes, you can take example on the following documentations::\n",
        "- Pytorch : https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html\n",
        "- IDRIS : http://www.idris.fr/jean-zay/pre-post/jean-zay-tensorboard.html\n",
        "\n",
        "> Try to add another metric to the logger, for example the validation loss at each epoch."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0qRmXet6NOVW"
      },
      "outputs": [],
      "source": [
        "def train_default_tensorboard(train_loader, val_loader, model, optimizer, criterion, args, exp_name):\n",
        "    log_dir = \"./logs/\"+exp_name\n",
        "    writer = SummaryWriter(log_dir)\n",
        "    \n",
        "    train_losses = []\n",
        "    train_accuracies = []\n",
        "    val_losses = []\n",
        "    val_accuracies = []\n",
        "    time_start = time.time()\n",
        "    with torch.profiler.profile(\n",
        "        schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=2),\n",
        "        on_trace_ready=torch.profiler.tensorboard_trace_handler(log_dir),\n",
        "        record_shapes=True,\n",
        "        profile_memory=True,\n",
        "        with_stack=True\n",
        "    ) as prof:\n",
        "        for epoch in range(args['epochs']):\n",
        "            print(\"Epoch \", epoch)\n",
        "            for i, (images, labels) in enumerate(train_loader):\n",
        "                # distribution of images and labels to all GPUs\n",
        "                images = images.to(args['device'], non_blocking=True)\n",
        "                labels = labels.to(args['device'], non_blocking=True)\n",
        "\n",
        "                # Zero the parameter gradients\n",
        "                optimizer.zero_grad()\n",
        "\n",
        "                # Forward pass\n",
        "                outputs = model(images)\n",
        "                loss = criterion(outputs, labels)\n",
        "                \n",
        "                # Log a scalar (loss)\n",
        "                writer.add_scalar(\"Loss/train\", loss, i+epoch*len(train_loader))\n",
        "                \n",
        "                # Backward pass\n",
        "                loss.backward()\n",
        "\n",
        "                # Optimize\n",
        "                optimizer.step()\n",
        "                \n",
        "                # Indicate to profiler when a step is over\n",
        "                prof.step()\n",
        "                \n",
        "            # Evaluate at the end of the epoch on the train set\n",
        "            train_loss, train_accuracy = evaluate(train_loader, model, criterion, args)\n",
        "            print(\"\\t Train loss : \", train_loss, \"& Train accuracy : \", train_accuracy)\n",
        "            train_losses.append(train_loss)\n",
        "            train_accuracies.append(train_accuracy)                \n",
        "\n",
        "            # Evaluate at the end of the epoch on the val set\n",
        "            val_loss, val_accuracy = evaluate(val_loader, model, criterion, args)\n",
        "            print(\"\\t Validation loss : \", val_loss, \"& Validation accuracy : \", val_accuracy)\n",
        "            val_losses.append(val_loss)\n",
        "            val_accuracies.append(val_accuracy)\n",
        "    duration = time.time() - time_start\n",
        "    print('Finished Training in:', duration, 'seconds with mean epoch duration:', duration/args['epochs'], ' seconds')\n",
        "    results = {'model':model,\n",
        "               'train_losses': train_losses,\n",
        "               'train_accuracies': train_accuracies,\n",
        "               'val_losses': val_losses,\n",
        "               'val_accuracies': val_accuracies,\n",
        "               'duration':duration}\n",
        "    return results"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mAPz5qdYNOVX"
      },
      "outputs": [],
      "source": [
        "args[\"epochs\"] = 1\n",
        "_ = train_default_tensorboard(train_loader, val_loader, model, optimizer, criterion, args, \"default_perf\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VlUFsWoVNOVa"
      },
      "outputs": [],
      "source": [
        "# Load the TensorBoard notebook extension\n",
        "!pip install torch_tb_profiler\n",
        "%load_ext tensorboard\n",
        "%tensorboard --logdir logs"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "provenance": []
    },
    "gpuClass": "standard",
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}