This commit is contained in:
Daniel Bourke committed 2022-07-29 10:36:23 +10:00
commit b38a9bfef6
3 files changed
+1505 -206

No files matched your search

@@ -0,0 +1,524 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "08_pytorch_paper_replicating_exercises.ipynb",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true,
"authorship_tag": "ABX9TyOhoCjGZZxrecbm76R8UJZn",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU",
"gpuClass": "standard"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/mrdbourke/pytorch-deep-learning/blob/main/extras/exercises/08_pytorch_paper_replicating_exercises.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# 08. PyTorch Experiment Tracking Exercises\n",
"\n",
"Welcome to the 08. PyTorch Paper Replicating exercises.\n",
"\n",
"Your objective is to write code to satisify each of the exercises below.\n",
"\n",
"Some starter code has been provided to make sure you have all the resources you need.\n",
"\n",
"> **Note:** There may be more than one solution to each of the exercises.\n",
"\n",
"## Resources\n",
"\n",
"1. These exercises/solutions are based on [section 08. PyTorch Paper Replicating](https://www.learnpytorch.io/08_pytorch_paper_replicating/) of the Learn PyTorch for Deep Learning course by Zero to Mastery.\n",
"2. See a live [walkthrough of the solutions (errors and all) on YouTube](https://youtu.be/tjpW_BY8y3g) (but try the exercises yourself first!).\n",
"3. See [all solutions on the course GitHub](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/extras/solutions).\n",
"\n",
"> **Note:** The first section of this notebook is dedicated to getting various helper functions and datasets used for the exercises. The exercises start at the heading \"Exercise 1: ...\"."
],
"metadata": {
"id": "zNqPNlYylluR"
}
},
{
"cell_type": "markdown",
"source": [
"### Get various imports and helper functions\n",
"\n",
"The code in the following cells prepares imports and data for the exercises below. They are taken from [08. PyTorch Paper Replicating](https://www.learnpytorch.io/08_pytorch_paper_replicating/). "
],
"metadata": {
"id": "sf8ab9cyHTzU"
}
},
{
"cell_type": "code",
"source": [
"# For this notebook to run with updated APIs, we need torch 1.12+ and torchvision 0.13+\n",
"try:\n",
" import torch\n",
" import torchvision\n",
" assert int(torch.__version__.split(\".\")[1]) >= 12, \"torch version should be 1.12+\"\n",
" assert int(torchvision.__version__.split(\".\")[1]) >= 13, \"torchvision version should be 0.13+\"\n",
" print(f\"torch version: {torch.__version__}\")\n",
" print(f\"torchvision version: {torchvision.__version__}\")\n",
"except:\n",
" print(f\"[INFO] torch/torchvision versions not as required, installing nightly versions.\")\n",
" !pip3 install -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu113\n",
" import torch\n",
" import torchvision\n",
" print(f\"torch version: {torch.__version__}\")\n",
" print(f\"torchvision version: {torchvision.__version__}\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ChRaHUSJ8DYZ",
"outputId": "8f1c0a98-c04a-4d4b-a748-e591a315f805"
},
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"torch version: 1.12.0+cu113\n",
"torchvision version: 0.13.0+cu113\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Continue with regular imports\n",
"import matplotlib.pyplot as plt\n",
"import torch\n",
"import torchvision\n",
"\n",
"from torch import nn\n",
"from torchvision import transforms\n",
"\n",
"# Try to get torchinfo, install it if it doesn't work\n",
"try:\n",
" from torchinfo import summary\n",
"except:\n",
" print(\"[INFO] Couldn't find torchinfo... installing it.\")\n",
" !pip install -q torchinfo\n",
" from torchinfo import summary\n",
"\n",
"# Try to import the going_modular directory, download it from GitHub if it doesn't work\n",
"try:\n",
" from going_modular.going_modular import data_setup, engine\n",
" from helper_functions import download_data, set_seeds, plot_loss_curves\n",
"except:\n",
" # Get the going_modular scripts\n",
" print(\"[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.\")\n",
" !git clone https://github.com/mrdbourke/pytorch-deep-learning\n",
" !mv pytorch-deep-learning/going_modular .\n",
" !mv pytorch-deep-learning/helper_functions.py . # get the helper_functions.py script\n",
" !rm -rf pytorch-deep-learning\n",
" from going_modular.going_modular import data_setup, engine\n",
" from helper_functions import download_data, set_seeds, plot_loss_curves"
],
"metadata": {
"id": "Y5H5P8EjCNGK",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4214da9e-f3a8-43e6-a48c-1a33f44a9be9"
},
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[INFO] Couldn't find torchinfo... installing it.\n",
"[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.\n",
"Cloning into 'pytorch-deep-learning'...\n",
"remote: Enumerating objects: 2589, done.\u001b[K\n",
"remote: Counting objects: 100% (28/28), done.\u001b[K\n",
"remote: Compressing objects: 100% (17/17), done.\u001b[K\n",
"remote: Total 2589 (delta 11), reused 28 (delta 11), pack-reused 2561\u001b[K\n",
"Receiving objects: 100% (2589/2589), 446.45 MiB | 41.00 MiB/s, done.\n",
"Resolving deltas: 100% (1455/1455), done.\n",
"Checking out files: 100% (184/184), done.\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"id": "bE1AAH_uCjiP",
"outputId": "d4f0001d-3854-4845-f195-eeb08c503aa8"
},
"execution_count": 4,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'cuda'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 4
}
]
},
{
"cell_type": "markdown",
"source": [
"### Get data\n",
"\n",
"Want to download the data we've been using in PyTorch Paper Replicating: https://www.learnpytorch.io/08_pytorch_paper_replicating/#1-get-data"
],
"metadata": {
"id": "GmS5yuvxCpLp"
}
},
{
"cell_type": "code",
"source": [
"# Download pizza, steak, sushi images from GitHub\n",
"image_path = download_data(source=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip\",\n",
" destination=\"pizza_steak_sushi\")\n",
"image_path"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "dm772wqgCzN9",
"outputId": "ca6c646d-dd40-4453-c12c-a1f0ef5f86f4"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[INFO] Did not find data/pizza_steak_sushi directory, creating one...\n",
"[INFO] Downloading pizza_steak_sushi.zip from https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip...\n",
"[INFO] Unzipping pizza_steak_sushi.zip data...\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"PosixPath('data/pizza_steak_sushi')"
]
},
"metadata": {},
"execution_count": 5
}
]
},
{
"cell_type": "code",
"source": [
"# Setup directory paths to train and test images\n",
"train_dir = image_path / \"train\"\n",
"test_dir = image_path / \"test\""
],
"metadata": {
"id": "r1ML2c-dCzCi"
},
"execution_count": 6,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### Preprocess data\n",
"\n",
"Turn images into tensors using same code as PyTorch Paper Replicating section 2.1 and 2.2: https://www.learnpytorch.io/08_pytorch_paper_replicating/#21-prepare-transforms-for-images"
],
"metadata": {
"id": "nNBZ_2h_Cy86"
}
},
{
"cell_type": "code",
"source": [
"# Create image size (from Table 3 in the ViT paper) \n",
"IMG_SIZE = 224\n",
"\n",
"# Create transform pipeline manually\n",
"manual_transforms = transforms.Compose([\n",
" transforms.Resize((IMG_SIZE, IMG_SIZE)),\n",
" transforms.ToTensor(),\n",
"]) \n",
"print(f\"Manually created transforms: {manual_transforms}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "mU0T4gP3DJdF",
"outputId": "de32055d-b807-4245-e4a6-c10653502630"
},
"execution_count": 7,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Manually created transforms: Compose(\n",
" Resize(size=(224, 224), interpolation=bilinear, max_size=None, antialias=None)\n",
" ToTensor()\n",
")\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Set the batch size\n",
"BATCH_SIZE = 32 # this is lower than the ViT paper but it's because we're starting small\n",
"\n",
"# Create data loaders\n",
"train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(\n",
" train_dir=train_dir,\n",
" test_dir=test_dir,\n",
" transform=manual_transforms, # use manually created transforms\n",
" batch_size=BATCH_SIZE\n",
")\n",
"\n",
"train_dataloader, test_dataloader, class_names"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "W4vWgIprDJau",
"outputId": "6de4b52b-1570-408a-8399-8f6465258a31"
},
"execution_count": 8,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(<torch.utils.data.dataloader.DataLoader at 0x7f7e08f76c90>,\n",
" <torch.utils.data.dataloader.DataLoader at 0x7f7e0889f590>,\n",
" ['pizza', 'steak', 'sushi'])"
]
},
"metadata": {},
"execution_count": 8
}
]
},
{
"cell_type": "code",
"source": [
"# Get a batch of images\n",
"image_batch, label_batch = next(iter(train_dataloader))\n",
"\n",
"# Get a single image from the batch\n",
"image, label = image_batch[0], label_batch[0]\n",
"\n",
"# View the batch shapes\n",
"image.shape, label"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "u7eLIFHyDJRr",
"outputId": "464ae045-dddd-40a4-ef6c-3414e3ebc787"
},
"execution_count": 9,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(torch.Size([3, 224, 224]), tensor(0))"
]
},
"metadata": {},
"execution_count": 9
}
]
},
{
"cell_type": "code",
"source": [
"# Plot image with matplotlib\n",
"plt.imshow(image.permute(1, 2, 0)) # rearrange image dimensions to suit matplotlib [color_channels, height, width] -> [height, width, color_channels]\n",
"plt.title(class_names[label])\n",
"plt.axis(False);"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 264
},
"id": "2yyNHCmCDbSR",
"outputId": "da4b3c3a-6b9a-4954-9b44-226c89f89a8e"
},
"execution_count": 10,
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
],
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAOcAAAD3CAYAAADmIkO7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nOy9SaxlSZrn9fvM7Az33jf48yk8IjIicqqoys4q1cCiBE2J3iDEAsECMQhWiB0SrBBCzQIkGnYgBBtWiAUNvQGxQEiAUCNaNXQhqEXRTXVlVmZGRnj48NzfdO+795xjZh+Lz+zc656ZUZVBV1cgPVO43OO9O5xj9o3/7/99R1SVu3W37tZXb7m/6Au4W3frbv30daecd+tufUXXnXLerbv1FV13ynm37tZXdN0p5926W1/Rdaecd+tufUXXnXL+/2yJyG+JyB/9RV/H3frzX3JX57xbd+urue485926W1/RdaecX9ElIj8UkX9bRP6OiFyIyH8hIr2I/BUR+bS85p8XkfXBn0FE/qaIvPfWz29FRMt7viUi/6uIvBKRcxH5r0Tk3l/s3d6tn7bulPOrvf4l4J8AvgV8DPw7h79U1b+hqkeqegS8B/wJ8F+r6tP68/K7/w74b8rbBPgPy+u/A3wA/Lv/IG7mbv186045v9rrP1PVH6vqa+CvAf/iT3uRiDjgrwN/U1X/87d+928BvwT8KwCq+j1V/Z9VdVDVl8B/BPxjf543cbe+3Ap/0Rdwt75w/fjg3z/CvN1PW38NOAb+9cMfisg/CfwbwG+q6rb87B3gPwF+q7zHARd/fy/7bv39WHee86u9Pjj494fA07dfICL/AuZR/1lVn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/oFoEYEymNLLolTdMhoUcWJ4SjM6Rd8u7DxyjCLk688977PHznCR9882NOHjwB16IugK/pDCQgOccklvOhijpBsnJx8Yrf+73f5eTkhG//4i+xfv2ak9NTVssjxusrNGWq+8w5M00TcZpmHCHGCHmf+gDEaSreFUtNgKhqEYLAatHjVE22czKP6+ys1TLP+RxM6eH+2RmbzYanz54xjCO3OZE1krKlcCfHiy+nnIdKWi2QCb/OSmI5p5RNqGFhCQ5LCGFhMMSc7aKTEHcJr44sjomJnAqoUcJiAVKacC7sUVCpoarlUCag9p1VOatHO1TYGsrW6/fOkUu+7FyY868K+OSUDUAAfGgOwKb0BopbP7vuDxkkCKK5eEdzn84V7+4ELw6Ps3ufMtvrkdc/vuDV988Ja3jkjlg1Lb2POEkEFxBvXk/IZmDE9iAr5ikVgqMAcQWcalq7Ju8QMYOX1fJyTeYNteTvzjtC8HN4LhJo2oYpJVIGcQ1ZE2M0cW/aBc4FRvG0qxX98Smh78kpEacdbXB0/Snf/MXv8uHH32X14AlH9x/huxXOebIH3wTwjkwgqiOrgDNJSoBKQY7FgFsh4zQjmrldr/nbv/s73Nys+Ud+5R/l5Pgew/qG5XLBomu59o6U8kGCAtM0MU1TMfAOdQ6nbg5rU4xvIbbFa6bMGM1wLboWlzPatjPWUr1DNSi5gBkWNjs0Jx7df8Bms+H84hUxKuARHMMuoas3Kwl/ZuV0riKU+SCn0xmltddYvJ4rHG0OZw4Fqd61IoYIkoU4RCRLESgTYFWZFXQON9h/D1iIoVpCaGEOTfe5cUWJDaR6O/cUsVKQFLine truncated
},
"metadata": {
"needs_background": "light"
}
}
]
},
{
"cell_type": "markdown",
"source": [
"## 1. Replicate the ViT architecture we created with in-built [PyTorch transformer layers](https://pytorch.org/docs/stable/nn.html#transformer-layers).\n",
"\n",
"* You'll want to look into replacing our `TransformerEncoderBlock()` class with [`torch.nn.TransformerEncoderLayer()`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html#torch.nn.TransformerEncoderLayer) (these contain the same layers as our custom blocks). \n",
"* You can stack `torch.nn.TransformerEncoderLayer()`'s on top of each other with [`torch.nn.TransformerEncoder()`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder)."
],
"metadata": {
"id": "nwmoMhW8IqSu"
}
},
{
"cell_type": "code",
"source": [
"# TODO: your code"
],
"metadata": {
"id": "pmDd_YZ7VSrL"
},
"execution_count": 11,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## 2. Turn the custom ViT architecture we created into a Python script, for example, `vit.py`.\n",
"\n",
"* You should be able to import an entire ViT model using something like`from vit import ViT`.\n",
"* We covered the art of turning code cells into Python scrips in [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/). \n"
],
"metadata": {
"id": "MBWnDZao9w_5"
}
},
{
"cell_type": "code",
"source": [
"# TODO: your code"
],
"metadata": {
"id": "NFXVZNCzVYgV"
},
"execution_count": 12,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## 3. Train a pretrained ViT feature extractor model (like the one we made in [08. PyTorch Paper Replicating section 10](https://www.learnpytorch.io/08_pytorch_paper_replicating/#10-bring-in-pretrained-vit-from-torchvisionmodels-on-same-dataset)) on 20% of the pizza, steak and sushi data like the dataset we used in [07. PyTorch Experiment Tracking section 7.3](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#73-download-different-datasets) \n",
"* See how it performs compared to the EffNetB2 model we compared it to in [08. PyTorch Paper Replicating section 10.6](https://www.learnpytorch.io/08_pytorch_paper_replicating/#106-save-feature-extractor-vit-model-and-check-file-size)."
],
"metadata": {
"id": "aTKbje-e9118"
}
},
{
"cell_type": "code",
"source": [
"# TODO: your code"
],
"metadata": {
"id": "R7iKYRAUVkA7"
},
"execution_count": 13,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## 4. Try repeating the steps from excercise 3 but this time use the \"`ViT_B_16_Weights.IMAGENET1K_SWAG_E2E_V1`\" pretrained weights from [`torchvision.models.vit_b_16()`](https://pytorch.org/vision/stable/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16).\n",
"* Note: ViT pretrained with SWAG weights has a minimum input image size of (384, 384), though this is accessible in the weights `.transforms()` method."
],
"metadata": {
"id": "LH-vHr3m9_oH"
}
},
{
"cell_type": "code",
"source": [
"# TODO: your code"
],
"metadata": {
"id": "dWxceTz3VmeB"
},
"execution_count": 14,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# 5. Our custom ViT model architecture closely mimics that of the ViT paper, however, our training recipe misses a few things. \n",
"* Research some of the following topics from Table 3 in the ViT paper that we miss and write a sentence about each and how it might help with training:\n",
" * **ImageNet-22k pretraining** \n",
" * **Learning rate warmup** \n",
" * **Learning rate decay** \n",
" * **Gradient clipping** "
],
"metadata": {
"id": "ZLcCgRhS-OhV"
}
},
{
"cell_type": "code",
"source": [
"# TODO: your explanations of the above terms"
],
"metadata": {
"id": "7HwonCSsVtnr"
},
"execution_count": 15,
"outputs": []
}
]
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -12,3 +12,4 @@ You can video walkthroughs of me live-coding possible solutions (errors and all)
| 05 PyTorch Going Modular | https://youtu.be/ijgFhMK3pp4 |
| 06 PyTorch Transfer Learning | https://youtu.be/ueLolShyFqs |
| 07 PyTorch Experiment Tracking | https://youtu.be/cO_r2FYcAjU |
| 08 PyTorch Paper Replicating | https://youtu.be/tjpW_BY8y3g |