diff --git a/09_pytorch_model_deployment.ipynb b/09_pytorch_model_deployment.ipynb index 8bf1f9d..0256b87 100644 --- a/09_pytorch_model_deployment.ipynb +++ b/09_pytorch_model_deployment.ipynb @@ -17,8 +17,11 @@ "\n", "**Status:** Work in progress.\n", "\n", - "Goal: Take FoodVision Mini model and make it publically accessible (deploy it to a usable app/interface)\n", + "Goal: Take FoodVision Mini model and make it publically accessible (deploy it to a usable app/interface), want it to be:\n", + "* Fast (a slow app is a boring app)\n", + "* Good (95%+ accuracy for 3 classes but this would be harder to achieve with more classes)\n", "\n", + "--\n", "* TK - What is model deployment?\n", " * TK - PyTorch workflow + model deployment... (another step)\n", "* TK - Why deploy a machine learning model?\n", @@ -27,7 +30,11 @@ "* TK - On edge vs on cloud\n", "* TK - What to do when your model is deployed? E.g. monitoring? \n", " * TK - Perhaps talk about this when the model is actually deployed\n", - " * TK - What could go wrong when a model is deployed?" + " * TK - What could go wrong when a model is deployed?\n", + "* TK - Creating a demo (what are the inputs and outputs)...\n", + " * TK - Describing a machine learning problem... one of the best ways is in inputs and outputs, \"what are your ideal inputs and ideal outputs?\"\n", + "\n", + "## TK - What we're going to cover " ] }, { @@ -181,9 +188,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## 1. Getting data\n", + "## TK - 1. Getting data\n", "\n", - "Get 20% data to train models on same playing field." + "We left off in [08. PyTorch Paper Replicating](https://www.learnpytorch.io/08_pytorch_paper_replicating/#106-save-feature-extractor-vit-model-and-check-file-size) comparing our own ViT (Vision Transformer) feature extractor model to the EfficientNetB2 (EffNetB2) feature extractor model we created in [07. PyTorch Experiment Tracking](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#9-load-in-the-best-model-and-make-predictions-with-it).\n", + "\n", + "And we found that there was a slight difference in the comparison.\n", + "\n", + "The EffNetB2 model was trained on 20% of the pizza, steak and sushi data from Food101 where as the ViT model was trained on 10%.\n", + "\n", + "Since our goal is to deploy the best model for our FoodVision Mini problem, let's start by downloading the [20% pizza, steak and sushi dataset](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi_20_percent.zip) and train an EffNetB2 feature extractor and ViT feature extractor on it and then compare the two models.\n", + "\n", + "This way we'll be comparing apples to apples.\n", + "\n", + "> **Note:** The dataset we're downloading is a sample of the entire [Food101 dataset](https://pytorch.org/vision/main/generated/torchvision.datasets.Food101.html#food101) (101 food classes with 1,000 images each). More specifically, 20% refers to 20% of images from the pizza, steak and sushi classes selected at random. You can see how this dataset was created in [`extras/04_custom_data_creation.ipynb`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb)." ] }, { @@ -217,6 +234,15 @@ "data_20_percent_path" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Wonderful!\n", + "\n", + "Now we've got a dataset, let's creat training and test paths." + ] + }, { "cell_type": "code", "execution_count": 5, @@ -234,42 +260,187 @@ "source": [ "## TK - FoodVision Mini modelling experiment outline\n", "\n", - "Going to train two different feature extractor models:\n", + "The ideal deployed model FoodVision Mini performs well and fast.\n", "\n", - "1. EffNetB2\n", - "2. ViT-B/16" + "Ideally, we'd like a model that performs as close to real-time as possible.\n", + "\n", + "Real-time in this case being ~30FPS (frames per second) because that's about how fast the human eye can see (there is debate on this but let's just use ~30FPS as our benchmark).\n", + "\n", + "And for classifying three different classes (pizza, steak and sushi), we'd like a model that performs at 95%+ accuracy.\n", + "\n", + "Of course, higher accuracy would be nice but this might sacrifice speed.\n", + "\n", + "So our goals are:\n", + "\n", + "1. A model that can classify an image at ~30FPS (0.03 seconds per image).\n", + "2. A model that performs at 95%+ accuracy.\n", + "\n", + "To try and achieve these results, let's bring in our best performing models from the previous sections: \n", + "\n", + "1. EffNetB2 feature extractor - originally created in [07. PyTorch Experiment Tracking section 7.5](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#75-create-feature-extractor-models) using [`torchvision.models.efficientnet_b2`](https://pytorch.org/vision/stable/models/generated/torchvision.models.efficientnet_b2.html#efficientnet-b2) with adjusted `classifier` layers.\n", + "2. ViT-B/16 feature extractor - originally created in [08. PyTorch Paper Replicating section 10](https://www.learnpytorch.io/08_pytorch_paper_replicating/#10-using-a-pretrained-vit-from-torchvisionmodels-on-the-same-dataset) using [`torchvision.models.vit_b_16`](https://pytorch.org/vision/stable/models/generated/torchvision.models.vit_b_16.html#vit-b-16) with adjusted `head` layers. \n", + "\n", + "TK image - experiment outline (2 models, same dataset, same training regime)\n", + "\n", + "> **Note:** A \"feature extractor model\" often starts with a model that has been pretrained on a dataset similar to your own problem. The pretrained model's base layers are often left frozen (the pretrained patterns/weights stay the same) whilst some of the top (or classifier/classification head) layers get customized to your own problem by training on your own data. We covered the concept of a feature extractor model in [06. PyTorch Transfer Learning section 3.4](https://www.learnpytorch.io/06_pytorch_transfer_learning/#34-freezing-the-base-model-and-changing-the-output-layer-to-suit-our-needs)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## TK - Creating an EffNetB2 feature extractor" + "## TK - Creating an EffNetB2 feature extractor\n", + "\n", + "We first created an EffNetB2 feature extractor model in [07. PyTorch Experiment Tracking section 7.5](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#75-create-feature-extractor-models).\n", + "\n", + "And we saw by the end of that section it performed very well.\n", + "\n", + "So let's now recreate it here so we can compare its results to a ViT feature extractor trained on the same data.\n", + "\n", + "To do so we can:\n", + "1. Setup the pretrained weights as `torchvision.models.EfficientNet_B2_Weights.DEFAULT`, where \"`DEFAULT`\" means \"best currently available\" (or could use `weights=\"DEFAULT\"`). \n", + "2. Get the pretrained model image transforms from the weights with the `transforms()` method.\n", + "3. Create a pretrained model instance by passing the weights to an instance of `torchvision.models.efficientnet_b2`.\n", + "4. Freeze the base layers in the model.\n", + "5. Update the classifier head to suit our own data." ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 71, "metadata": {}, "outputs": [], "source": [ - "def create_effnetb2_model(num_classes:int=3, seed:int=42):\n", + "# 1. Setup pretrained EffNetB2 weights\n", + "effnetb2_weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT\n", + "\n", + "# 2. Get EffNetB2 transforms\n", + "effnetb2_transforms = effnetb2_weights.transforms()\n", + "\n", + "# 3. Setup pretrained model\n", + "effnetb2 = torchvision.models.efficientnet_b2(weights=effnetb2_weights) # could also use weights=\"DEFAULT\"\n", + "\n", + "# 4. Freeze the base layers in the model (this will freeze all layers to begin with)\n", + "for param in model.parameters():\n", + " param.requires_grad = False" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now to change the classifier head, let's first inspect it using the `classifier` attribute of our model." + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "Sequential(\n", + " (0): Dropout(p=0.3, inplace=True)\n", + " (1): Linear(in_features=1408, out_features=1000, bias=True)\n", + ")" + ] + }, + "execution_count": 74, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check out EffNetB2 classifier head\n", + "effnetb2.classifier" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Excellent! To change the classifier head to suit our own problem, let's replace the `out_features` variable with the same number of classes we have (in our case, `out_features=3`, one for pizza, steak, sushi).\n", + "\n", + "> **Note:** This process of changing the output layers/classifier head will be dependent on the problem you're working on. For example, if you wanted a different *number* of outputs or a different *kind* of ouput, you would have to change the output layers accordingly. " + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": {}, + "outputs": [], + "source": [ + "# 5. Update the classifier head\n", + "effnetb2.classifier = nn.Sequential(\n", + " nn.Dropout(p=0.3, inplace=True), # keep dropout layer same\n", + " nn.Linear(in_features=1408, # keep in_features same \n", + " out_features=3)) # change out_features to suit our number of classes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Beautiful!\n", + "\n", + "Looks like our EffNetB2 feature extractor is ready to go, however, since there's quite a few steps involved here, how about we turn the code above into a function we can re-use later?\n", + "\n", + "We'll call it `create_effnetb2_model()` and it'll take a customizable number of classes and a random seed parameter for reproducibility.\n", + "\n", + "Ideally, it will return an EffNetB2 feature extractor along with its assosciated transforms." + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "metadata": {}, + "outputs": [], + "source": [ + "def create_effnetb2_model(num_classes:int=3, \n", + " seed:int=42):\n", + " \"\"\"Creates and EfficientNetB2 feature extractor model and transforms.\n", + "\n", + " Args:\n", + " num_classes (int, optional): number of classes in the classifier head. \n", + " Defaults to 3.\n", + " seed (int, optional): random seed value. Defaults to 42.\n", + "\n", + " Returns:\n", + " model (torch.nn.Module): EffNetB2 feature extractor model. \n", + " transforms (torchvision.transforms): EffNetB2 image transforms.\n", + " \"\"\"\n", + " # 1, 2, 3. Create EffNetB2 pretrained weights, transforms and model.\n", " weights = torchvision.models.EfficientNet_B2_Weights.DEFAULT\n", " transforms = weights.transforms()\n", " model = torchvision.models.efficientnet_b2(weights=weights)\n", "\n", - " # Freeze base model\n", + " # 4. Freeze all layers in base model\n", " for param in model.parameters():\n", " param.requires_grad = False\n", "\n", - " # Change classifier head\n", + " # 5. Change classifier head with random seed for reproducibility\n", " torch.manual_seed(seed)\n", " model.classifier = nn.Sequential(\n", " nn.Dropout(p=0.3, inplace=True),\n", " nn.Linear(in_features=1408, out_features=num_classes),\n", " )\n", - " return model, transforms\n", - "\n", + " return model, transforms" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Woohoo! That's a nice looking function, let's try it out." + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": {}, + "outputs": [], + "source": [ "effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=3,\n", " seed=42)" ] @@ -278,32 +449,110 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "```\n", - "(classifier): Sequential(\n", - " (0): Dropout(p=0.3, inplace=True)\n", - " (1): Linear(in_features=1408, out_features=1000, bias=True)\n", - " )\n", - "```" + "No errors, nice, now to really try it out, let's get a summary with `torchinfo.summary()`. " ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 78, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "============================================================================================================================================\n", + "Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n", + "============================================================================================================================================\n", + "EfficientNet (EfficientNet) [1, 3, 224, 224] [1, 3] -- Partial\n", + "├─Sequential (features) [1, 3, 224, 224] [1, 1408, 7, 7] -- False\n", + "│ └─Conv2dNormActivation (0) [1, 3, 224, 224] [1, 32, 112, 112] -- False\n", + "│ │ └─Conv2d (0) [1, 3, 224, 224] [1, 32, 112, 112] (864) False\n", + "│ │ └─BatchNorm2d (1) [1, 32, 112, 112] [1, 32, 112, 112] (64) False\n", + "│ │ └─SiLU (2) [1, 32, 112, 112] [1, 32, 112, 112] -- --\n", + "│ └─Sequential (1) [1, 32, 112, 112] [1, 16, 112, 112] -- False\n", + "│ │ └─MBConv (0) [1, 32, 112, 112] [1, 16, 112, 112] (1,448) False\n", + "│ │ └─MBConv (1) [1, 16, 112, 112] [1, 16, 112, 112] (612) False\n", + "│ └─Sequential (2) [1, 16, 112, 112] [1, 24, 56, 56] -- False\n", + "│ │ └─MBConv (0) [1, 16, 112, 112] [1, 24, 56, 56] (6,004) False\n", + "│ │ └─MBConv (1) [1, 24, 56, 56] [1, 24, 56, 56] (10,710) False\n", + "│ │ └─MBConv (2) [1, 24, 56, 56] [1, 24, 56, 56] (10,710) False\n", + "│ └─Sequential (3) [1, 24, 56, 56] [1, 48, 28, 28] -- False\n", + "│ │ └─MBConv (0) [1, 24, 56, 56] [1, 48, 28, 28] (16,518) False\n", + "│ │ └─MBConv (1) [1, 48, 28, 28] [1, 48, 28, 28] (43,308) False\n", + "│ │ └─MBConv (2) [1, 48, 28, 28] [1, 48, 28, 28] (43,308) False\n", + "│ └─Sequential (4) [1, 48, 28, 28] [1, 88, 14, 14] -- False\n", + "│ │ └─MBConv (0) [1, 48, 28, 28] [1, 88, 14, 14] (50,300) False\n", + "│ │ └─MBConv (1) [1, 88, 14, 14] [1, 88, 14, 14] (123,750) False\n", + "│ │ └─MBConv (2) [1, 88, 14, 14] [1, 88, 14, 14] (123,750) False\n", + "│ │ └─MBConv (3) [1, 88, 14, 14] [1, 88, 14, 14] (123,750) False\n", + "│ └─Sequential (5) [1, 88, 14, 14] [1, 120, 14, 14] -- False\n", + "│ │ └─MBConv (0) [1, 88, 14, 14] [1, 120, 14, 14] (149,158) False\n", + "│ │ └─MBConv (1) [1, 120, 14, 14] [1, 120, 14, 14] (237,870) False\n", + "│ │ └─MBConv (2) [1, 120, 14, 14] [1, 120, 14, 14] (237,870) False\n", + "│ │ └─MBConv (3) [1, 120, 14, 14] [1, 120, 14, 14] (237,870) False\n", + "│ └─Sequential (6) [1, 120, 14, 14] [1, 208, 7, 7] -- False\n", + "│ │ └─MBConv (0) [1, 120, 14, 14] [1, 208, 7, 7] (301,406) False\n", + "│ │ └─MBConv (1) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False\n", + "│ │ └─MBConv (2) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False\n", + "│ │ └─MBConv (3) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False\n", + "│ │ └─MBConv (4) [1, 208, 7, 7] [1, 208, 7, 7] (686,868) False\n", + "│ └─Sequential (7) [1, 208, 7, 7] [1, 352, 7, 7] -- False\n", + "│ │ └─MBConv (0) [1, 208, 7, 7] [1, 352, 7, 7] (846,900) False\n", + "│ │ └─MBConv (1) [1, 352, 7, 7] [1, 352, 7, 7] (1,888,920) False\n", + "│ └─Conv2dNormActivation (8) [1, 352, 7, 7] [1, 1408, 7, 7] -- False\n", + "│ │ └─Conv2d (0) [1, 352, 7, 7] [1, 1408, 7, 7] (495,616) False\n", + "│ │ └─BatchNorm2d (1) [1, 1408, 7, 7] [1, 1408, 7, 7] (2,816) False\n", + "│ │ └─SiLU (2) [1, 1408, 7, 7] [1, 1408, 7, 7] -- --\n", + "├─AdaptiveAvgPool2d (avgpool) [1, 1408, 7, 7] [1, 1408, 1, 1] -- --\n", + "├─Sequential (classifier) [1, 1408] [1, 3] -- True\n", + "│ └─Dropout (0) [1, 1408] [1, 1408] -- --\n", + "│ └─Linear (1) [1, 1408] [1, 3] 4,227 True\n", + "============================================================================================================================================\n", + "Total params: 7,705,221\n", + "Trainable params: 4,227\n", + "Non-trainable params: 7,700,994\n", + "Total mult-adds (M): 657.64\n", + "============================================================================================================================================\n", + "Input size (MB): 0.60\n", + "Forward/backward pass size (MB): 156.80\n", + "Params size (MB): 30.82\n", + "Estimated Total Size (MB): 188.22\n", + "============================================================================================================================================" + ] + }, + "execution_count": 78, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# summary(effnetb2, \n", - "# input_size=(1, 3, 224, 224),\n", - "# col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n", - "# col_width=20,\n", - "# row_settings=[\"var_names\"])" + "from torchinfo import summary\n", + "summary(effnetb2, \n", + " input_size=(1, 3, 224, 224),\n", + " col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n", + " col_width=20,\n", + " row_settings=[\"var_names\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Create DataLoaders for EffNetB2 " + "Base layers frozen, top layers trainable and customized!\n", + "\n", + "TK image - turn model summary into image" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Create DataLoaders for EffNetB2 \n", + "\n", + "Our EffNetB2 feature extractor is ready, time to create some `DataLoader`s.\n", + "\n", + "UPTOHERE: detail the DataLoader creation...\n", + "* TK Where have we done this before? (plenty of places...)" ] }, { @@ -316,7 +565,7 @@ "train_dataloader_effnetb2, test_dataloader_effnetb2, class_names = data_setup.create_dataloaders(train_dir=train_dir,\n", " test_dir=test_dir,\n", " transform=effnetb2_transforms,\n", - " batch_size=32)\n" + " batch_size=32)" ] }, { @@ -334,7 +583,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "67dc332241e14e9ab32c455c6db34589", + "model_id": "3d4684293dc5410da7dd1862fddbe981", "version_major": 2, "version_minor": 0 }, @@ -578,7 +827,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "740c2aa06e7a4ab58fa685e36655b3f9", + "model_id": "f851e14cc88d4c4fbe09136ee6bc1a8f", "version_major": 2, "version_minor": 0 }, @@ -810,7 +1059,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "96876288b60b44d599536a9d3d058261", + "model_id": "657243417ae446e2af80737638b5c318", "version_major": 2, "version_minor": 0 }, @@ -828,19 +1077,19 @@ " 'class_name': 'steak',\n", " 'pred_prob': 0.9293267726898193,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.0611,\n", + " 'time_for_pred': 0.0552,\n", " 'correct': True},\n", " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),\n", " 'class_name': 'steak',\n", " 'pred_prob': 0.9533632397651672,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.0376,\n", + " 'time_for_pred': 0.0351,\n", " 'correct': True},\n", " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),\n", " 'class_name': 'steak',\n", " 'pred_prob': 0.7531499266624451,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.0367,\n", + " 'time_for_pred': 0.0343,\n", " 'correct': True}]" ] }, @@ -874,7 +1123,7 @@ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "1f8a038bc23149f7ab7603782e270867", + "model_id": "e9555bfb67f6461a89656ab8b9b95c1f", "version_major": 2, "version_minor": 0 }, @@ -892,19 +1141,19 @@ " 'class_name': 'steak',\n", " 'pred_prob': 0.9932767748832703,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.1636,\n", + " 'time_for_pred': 0.1866,\n", " 'correct': True},\n", " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/3100563.jpg'),\n", " 'class_name': 'steak',\n", " 'pred_prob': 0.9893474578857422,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.0685,\n", + " 'time_for_pred': 0.0638,\n", " 'correct': True},\n", " {'image_path': PosixPath('data/pizza_steak_sushi_20_percent/test/steak/2752603.jpg'),\n", " 'class_name': 'steak',\n", " 'pred_prob': 0.997147262096405,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.0639,\n", + " 'time_for_pred': 0.0626,\n", " 'correct': True}]" ] }, @@ -938,7 +1187,7 @@ { "data": { "text/plain": [ - "0.031052666666666683" + "0.028969333333333333" ] }, "execution_count": 24, @@ -965,7 +1214,7 @@ "{'test_loss': 0.281286683678627,\n", " 'test_acc': 0.96875,\n", " 'model_size (MB)': 29,\n", - " 'time_per_pred_cpu': 0.031052666666666683}" + " 'time_per_pred_cpu': 0.028969333333333333}" ] }, "execution_count": 25, @@ -986,7 +1235,7 @@ { "data": { "text/plain": [ - "0.06613866666666665" + "0.0646173333333333" ] }, "execution_count": 26, @@ -1013,7 +1262,7 @@ "{'test_loss': 0.06418213145807386,\n", " 'test_acc': 0.984659090909091,\n", " 'model_size (MB)': 327,\n", - " 'time_per_pred_cpu': 0.06613866666666665}" + " 'time_per_pred_cpu': 0.0646173333333333}" ] }, "execution_count": 27, @@ -1071,14 +1320,14 @@ "