diff --git a/09_pytorch_model_deployment.ipynb b/09_pytorch_model_deployment.ipynb index 0256b87..9ad4117 100644 --- a/09_pytorch_model_deployment.ipynb +++ b/09_pytorch_model_deployment.ipynb @@ -33,6 +33,8 @@ " * 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", + "* TK - Even at the last project we're still experimenting... two model's have shined throughout on the FoodVision Mini project, now let's investigate further to see which is best\n", + " * TK - fast & good \n", "\n", "## TK - What we're going to cover " ] @@ -73,7 +75,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 78, "metadata": {}, "outputs": [ { @@ -121,7 +123,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 79, "metadata": {}, "outputs": [], "source": [ @@ -165,7 +167,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 80, "metadata": {}, "outputs": [ { @@ -174,7 +176,7 @@ "'cuda'" ] }, - "execution_count": 3, + "execution_count": 80, "metadata": {}, "output_type": "execute_result" } @@ -205,7 +207,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 81, "metadata": {}, "outputs": [ { @@ -221,7 +223,7 @@ "PosixPath('data/pizza_steak_sushi_20_percent')" ] }, - "execution_count": 4, + "execution_count": 81, "metadata": {}, "output_type": "execute_result" } @@ -245,7 +247,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 82, "metadata": {}, "outputs": [], "source": [ @@ -272,13 +274,14 @@ "\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", + "1. **Speed** - A model that can classify an image at ~30FPS (0.03 seconds per image).\n", + "2. **Performance** - 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", + "1. **EffNetB2 feature extractor** (EffNetB2 for short) - 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** (ViT for short) - 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", + " * **Note** ViT-B/16 stands for \"Vision Transformer Base, patch size 16\".\n", "\n", "TK image - experiment outline (2 models, same dataset, same training regime)\n", "\n", @@ -299,7 +302,7 @@ "\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", + "2. Get the pretrained model image transforms from the weights with the `transforms()` method (we need these so we can convert our images into the same format as the pretrained EffNetB2 was trained on).\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." @@ -307,7 +310,7 @@ }, { "cell_type": "code", - "execution_count": 71, + "execution_count": 83, "metadata": {}, "outputs": [], "source": [ @@ -321,7 +324,7 @@ "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", + "for param in effnetb2.parameters():\n", " param.requires_grad = False" ] }, @@ -334,7 +337,7 @@ }, { "cell_type": "code", - "execution_count": 74, + "execution_count": 84, "metadata": {}, "outputs": [ { @@ -346,7 +349,7 @@ ")" ] }, - "execution_count": 74, + "execution_count": 84, "metadata": {}, "output_type": "execute_result" } @@ -367,7 +370,7 @@ }, { "cell_type": "code", - "execution_count": 75, + "execution_count": 85, "metadata": {}, "outputs": [], "source": [ @@ -393,13 +396,13 @@ }, { "cell_type": "code", - "execution_count": 76, + "execution_count": 86, "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", + " \"\"\"Creates an EfficientNetB2 feature extractor model and transforms.\n", "\n", " Args:\n", " num_classes (int, optional): number of classes in the classifier head. \n", @@ -410,7 +413,7 @@ " 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", + " # 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", @@ -425,6 +428,7 @@ " nn.Dropout(p=0.3, inplace=True),\n", " nn.Linear(in_features=1408, out_features=num_classes),\n", " )\n", + " \n", " return model, transforms" ] }, @@ -437,7 +441,7 @@ }, { "cell_type": "code", - "execution_count": 77, + "execution_count": 87, "metadata": {}, "outputs": [], "source": [ @@ -454,7 +458,7 @@ }, { "cell_type": "code", - "execution_count": 78, + "execution_count": 88, "metadata": {}, "outputs": [ { @@ -520,7 +524,7 @@ "============================================================================================================================================" ] }, - "execution_count": 78, + "execution_count": 88, "metadata": {}, "output_type": "execute_result" } @@ -547,21 +551,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Create DataLoaders for EffNetB2 \n", + "### TK - Creating 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...)" + "We can do this by using the `data_setup.create_dataloaders()` function we created in [05. PyTorch Going Modular section 2](https://www.learnpytorch.io/05_pytorch_going_modular/#2-create-datasets-and-dataloaders-data_setuppy).\n", + "\n", + "We'll use a `batch_size` of 32 and transform our images using the `effnetb2_transforms` so they're in the same format that our `effnetb2` model was trained on." ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 89, "metadata": {}, "outputs": [], "source": [ - "# Setup dataloaders\n", + "# Setup DataLoaders\n", + "from going_modular.going_modular import data_setup\n", "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", @@ -572,18 +578,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Train EffNetB2" + "### TK - Training EffNetB2\n", + "\n", + "Model ready, `DataLoader`s ready, let's train!\n", + "\n", + "Just like in [07. PyTorch Experiment Tracking section 7.6](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#76-create-experiments-and-set-up-training-code), ten epochs should be enough to get good results.\n", + "\n", + "We can do so by creating an optimizer (we'll use [`torch.optim.Adam()`](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam) with a learning rate of `1e-3`), a loss function (we'll use [`torch.nn.CrossEntropyLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) for multi-class classification) and then passing everything to the [`engine.train()`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/engine.py) function we created in [05. PyTorch Going Modular section 4](https://www.learnpytorch.io/05_pytorch_going_modular/#4-creating-train_step-and-test_step-functions-and-train-to-combine-them)." ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "3d4684293dc5410da7dd1862fddbe981", + "model_id": "d2cdf62a8776406ba6692154714840fc", "version_major": 2, "version_minor": 0 }, @@ -612,14 +624,15 @@ } ], "source": [ - "# Train the model\n", "from going_modular.going_modular import engine\n", "\n", + "# Setup optimizer\n", "optimizer = torch.optim.Adam(params=effnetb2.parameters(),\n", " lr=1e-3)\n", - "\n", + "# Setup loss function\n", "loss_fn = torch.nn.CrossEntropyLoss()\n", "\n", + "# Set seeds for reproducibility and train the model\n", "set_seeds()\n", "effnetb2_results = engine.train(model=effnetb2,\n", " train_dataloader=train_dataloader_effnetb2,\n", @@ -634,14 +647,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Plot EffNetB2 loss curves \n", + "### TK - Inspecting EffNetB2 loss curves \n", "\n", - "* TK - Link to loss curves section: https://www.learnpytorch.io/04_pytorch_custom_datasets/#8-what-should-an-ideal-loss-curve-look-like " + "Nice!\n", + "\n", + "As we saw in 07. PyTorch Experiment Tracking, the EffNetB2 feature extractor model works quite well on our data.\n", + "\n", + "Let's turn its results into loss curves to inspect them further.\n", + "\n", + "> **Note:** Loss curves are one of the best ways to visualize how your model's performing. For more on loss curves, check out [04. PyTorch Custom Datasets section 8: What should an ideal loss curve look like?](https://www.learnpytorch.io/04_pytorch_custom_datasets/#8-what-should-an-ideal-loss-curve-look-like)" ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 91, "metadata": {}, "outputs": [ { @@ -667,12 +686,31 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Save EffNetB2 model" + "Woah!\n", + "\n", + "Those are some nice looking loss curves. \n", + "\n", + "It looks like our model is performing quite well and perhaps would benefit from a little longer training and potentially some [data augmentation](https://www.learnpytorch.io/04_pytorch_custom_datasets/#6-other-forms-of-transforms-data-augmentation) (to help prevent overfitting occurring from longer training)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "tags": [] + }, + "source": [ + "### TK - Saving EffNetB2\n", + "\n", + "Now we've got a well-performing trained model, let's save it to file so we can import and use it later.\n", + "\n", + "To save our model we can use the `utils.save_model()` function we created in [05. PyTorch Going Modular section 5](https://www.learnpytorch.io/05_pytorch_going_modular/#5-creating-a-function-to-save-the-model-utilspy).\n", + "\n", + "We'll set the `target_dir` to `\"models\"` and the `model_name` to `\"09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth\"` (a little comprehensive but at least we know what's going on)." ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 92, "metadata": {}, "outputs": [ { @@ -684,17 +722,36 @@ } ], "source": [ - "# Save the model\n", "from going_modular.going_modular import utils\n", "\n", + "# Save the model\n", "utils.save_model(model=effnetb2,\n", " target_dir=\"models\",\n", " model_name=\"09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Checking the size of EffNetB2\n", + "\n", + "Since one of our criteria for deploying a model to power FoodVision Mini is **speed** (~30FPS or better), let's check the size of our model.\n", + "\n", + "Why check the size?\n", + "\n", + "Well, while not always the case, the size of a model can influence its inference speed.\n", + "\n", + "As in, if a model has more parameters, it generally performs more operations and each one of these operations requires some computing power.\n", + "\n", + "And because we'd like our model to work on devices with limited computing power (e.g. on a mobile device or in a web browser), generally, the smaller the size the better (as long as it still performs well in terms of accuracy).\n", + "\n", + "To check our model's size in bytes, we can use `pathlib.Path.stat(\"path_to_model\").st_size` and then we can convert it (roughly) to megabytes by dividing it by `(1024*1024)`. " + ] + }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 93, "metadata": {}, "outputs": [ { @@ -717,30 +774,70 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Collect EffNetB2 stats\n", + "### TK - Collecting EffNetB2 stats\n", "\n", - "* TK - Want to compare our models later on... " + "We've got a few statistics about our EffNetB2 model such as test loss, test accuracy and model size, how about we collect them all in a dictionary so we can compare them to the upcoming ViT feature extractor.\n", + "\n", + "And we'll calculate an extra one for fun, total number of parameters.\n", + "\n", + "We can do so by counting the number of elements (or patterns/weights) in `effnetb2.parameters()`. We'll access the number of elements in each parameter using the [`torch.numel()`](https://pytorch.org/docs/stable/generated/torch.numel.html) (short for \"number of elements\") method. " ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "{'test_loss': 0.281286683678627, 'test_acc': 0.96875, 'model_size (MB)': 29}" + "7705221" ] }, - "execution_count": 13, + "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ + "# Count number of parameters in EffNetB2\n", + "effnetb2_total_params = sum(torch.numel(param) for param in effnetb2.parameters())\n", + "effnetb2_total_params" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Excellent!\n", + "\n", + "Now let's put everything in a dictionary so we can make comparisons later on." + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'test_loss': 0.281286683678627,\n", + " 'test_acc': 0.96875,\n", + " 'number_of_parameters': 7705221,\n", + " 'model_size (MB)': 29}" + ] + }, + "execution_count": 95, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Create a dictionary with EffNetB2 statistics\n", "effnetb2_stats = {\"test_loss\": effnetb2_results[\"test_loss\"][-1],\n", " \"test_acc\": effnetb2_results[\"test_acc\"][-1],\n", + " \"number_of_parameters\": effnetb2_total_params,\n", " \"model_size (MB)\": pretrained_effnetb2_model_size}\n", "effnetb2_stats" ] @@ -751,32 +848,99 @@ "source": [ "## TK - Creating a ViT feature extractor\n", "\n", - "Source - https://pytorch.org/vision/stable/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16" + "Time to continue with our FoodVision Mini modelling experiments.\n", + "\n", + "This time we're going to create a ViT feature extractor.\n", + "\n", + "And we'll do it in much the same way as the EffNetB2 feature extractor except this time with [`torchvision.models.vit_b_16()`](https://pytorch.org/vision/stable/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16) instead of `torchvision.models.efficientnet_b2()`.\n", + "\n", + "We'll start by creating a function called `create_vit_model()` which will be very similar to `create_effnetb2_model()` except of course returning a ViT feature extractor model and transforms rather than EffNetB2.\n", + "\n", + "Another slight difference is that `torchvision.models.vit_b_16()`'s output layer is called `heads` rather than `classifier`." ] }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 96, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "Sequential(\n", + " (head): Linear(in_features=768, out_features=1000, bias=True)\n", + ")" + ] + }, + "execution_count": 96, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check out ViT heads layer\n", + "vit = torchvision.models.vit_b_16()\n", + "vit.heads" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Knowing this, we've got all the pieces of the puzzle we need." + ] + }, + { + "cell_type": "code", + "execution_count": 97, "metadata": {}, "outputs": [], "source": [ - "def create_vit_model(num_classes: int=3, seed: int=42):\n", + "def create_vit_model(num_classes:int=3, \n", + " seed:int=42):\n", + " \"\"\"Creates a ViT-B/16 feature extractor model and transforms.\n", + "\n", + " Args:\n", + " num_classes (int, optional): number of target classes. Defaults to 3.\n", + " seed (int, optional): random seed value for output layer. Defaults to 42.\n", + "\n", + " Returns:\n", + " model (torch.nn.Module): ViT-B/16 feature extractor model. \n", + " transforms (torchvision.transforms): ViT-B/16 image transforms.\n", + " \"\"\"\n", + " # Create EffNetB2 pretrained weights, transforms and model\n", " weights = torchvision.models.ViT_B_16_Weights.DEFAULT\n", " transforms = weights.transforms()\n", " model = torchvision.models.vit_b_16(weights=weights)\n", "\n", - "\n", - " # Freeze base model\n", + " # Freeze all layers in model\n", " for param in model.parameters():\n", " param.requires_grad = False\n", "\n", - " # Change classifier head\n", + " # Change classifier head to suit our needs (this will be trainable)\n", " torch.manual_seed(seed)\n", - " model.heads = nn.Sequential(nn.Linear(in_features=768, \n", - " out_features=len(class_names)))\n", + " model.heads = nn.Sequential(nn.Linear(in_features=768, # keep this the same as original model\n", + " out_features=num_classes)) # update to reflect target number of classes\n", " \n", - " return model, transforms\n", + " return model, transforms" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "ViT feature extraction model creation function ready!\n", "\n", + "Let's test it out." + ] + }, + { + "cell_type": "code", + "execution_count": 98, + "metadata": {}, + "outputs": [], + "source": [ + "# Create ViT model and transforms\n", "vit, vit_transforms = create_vit_model(num_classes=3,\n", " seed=42)" ] @@ -785,49 +949,131 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Create DataLoaders for ViT" + "No errors, lovely to see! \n", + "\n", + "Now let's get a nice-looking summary of our ViT model using `torchinfo.summary()`." ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 99, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "======================================================================================================================================================\n", + "Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n", + "======================================================================================================================================================\n", + "VisionTransformer (VisionTransformer) [1, 3, 224, 224] [1, 3] 768 Partial\n", + "├─Conv2d (conv_proj) [1, 3, 224, 224] [1, 768, 14, 14] (590,592) False\n", + "├─Encoder (encoder) [1, 197, 768] [1, 197, 768] 151,296 False\n", + "│ └─Dropout (dropout) [1, 197, 768] [1, 197, 768] -- --\n", + "│ └─Sequential (layers) [1, 197, 768] [1, 197, 768] -- False\n", + "│ │ └─EncoderBlock (encoder_layer_0) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_1) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_2) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_3) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_4) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_5) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_6) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_7) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_8) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_9) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_10) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ │ └─EncoderBlock (encoder_layer_11) [1, 197, 768] [1, 197, 768] (7,087,872) False\n", + "│ └─LayerNorm (ln) [1, 197, 768] [1, 197, 768] (1,536) False\n", + "├─Sequential (heads) [1, 768] [1, 3] -- True\n", + "│ └─Linear (0) [1, 768] [1, 3] 2,307 True\n", + "======================================================================================================================================================\n", + "Total params: 85,800,963\n", + "Trainable params: 2,307\n", + "Non-trainable params: 85,798,656\n", + "Total mult-adds (M): 172.47\n", + "======================================================================================================================================================\n", + "Input size (MB): 0.60\n", + "Forward/backward pass size (MB): 104.09\n", + "Params size (MB): 257.55\n", + "Estimated Total Size (MB): 362.24\n", + "======================================================================================================================================================" + ] + }, + "execution_count": 99, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from torchinfo import summary\n", + "summary(vit, \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 image - summary output\n", + "\n", + "Just like our EffNetB2 feature extractor model, our ViT model's base layers are frozen and the output layer is customized to our needs! \n", + "\n", + "Do you notice the big difference though?\n", + "\n", + "Our ViT model has *far* more parameters than our EffNetB2 model. Perhaps this will come into play when we compare are our models across speed and performance later on." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Create DataLoaders for ViT\n", + "\n", + "We've got our ViT model ready, now let's create some `DataLoader`s for it.\n", + "\n", + "We'll do this in the same way we did for EffNetB2 except we'll use `vit_transforms` to transform our images into the same format the ViT model was trained on. " + ] + }, + { + "cell_type": "code", + "execution_count": 100, "metadata": {}, "outputs": [], "source": [ - "# Setup dataloaders\n", + "# Setup ViT DataLoaders\n", + "from going_modular.going_modular import data_setup\n", "train_dataloader_vit, test_dataloader_vit, class_names = data_setup.create_dataloaders(train_dir=train_dir,\n", - " test_dir=test_dir,\n", - " transform=vit_transforms,\n", - " batch_size=32)\n" + " test_dir=test_dir,\n", + " transform=vit_transforms,\n", + " batch_size=32)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "```\n", - "(heads): Sequential(\n", - " (head): Linear(in_features=768, out_features=1000, bias=True)\n", - " )\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### TK - Train ViT" + "### TK - Training ViT\n", + "\n", + "You know what time it is...\n", + "\n", + "...it's traininggggggg time (sung in the same tune as the song [Closing Time](https://youtu.be/xGytDsqkQY8)). \n", + "\n", + "Let's train our ViT feature extractor model for 10 epochs using our `engine.train()` function with `torch.optim.Adam()` and a learning rate of `1e-3` as our optimizer and `torch.nn.CrossEntropyLoss()` as our loss function.\n", + "\n", + "We'll use our `set_seeds()` function before training to try and make our results as reproducible as possible. " ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 101, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "f851e14cc88d4c4fbe09136ee6bc1a8f", + "model_id": "5a7951e3d3d44deeb8bd22d60e115dcd", "version_major": 2, "version_minor": 0 }, @@ -856,14 +1102,15 @@ } ], "source": [ - "# Train the model\n", "from going_modular.going_modular import engine\n", "\n", + "# Setup optimizer\n", "optimizer = torch.optim.Adam(params=vit.parameters(),\n", " lr=1e-3)\n", - "\n", + "# Setup loss function\n", "loss_fn = torch.nn.CrossEntropyLoss()\n", "\n", + "# Train ViT model with seeds set for reproducibility\n", "set_seeds()\n", "vit_results = engine.train(model=vit,\n", " train_dataloader=train_dataloader_vit,\n", @@ -878,14 +1125,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - Plot ViT loss curves\n", + "### TK - Inspecting ViT loss curves\n", "\n", - "* TK - see ideal loss curves here: https://www.learnpytorch.io/04_pytorch_custom_datasets/#8-what-should-an-ideal-loss-curve-look-like" + "Alright, alright, alright, ViT model trained, let's get visual and see some loss curves.\n", + "\n", + "> **Note:** Don't forget you can see what an ideal set of loss curves should look like in [04. PyTorch Custom Datasets section 8](https://www.learnpytorch.io/04_pytorch_custom_datasets/#8-what-should-an-ideal-loss-curve-look-like)." ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 102, "metadata": {}, "outputs": [ { @@ -907,9 +1156,31 @@ "plot_loss_curves(vit_results)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Ohh yeah! \n", + "\n", + "Those are some nice looking loss curves. Just like our EffNetB2 feature extractor model, it looks our ViT model might benefit from a little longer training time and perhaps some [data augmentation](https://www.learnpytorch.io/04_pytorch_custom_datasets/#6-other-forms-of-transforms-data-augmentation) (to help prevent overfitting). " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Saving ViT\n", + "\n", + "Our ViT model is performing outstanding! \n", + "\n", + "So let's save it to file so we can import it and use it later if we wish.\n", + "\n", + "We can do so using the `utils.save_model()` function we created in [05. PyTorch Going Modular section 5](https://www.learnpytorch.io/05_pytorch_going_modular/#5-creating-a-function-to-save-the-model-utilspy). " + ] + }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 27, "metadata": {}, "outputs": [ { @@ -929,9 +1200,20 @@ " model_name=\"09_pretrained_vit_feature_extractor_pizza_steak_sushi_20_percent.pth\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Checking the size of ViT\n", + "\n", + "And since we want to compare our EffNetB2 model to our ViT model across a number of characteristics, let's find out its size.\n", + "\n", + "To check our model's size in bytes, we can use Python's `pathlib.Path.stat(\"path_to_model\").st_size` and then we can convert it (roughly) to megabytes by dividing it by `(1024*1024)`. " + ] + }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 28, "metadata": {}, "outputs": [ { @@ -950,9 +1232,49 @@ "print(f\"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB\")" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hmmm, how does the ViT feature extractor model size compare to our EffNetB2 model size?\n", + "\n", + "We'll find this out shortly when we compare all of our model's characteristics." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### TK - Collecting ViT stats\n", + "\n", + "UPTOHERE: collecting stats and comparing models... " + ] + }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "85800963" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Count number of parameters in ViT\n", + "vit_total_params = sum(torch.numel(param) for param in vit.parameters())\n", + "vit_total_params" + ] + }, + { + "cell_type": "code", + "execution_count": 30, "metadata": {}, "outputs": [ { @@ -960,10 +1282,11 @@ "text/plain": [ "{'test_loss': 0.06418213145807386,\n", " 'test_acc': 0.984659090909091,\n", + " 'number_of_parameters': 85800963,\n", " 'model_size (MB)': 327}" ] }, - "execution_count": 20, + "execution_count": 30, "metadata": {}, "output_type": "execute_result" } @@ -971,6 +1294,7 @@ "source": [ "vit_stats = {\"test_loss\": vit_results[\"test_loss\"][-1],\n", " \"test_acc\": vit_results[\"test_acc\"][-1],\n", + " \"number_of_parameters\": vit_total_params,\n", " \"model_size (MB)\": pretrained_vit_model_size}\n", "vit_stats" ] @@ -987,7 +1311,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 31, "metadata": {}, "outputs": [], "source": [ @@ -1053,13 +1377,13 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "657243417ae446e2af80737638b5c318", + "model_id": "f7dd70d57a014b579f5224ed02c6353f", "version_major": 2, "version_minor": 0 }, @@ -1077,23 +1401,23 @@ " 'class_name': 'steak',\n", " 'pred_prob': 0.9293267726898193,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.0552,\n", + " 'time_for_pred': 0.0553,\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.0351,\n", + " 'time_for_pred': 0.0305,\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.0343,\n", + " 'time_for_pred': 0.0297,\n", " 'correct': True}]" ] }, - "execution_count": 22, + "execution_count": 32, "metadata": {}, "output_type": "execute_result" } @@ -1117,13 +1441,13 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { - "model_id": "e9555bfb67f6461a89656ab8b9b95c1f", + "model_id": "77df9b8cca754860a4d998a6aaad3713", "version_major": 2, "version_minor": 0 }, @@ -1141,23 +1465,23 @@ " 'class_name': 'steak',\n", " 'pred_prob': 0.9932767748832703,\n", " 'pred_class': 'steak',\n", - " 'time_for_pred': 0.1866,\n", + " 'time_for_pred': 0.1276,\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.0638,\n", + " 'time_for_pred': 0.0649,\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.0626,\n", + " 'time_for_pred': 0.0642,\n", " 'correct': True}]" ] }, - "execution_count": 23, + "execution_count": 33, "metadata": {}, "output_type": "execute_result" } @@ -1181,16 +1505,16 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "0.028969333333333333" + "0.03083866666666667" ] }, - "execution_count": 24, + "execution_count": 34, "metadata": {}, "output_type": "execute_result" } @@ -1205,7 +1529,7 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 35, "metadata": {}, "outputs": [ { @@ -1213,11 +1537,12 @@ "text/plain": [ "{'test_loss': 0.281286683678627,\n", " 'test_acc': 0.96875,\n", + " 'number_of_parameters': 7705221,\n", " 'model_size (MB)': 29,\n", - " 'time_per_pred_cpu': 0.028969333333333333}" + " 'time_per_pred_cpu': 0.03083866666666667}" ] }, - "execution_count": 25, + "execution_count": 35, "metadata": {}, "output_type": "execute_result" } @@ -1229,16 +1554,16 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "0.0646173333333333" + "0.06575066666666665" ] }, - "execution_count": 26, + "execution_count": 36, "metadata": {}, "output_type": "execute_result" } @@ -1253,7 +1578,7 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 37, "metadata": {}, "outputs": [ { @@ -1261,11 +1586,12 @@ "text/plain": [ "{'test_loss': 0.06418213145807386,\n", " 'test_acc': 0.984659090909091,\n", + " 'number_of_parameters': 85800963,\n", " 'model_size (MB)': 327,\n", - " 'time_per_pred_cpu': 0.0646173333333333}" + " 'time_per_pred_cpu': 0.06575066666666665}" ] }, - "execution_count": 27, + "execution_count": 37, "metadata": {}, "output_type": "execute_result" } @@ -1277,7 +1603,7 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 38, "metadata": {}, "outputs": [ { @@ -1303,6 +1629,7 @@ "