{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-1 fw=all -->\n",
    "\n",
    "# Fine-Tuning\n",
    "\n",
    "In earlier chapters, we discussed how to train models on the Fashion-MNIST training dataset with only 60000 images. We also described ImageNet, the most widely used large-scale image dataset in academia, which has more than 10 million images and 1000 objects. However, the size of the dataset that we usually encounter is between those of the two datasets.\n",
    "\n",
    "\n",
    "Suppose that we want to recognize different types of chairs from images, and then recommend purchase links to users. \n",
    "One possible method is to first identify\n",
    "100 common chairs,\n",
    "take 1000 images of different angles for each chair, \n",
    "and then train a classification model on the collected image dataset.\n",
    "Although this chair dataset may be larger than the Fashion-MNIST dataset,\n",
    "the number of examples is still less than one-tenth of \n",
    "that in ImageNet.\n",
    "This may lead to overfitting of complicated models \n",
    "that are suitable for ImageNet on this chair dataset.\n",
    "Besides, due to the limited amount of training examples,\n",
    "the accuracy of the trained model\n",
    "may not meet practical requirements.\n",
    "\n",
    "\n",
    "In order to address the above problems,\n",
    "an obvious solution is to collect more data.\n",
    "However, collecting and labeling data can take a lot of time and money.\n",
    "For example, in order to collect the ImageNet dataset, researchers have spent millions of dollars from research funding.\n",
    "Although the current data collection cost has been significantly reduced, this cost still cannot be ignored.\n",
    "\n",
    "\n",
    "Another solution is to apply *transfer learning* to transfer the knowledge learned from the *source dataset* to the *target dataset*.\n",
    "For example, although most of the images in the ImageNet dataset have nothing to do with chairs, the model trained on this dataset may extract more general image features, which can help identify edges, textures, shapes, and object composition.\n",
    "These similar features may\n",
    "also be effective for recognizing chairs.\n",
    "\n",
    "\n",
    "## Steps\n",
    "\n",
    "\n",
    "In this section, we will introduce a common technique in transfer learning: *fine-tuning*. As shown in the figure, fine-tuning consists of the following four steps:\n",
    "\n",
    "\n",
    "1. Pretrain a neural network model, i.e., the *source model*, on a source dataset (e.g., the ImageNet dataset).\n",
    "1. Create a new neural network model, i.e., the *target model*. This copies all model designs and their parameters on the source model except the output layer. We assume that these model parameters contain the knowledge learned from the source dataset and this knowledge will also be applicable to the target dataset. We also assume that the output layer of the source model is closely related to the labels of the source dataset; thus it is not used in the target model.\n",
    "1. Add an output layer to the target model, whose number of outputs is the number of categories in the target dataset. Then randomly initialize the model parameters of this layer.\n",
    "1. Train the target model on the target dataset, such as a chair dataset. The output layer will be trained from scratch, while the parameters of all the other layers are fine-tuned based on the parameters of the source model.\n",
    "\n",
    "![Fine tuning.](../img/finetune.svg)\n",
    "\n",
    "When target datasets are much smaller than source datasets, fine-tuning helps to improve models' generalization ability.\n",
    "\n",
    "\n",
    "## Hot Dog Recognition\n",
    "\n",
    "Let's demonstrate fine-tuning via a concrete case:\n",
    "hot dog recognition. \n",
    "We will fine-tune a ResNet model on a small dataset,\n",
    "which was pretrained on the ImageNet dataset.\n",
    "This small dataset consists of\n",
    "thousands of images with and without hot dogs.\n",
    "We will use the fine-tuned model to recognize \n",
    "hot dogs from images."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-hot-dog-recognition"
   },
   "source": [
    "%matplotlib inline\n",
    "import os\n",
    "from d2l import jax as d2l\n",
    "from d2l.nnx_resnet import ResNet50, Bottleneck\n",
    "from flax import nnx\n",
    "import jax\n",
    "from jax import numpy as jnp\n",
    "import optax\n",
    "import numpy as np\n",
    "import tensorflow as tf  # only used for tf.data input pipeline\n",
    "\n",
    "# Activation (gradient) checkpointing. Fine-tuning ResNet-50 at batch size 128\n",
    "# would otherwise hold the whole forward graph's activations live for the\n",
    "# backward pass (~23 GB). Wrapping each residual block (`Bottleneck`) in\n",
    "# `nnx.remat` recomputes that block's activations during backprop instead of\n",
    "# storing them, cutting the peak to ~6 GB. `nnx.remat` propagates state\n",
    "# correctly, so gradients and batch-norm running statistics are identical to\n",
    "# the un-checkpointed model.\n",
    "if not getattr(Bottleneck, '_d2l_remat', False):\n",
    "    Bottleneck.__call__ = nnx.remat(Bottleneck.__call__)\n",
    "    Bottleneck._d2l_remat = True"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-2 fw=all -->\n",
    "\n",
    "### Reading the Dataset\n",
    "\n",
    "The hot dog dataset we use was taken from online images.\n",
    "This dataset consists of\n",
    "1400 positive-class images containing hot dogs,\n",
    "and as many negative-class images containing other foods.\n",
    "1000 images of both classes are used for training and the rest are for testing.\n",
    "\n",
    "\n",
    "After unzipping the downloaded dataset,\n",
    "we obtain two folders `hotdog/train` and `hotdog/test`. Both folders have `hotdog` and `not-hotdog` subfolders, either of which contains images of\n",
    "the corresponding class."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-reading-the-dataset-1"
   },
   "source": [
    "\n",
    "d2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip', \n",
    "                         'fba480ffa8aa7e0febbb511d181409f899b9baa5')\n",
    "\n",
    "data_dir = d2l.download_extract('hotdog')"
   ],
   "execution_count": 2,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-3 fw=all -->\n",
    "\n",
    "We create two instances to read all the image files in the training and testing datasets, respectively."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-reading-the-dataset-2"
   },
   "source": [
    "# Load images as (PIL.Image, label) lists for compatibility with show_images\n",
    "from PIL import Image as _PILImage\n",
    "import pathlib\n",
    "\n",
    "def _load_image_folder(path):\n",
    "    \"\"\"Load images from a directory with class subfolders, returning\n",
    "    a list of (PIL.Image, class_index) tuples.\"\"\"\n",
    "    path = pathlib.Path(path)\n",
    "    class_names = sorted([p.name for p in path.iterdir() if p.is_dir()])\n",
    "    class_to_idx = {c: i for i, c in enumerate(class_names)}\n",
    "    items = []\n",
    "    for cls in class_names:\n",
    "        for img_path in sorted((path / cls).iterdir()):\n",
    "            try:\n",
    "                img = _PILImage.open(str(img_path)).convert('RGB')\n",
    "                items.append((img, class_to_idx[cls]))\n",
    "            except Exception:\n",
    "                continue\n",
    "    return items\n",
    "\n",
    "train_imgs = _load_image_folder(os.path.join(data_dir, 'train'))\n",
    "test_imgs = _load_image_folder(os.path.join(data_dir, 'test'))"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-4 fw=all -->\n",
    "\n",
    "The first 8 positive examples and the last 8 negative images are shown below. As you can see, the images vary in size and aspect ratio."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-reading-the-dataset-3"
   },
   "source": [
    "hotdogs = [train_imgs[i][0] for i in range(8)]\n",
    "not_hotdogs = [train_imgs[-i - 1][0] for i in range(8)]\n",
    "d2l.show_images(hotdogs + not_hotdogs, 2, 8, scale=1.4);"
   ],
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/png": "[encoded data, 307324 characters]"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-5 fw=all -->\n",
    "\n",
    "During training, we first crop a random area of random size and random aspect ratio from the image,\n",
    "and then scale this area\n",
    "to a $224 \\times 224$ input image. \n",
    "During testing, we scale both the height and width of an image to 256 pixels, and then crop a central $224 \\times 224$ area as input.\n",
    "In addition, \n",
    "for the three RGB (red, green, and blue) color channels\n",
    "we *standardize* their values channel by channel.\n",
    "Concretely,\n",
    "the mean value of a channel is subtracted from each value of that channel and then the result is divided by the standard deviation of that channel."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-reading-the-dataset-4"
   },
   "source": [
    "# Image preprocessing. We use `tf.image` ops so the pipeline can run\n",
    "# inside `tf.data.Dataset.map`. The ImageNet RGB mean/std normalization\n",
    "# matches the preprocessing expected by the pretrained ImageNet ResNet\n",
    "# weights (and the PyTorch/MXNet tabs).\n",
    "IMG_SIZE = 224\n",
    "_IMAGENET_MEAN = tf.constant([0.485, 0.456, 0.406], dtype=tf.float32)\n",
    "_IMAGENET_STD  = tf.constant([0.229, 0.224, 0.225], dtype=tf.float32)\n",
    "\n",
    "def _normalize(x):\n",
    "    return (tf.cast(x, tf.float32) / 255.0 - _IMAGENET_MEAN) / _IMAGENET_STD\n",
    "\n",
    "def train_preprocess(x):\n",
    "    # `x` is a (256, 256, 3) float32 RGB image with values in [0, 255].\n",
    "    x = tf.image.random_crop(x, size=(IMG_SIZE, IMG_SIZE, 3))\n",
    "    x = tf.image.random_flip_left_right(x)\n",
    "    return _normalize(x)\n",
    "\n",
    "def test_preprocess(x):\n",
    "    x = tf.image.resize_with_crop_or_pad(x, IMG_SIZE, IMG_SIZE)\n",
    "    return _normalize(x)"
   ],
   "execution_count": 5,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-6 fw=all -->\n",
    "\n",
    "### Defining and Initializing the Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-7 fw=jax -->\n",
    "\n",
    "We use an NNX ResNet-50 pretrained on ImageNet as the source model. Its\n",
    "official Microsoft safetensors are downloaded from Hugging Face and mapped\n",
    "directly into the stateful NNX model.\n",
    "If this model is used for the first time,\n",
    "Internet connection is required for download."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-defining-and-initializing-the-model-1"
   },
   "source": [
    "_dummy = jnp.zeros((1, IMG_SIZE, IMG_SIZE, 3), dtype=jnp.float32)\n",
    "pretrained_net = ResNet50.from_pretrained()"
   ],
   "execution_count": 6,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "text/plain": "Downloading bytes:           |  0.00B            "
     },
     "metadata": {}
    },
    {
     "output_type": "display_data",
     "data": {
      "text/plain": "Reconstructing (incomplete total...): |          |  0.00B /  0.00B            "
     },
     "metadata": {}
    },
    {
     "output_type": "display_data",
     "data": {
      "text/plain": "Fetching 1 files:   0%|          | 0/1 [00:00<?, ?it/s]"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-8 fw=jax -->\n",
    "\n",
    "The pretrained source model contains a convolutional backbone and a final\n",
    "`fc` layer (the 1000-way ImageNet classifier).\n",
    "The main purpose of this division is to facilitate the fine-tuning of model parameters of all layers but the output layer.\n",
    "The shape of the source model's classifier weight is shown below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-defining-and-initializing-the-model-2"
   },
   "source": [
    "pretrained_net.fc.kernel.shape"
   ],
   "execution_count": 7,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "(2048, 1000)"
     },
     "metadata": {},
     "execution_count": 7
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-9 fw=all -->\n",
    "\n",
    "As a fully connected layer, it transforms ResNet's final global average pooling outputs into 1000 class outputs of the ImageNet dataset.\n",
    "We then construct a new neural network as the target model. It is defined in the same way as the pretrained source model except that\n",
    "its number of outputs in the final layer\n",
    "is set to\n",
    "the number of classes in the target dataset (rather than 1000).\n",
    "\n",
    "In the code below, the model parameters before the output layer of the target model instance `finetune_net` are initialized to model parameters of the corresponding layers from the source model.\n",
    "Since these model parameters were obtained via pretraining on ImageNet, \n",
    "they are effective.\n",
    "Therefore, we can only use \n",
    "a small learning rate to *fine-tune* such pretrained parameters.\n",
    "In contrast, model parameters in the output layer are randomly initialized and generally require a larger learning rate to be learned from scratch.\n",
    "Letting the base learning rate be $\\eta$, a learning rate of $10\\eta$ will be used to iterate the model parameters in the output layer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-defining-and-initializing-the-model-3"
   },
   "source": [
    "finetune_net = ResNet50.from_pretrained()\n",
    "finetune_net.fc = nnx.Linear(2048, 2, rngs=nnx.Rngs(1))"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "text/plain": "Downloading bytes:           |  0.00B            "
     },
     "metadata": {}
    },
    {
     "output_type": "display_data",
     "data": {
      "text/plain": "Reconstructing (incomplete total...): |          |  0.00B /  0.00B            "
     },
     "metadata": {}
    },
    {
     "output_type": "display_data",
     "data": {
      "text/plain": "Fetching 1 files:   0%|          | 0/1 [00:00<?, ?it/s]"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-10 fw=all -->\n",
    "\n",
    "### Fine-Tuning the Model\n",
    "\n",
    "First, we define a training function `train_fine_tuning` that uses fine-tuning so it can be called multiple times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-fine-tuning-the-model-1"
   },
   "source": [
    "def _make_tf_dataset(img_dir, preprocess, batch_size, shuffle=False):\n",
    "    \"\"\"Create a tf.data.Dataset from an image folder directory.\"\"\"\n",
    "    ds = tf.keras.utils.image_dataset_from_directory(\n",
    "        img_dir, label_mode='int', image_size=(256, 256),\n",
    "        batch_size=None, shuffle=shuffle)\n",
    "    ds = ds.map(lambda x, y: (preprocess(x), y),\n",
    "                num_parallel_calls=tf.data.AUTOTUNE)\n",
    "    # Keep fixed shapes for training, but evaluate every test example.\n",
    "    ds = ds.batch(batch_size, drop_remainder=shuffle).prefetch(tf.data.AUTOTUNE)\n",
    "    return ds\n",
    "\n",
    "# If `param_group=True`, the head is updated with a learning rate ten times\n",
    "# larger than the pretrained backbone (mirroring the PyTorch tab); otherwise\n",
    "# all parameters are trained at the same rate (used for `scratch_net`).\n",
    "def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5,\n",
    "                      param_group=True, update_batch_stats=False,\n",
    "                      momentum=0.0):\n",
    "    train_ds = _make_tf_dataset(os.path.join(data_dir, 'train'),\n",
    "                                train_preprocess, batch_size, shuffle=True)\n",
    "    test_ds = _make_tf_dataset(os.path.join(data_dir, 'test'),\n",
    "                               test_preprocess, batch_size, shuffle=False)\n",
    "\n",
    "    # Per-parameter learning rate: 10x for the new classifier, 1x for the\n",
    "    # pretrained backbone. Use a label tree to drive optax.multi_transform.\n",
    "    # Weight decay and optional momentum follow the comparison recipes below.\n",
    "    if param_group:\n",
    "        def labels(params):\n",
    "            return jax.tree_util.tree_map_with_path(\n",
    "                lambda path, _: ('head' if any(\n",
    "                    (getattr(p, 'key', None) == 'fc' or\n",
    "                     getattr(p, 'name', None) == 'fc') for p in path)\n",
    "                                 else 'base'), params)\n",
    "        tx = optax.multi_transform(\n",
    "            {'head': optax.chain(\n",
    "                 optax.add_decayed_weights(0.001),\n",
    "                 optax.sgd(learning_rate * 10, momentum=momentum)),\n",
    "             'base': optax.chain(\n",
    "                 optax.add_decayed_weights(0.001),\n",
    "                 optax.sgd(learning_rate, momentum=momentum))},\n",
    "            labels)\n",
    "    else:\n",
    "        tx = optax.chain(\n",
    "            optax.add_decayed_weights(0.001),\n",
    "            optax.sgd(learning_rate, momentum=momentum))\n",
    "    optimizer = nnx.Optimizer(net, tx, wrt=nnx.Param)\n",
    "    train_net = nnx.view(net, use_running_average=not update_batch_stats,\n",
    "                         raise_if_not_found=False)\n",
    "    eval_net = nnx.view(net, use_running_average=True,\n",
    "                        raise_if_not_found=False)\n",
    "\n",
    "    @nnx.jit\n",
    "    def train_step(model, optimizer, x, y):\n",
    "        def loss_fn(model):\n",
    "            logits = model(x)\n",
    "            loss = optax.softmax_cross_entropy_with_integer_labels(\n",
    "                logits, y).mean()\n",
    "            return loss, logits\n",
    "        (loss, logits), grads = nnx.value_and_grad(\n",
    "            loss_fn, has_aux=True)(model)\n",
    "        optimizer.update(model, grads)\n",
    "        acc = (jnp.argmax(logits, axis=-1) == y).mean()\n",
    "        return loss, acc\n",
    "\n",
    "    @nnx.jit\n",
    "    def eval_step(model, x, y):\n",
    "        logits = model(x)\n",
    "        return (jnp.argmax(logits, axis=-1) == y).sum()\n",
    "\n",
    "    for epoch in range(num_epochs):\n",
    "        total_loss, total_acc, n_batches = (jnp.array(0.0),\n",
    "                                            jnp.array(0.0), 0)\n",
    "        for x, y in train_ds:\n",
    "            x = jnp.asarray(x.numpy()); y = jnp.asarray(y.numpy())\n",
    "            loss, acc = train_step(train_net, optimizer, x, y)\n",
    "            total_loss += loss\n",
    "            total_acc += acc\n",
    "            n_batches += 1\n",
    "        test_correct, test_examples = jnp.array(0), 0\n",
    "        for x, y in test_ds:\n",
    "            x = jnp.asarray(x.numpy()); y = jnp.asarray(y.numpy())\n",
    "            test_correct += eval_step(eval_net, x, y)\n",
    "            test_examples += len(y)\n",
    "        total_loss, total_acc, test_correct = jax.device_get(\n",
    "            (total_loss, total_acc, test_correct))\n",
    "        print(f'epoch {epoch + 1}, loss {float(total_loss) / n_batches:.3f}, '\n",
    "              f'train acc {float(total_acc) / n_batches:.3f}, '\n",
    "              f'test acc {float(test_correct) / max(test_examples, 1):.3f}')\n",
    "\n",
    "    return net"
   ],
   "execution_count": 9,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-11 fw=all -->\n",
    "\n",
    "We set the base learning rate to a small value\n",
    "in order to *fine-tune* the model parameters obtained via pretraining. Based on the previous settings, we will train the output layer parameters of the target model from scratch using a learning rate ten times greater."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-fine-tuning-the-model-2"
   },
   "source": [
    "print('fine-tuned model')\n",
    "finetune_net = train_fine_tuning(finetune_net, 1e-4, momentum=0.9)"
   ],
   "execution_count": 10,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "fine-tuned model\nFound 2000 files belonging to 2 classes.\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Found 800 files belonging to 2 classes.\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stderr",
     "text": [
      "E0719 14:24:38.739296   46176 cuda_timer.cc:88] Delay kernel timed out: measured time has sub-optimal accuracy. There may be a missing warmup execution, please investigate in Nsight Systems.\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 1, loss 0.637, train acc 0.780, test acc 0.873\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 2, loss 0.524, train acc 0.906, test acc 0.911\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 3, loss 0.420, train acc 0.934, test acc 0.917\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 4, loss 0.342, train acc 0.942, test acc 0.921\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 5, loss 0.284, train acc 0.944, test acc 0.926\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-12 fw=all -->\n",
    "\n",
    "For comparison, we define an identical model, but initialize all of its model parameters to random values. Since the entire model needs to be trained from scratch, we can use a larger learning rate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-fine-tuning-the-model-3"
   },
   "source": [
    "print('scratch baseline')\n",
    "scratch_net = ResNet50(num_classes=2, rngs=nnx.Rngs(2))\n",
    "# On this tiny dataset the running statistics must adapt much faster than the\n",
    "# ImageNet default.\n",
    "scratch_net = nnx.view(scratch_net, momentum=0.5, raise_if_not_found=False)\n",
    "scratch_net = train_fine_tuning(\n",
    "    scratch_net, 1e-3, num_epochs=6, param_group=False,\n",
    "    update_batch_stats=True, momentum=0.9)"
   ],
   "execution_count": 11,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "scratch baseline\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Found 2000 files belonging to 2 classes.\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Found 800 files belonging to 2 classes.\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 1, loss 0.689, train acc 0.545, test acc 0.564\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 2, loss 0.651, train acc 0.620, test acc 0.497\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 3, loss 0.630, train acc 0.654, test acc 0.559\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 4, loss 0.494, train acc 0.779, test acc 0.566\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 5, loss 0.367, train acc 0.838, test acc 0.655\n"
     ]
    },
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "epoch 6, loss 0.352, train acc 0.845, test acc 0.771\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-13 fw=all -->\n",
    "\n",
    "As we can see, the fine-tuned model reaches high accuracy in fewer epochs\n",
    "because its initial parameter values already encode useful visual features.\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "* Transfer learning transfers knowledge learned from the source dataset to the target dataset. Fine-tuning is a common technique for transfer learning.\n",
    "* The target model copies all model designs with their parameters from the source model except the output layer, and fine-tunes these parameters based on the target dataset. In contrast, the output layer of the target model needs to be trained from scratch.\n",
    "* Generally, fine-tuning parameters uses a smaller learning rate, while training the output layer from scratch can use a larger learning rate.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Keep increasing the learning rate of `finetune_net`. How does the accuracy of the model change?\n",
    "2. Further adjust hyperparameters of `finetune_net` and `scratch_net` in the comparative experiment. Do they still differ in accuracy?\n",
    "3. Set the parameters before the output layer of `finetune_net` to those of the source model and do *not* update them during training. How does the accuracy of the model change? You can use the following code."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-exercises-1"
   },
   "source": [
    "# Freeze the pretrained ResNet-50 backbone; only the new `fc` head\n",
    "# is updated by setting the optimizer learning rate of every other parameter\n",
    "# to zero. For example, modify `train_fine_tuning` to use:\n",
    "#   optax.multi_transform(\n",
    "#       {'head': optax.sgd(lr * 10, momentum=0.9),\n",
    "#        'base': optax.set_to_zero()},\n",
    "#       labels)"
   ],
   "execution_count": 12,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-14 fw=all -->\n",
    "\n",
    "4. In fact, there is a \"hotdog\" class in the `ImageNet` dataset. Its corresponding weight parameter in the output layer can be obtained via the following code. How can we leverage this weight parameter?"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "fine-tuning-exercises-2"
   },
   "source": [
    "# The pretrained classifier maps 2048-dimensional features to 1000 classes.\n",
    "weight = pretrained_net.fc.kernel[...]  # Shape: (2048, 1000)\n",
    "hotdog_w = weight[:, 934]\n",
    "hotdog_w.shape"
   ],
   "execution_count": 13,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "(2048,)"
     },
     "metadata": {},
     "execution_count": 13
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=fine-tuning-md-15 fw=jax -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/1439)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-jax",
   "display_name": "d2l (JAX)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
