"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/09-model-deployment-what-were-doing-demo-trimmed-cropped-small.gif\" alt=\"demo of foodvision mini computer vision model being used on a mobile device to predict on an image of sushi and getting it right\" width=900/>\n",
"\n",
"*Trying out the [deployed version of FoodVision Mini](https://huggingface.co/spaces/mrdbourke/foodvision_mini) (what we're going to build) on my lunch. The model got it right too 🍣!*"
"For example, a banking database might rely on a machine learning model making predictions as to whether a transaction is fraudulent or not before transferring funds.\n",
"\n",
"Or an operating system may lower its resource consumption based on a machine learning model making predictions on how much power someone generally uses at specific times of day.\n",
"\n",
"These use cases can be mixed and matched as well.\n",
"For example, a Tesla car's computer vision system will interact with the car's route planning program (something else) and then the route planning program will get inputs and feedback from the driver (someone else).\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-what-is-model-deployment-someone-or-something-else.png\" width=900 alt=\"two use cases for model deployment, making your model available to someone else, for example, someone using it in an app, or making it available to something else such as another program or model\"/> \n",
"\n",
"*Machine learning model deployment involves making your model available to someone or something else. For example, someone might use your model as part of a food recognition app (such as FoodVision Mini or [Nutrify](https://nutrify.app)). And something else might be another model or program using your model such as a banking system using a machine learning model to detect if a transaction is fraud or not.* \n",
"One of the most important philosophical questions in machine learning is: \n",
"\n",
"<div align=\"center\">\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-does-it-exist.jpeg\" alt=\"curious dinosaur often referred to as philosoraptor asking the question if a machine learning model never leaves a notebook, does it exist?\" width=300/>\n",
"</div>\n",
"\n",
"Deploying a model is as important as training one.\n",
"\n",
"Because although you can get a pretty good idea of how your model's going to function by evaluting it on a well crafted test set or visualizing its results, you never really know how it's going to perform until you release it to the wild.\n",
"\n",
"Having people who've never used your model interact with it will often reveal edge cases you never thought of during training.\n",
"One solution would be to create another model that first classifies images as \"food\" or \"not food\" and passing the target image through that model first (this is what [Nutrify](https://nutrify.app) does).\n",
"Thus this highlights the importance of model deployment: it helps you figure out errors in your model that aren't obvious during training/testing.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-pytorch-workflow-with-deployment.png\" alt=\"A PyTorch workflow with added model deployment and monitoring step\" width=900/>\n",
"*We covered a PyTorch workflow back in [01. PyTorch Workflow](https://www.learnpytorch.io/01_pytorch_workflow/). But once you've got a good model, deployment is a good next step. Monitoring involves seeing how your model goes on the most important data split: data from the real world. For more resources on deployment and monitoring see [PyTorch Extra Resources](https://www.learnpytorch.io/pytorch_extra_resources/#resources-for-machine-learning-and-deep-learning-engineering).*"
"## Different types of machine learning model deployment\n",
"\n",
"Whole books could be written on the different types of machine learning model deployment (and many good ones are listed in [PyTorch Extra Resources](https://www.learnpytorch.io/pytorch_extra_resources/#resources-for-machine-learning-and-deep-learning-engineering)).\n",
"\n",
"And the field is still developing in terms of best practices.\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-deployment-questions-to-ask.png\" alt=\"some questions to ask when starting to deploy machine learning models, what's the model ideal use case, then work backwards and ask where's my model going to go and how's my model going to function\" width=900/>\n",
"\n",
"*When starting to deploy machine learning models, it's helpful to start by asking what's the most ideal use case and then work backwards from there, asking where the model's going to go and then how it's going to function.*"
"The main debate here is usually on-device (also called edge/in the browser) or on the cloud (a computer/server that isn't the *actual* device someone/something calls the model from). \n",
"| **On-device (edge/in the browser)** | Can be very fast (since no data leaves the device) | Limited compute power (larger models take longer to run) | \n",
"| | Privacy preserving (again no data has to leave the device) | Limited storage space (smaller model size required) | \n",
"| | Can deploy one model and use everywhere (via API) | Predictions can be slower due to data having to leave device and predictions having to come back (network latency) |\n",
"There are more details to these but I've left resources in the [extra-curriculum](https://www.learnpytorch.io/09_pytorch_model_deployment/#extra-curriculum) to learn more. \n",
"1. A model on-device that performs at 95% accuracy with an inference time (latency) of one second per prediction.\n",
"2. A model on the cloud that performs at 98% accuracy with an inference time of 10 seconds per per prediction (bigger, better model but takes longer to compute).\n",
"I've made these numbers up but they showcase a potential difference between on-device and on the cloud.\n",
"\n",
"Option 1 could potentially be a smaller less performant model that runs fast because its able to fit on a mobile device.\n",
"\n",
"Option 2 could potentially a larger more performant model that requires more compute and storage but it takes a bit longer to run because we have to send data off the device and get it back (so even though the actual prediction might be fast, the network time and data transfer has to factored in).\n",
"\n",
"For FoodVision Mini, we'd likely prefer option 1, because the small hit in performance is far outweighed by the faster inference speed.\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-model-deployment-on-device-vs-cloud.png\" width=900 alt=\"tesla computer vision system on device vs on the cloud\"/>\n",
"*In the case of a Tesla car's computer vision system, which would be better? A smaller model that performs well on device (model is on the car) or a larger model that performs better that's on the cloud? In this case, you'd much prefer the model being on the car. The extra network time it would take for data to go from the car to the cloud and then back to the car just wouldn't be worth it (or potentially even impossible with poor signal areas).*\n",
"> **Note:** For a full example of seeing what it's like to deploy a PyTorch model to an edge device, see the [PyTorch tutorial on achieving real-time inference (30fps+)](https://pytorch.org/tutorials/intermediate/realtime_rpi.html) with a computer vision model on a Raspberry Pi."
"* **Online (real-time)** - Predictions/inference happen **immediately**. For example, someone uploads an image, the image gets transformed and predictions are returned or someone makes a purchase and the transaction is verified to be non-fraudulent by a model so the purchase can go through.\n",
"* **Offline (batch)** - Predictions/inference happen **periodically**. For example, a photos application sorts your images into different categories (such as beach, mealtime, family, friends) whilst your mobile device is plugged into charge.\n",
"> **Note:** \"Batch\" refers to inference being performed on multiple samples at a time. However, to add a little confusion, batch processing can happen immediately/online (multiple images being classified at once) and/or offline (multiple images being predicted/trained on at once). \n",
"In the case of FoodVision Mini, we'd want our inference pipeline to happen online (real-time), so when someone uploads an image of pizza, steak or sushi, the prediction results are returned immediately (any slower than real-time would make a boring experience).\n",
"But for our training pipeline, it's okay for it to happen in a batch (offline) fashion, which is what we've been doing throughout the previous chapters."
"> **Note:** An [application programming interface (API)](https://en.wikipedia.org/wiki/API) is a way for two (or more) computer programs to interact with each other. For example, if your model was deployed as API, you would be able to write a program that could send data to it and then receive predictions back.\n",
"And one of the best ways to do so is by turning your machine learning model into a demo app with [Gradio](https://gradio.app) and then deploying it on Hugging Face Spaces.\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-tools-and-places-to-deploy-ml-models.png\" alt=\"tools and places to deploy machine learning models\" width=900/>\n",
"\n",
"*A handful of places and tools to host and deploy machine learning models. There are plenty I've missed so if you'd like to add more, please leave a [discussion on GitHub](https://github.com/mrdbourke/pytorch-deep-learning/discussions).*"
"We'll start by running an experiment to compare our best two models so far: EffNetB2 and ViT feature extractors.\n",
"\n",
"Then we'll deploy the one which performs closest to our goal metrics.\n",
"\n",
"Finally, we'll finish with a (BIG) surprise bonus.\n",
"\n",
"| **Topic** | **Contents** | \n",
"| ----- | ----- | \n",
"| **0. Getting setup** | We've written a fair bit of useful code over the past few sections, let's download it and make sure we can use it again. | \n",
"| **1. Get data** | Let's download the [`pizza_steak_sushi_20_percent.zip`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi_20_percent.zip) dataset so we can train our previously best performing models on the same dataset. |\n",
"| **2. FoodVision Mini model deployment experiment outline** | Even on the third milestone project, we're still going to be running multiple experiments to see which model (EffNetB2 or ViT) achieves closest to our goal metrics. |\n",
"| **3. Creating an EffNetB2 feature extractor** | An EfficientNetB2 feature extractor performed the best on our pizza, steak, sushi dataset in [07. PyTorch Experiment Tracking](https://www.learnpytorch.io/07_pytorch_experiment_tracking/), let's recreate it as a candidate for deployment. |\n",
"| **4. Creating a ViT feature extractor** | A ViT feature extractor has been the best performing model yet on our pizza, steak, sushi dataset in [08. PyTorch Paper Replicating](https://www.learnpytorch.io/08_pytorch_paper_replicating/), let's recreate it as a candidate for deployment alongside EffNetB2. |\n",
"| **5. Making predictions with our trained models and timing them** | We've built two of the best performing models yet, let's make predictions with them and track their results. |\n",
"| **6. Comparing model results, prediction times and size** | Let's compare our models to see which performs best with our goals. | \n",
"| **7. Bringing FoodVision Mini to life by creating a Gradio demo** | One of our models performs better than the other (in terms of our goals), so let's turn it into a working app demo! |\n",
"| **8. Turning our FoodVision Mini Gradio demo into a deployable app** | Our Gradio app demo works locally, let's prepare it for deployment! |\n",
"| **9. Deploying our Gradio demo to HuggingFace Spaces** | Let's take FoodVision Mini to the web and make it pubically accessible for all! |\n",
"| **10. Creating a BIG surprise** | We've built FoodVision Mini, time to step things up a notch. |\n",
"| **11. Deploying our BIG surprise** | Deploying one app was fun, how about we make it two? |"
"All of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n",
"\n",
"If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).\n",
"\n",
"And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. Getting setup \n",
"\n",
"As we've done previously, let's make sure we've got all of the modules we'll need for this section.\n",
"\n",
"We'll import the Python scripts (such as `data_setup.py` and `engine.py`) we created in [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n",
"\n",
"To do so, we'll download [`going_modular`](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/going_modular) directory from the [`pytorch-deep-learning` repository](https://github.com/mrdbourke/pytorch-deep-learning) (if we don't already have it).\n",
"\n",
"We'll also get the [`torchinfo`](https://github.com/TylerYep/torchinfo) package if it's not available. \n",
"\n",
"`torchinfo` will help later on to give us a visual representation of our model.\n",
"\n",
"And since later on we'll be using `torchvision` v0.13 package (available as of July 2022), we'll make sure we've got the latest versions.\n",
"\n",
"> **Note:** If you're using Google Colab, and you don't have a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`."
"> **Note:** If you're using Google Colab and the cell above starts to install various software packages, you may have to restart your runtime after running the above cell. After restarting, you can run the cell again and verify you've got the right versions of `torch` and `torchvision`.\n",
"\n",
"Now we'll continue with the regular imports, setting up device agnostic code and this time we'll also get the [`helper_functions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) script from GitHub.\n",
"The `helper_functions.py` script contains several functions we created in previous sections:\n",
"* `set_seeds()` to set the random seeds (created in [07. PyTorch Experiment Tracking section 0](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#create-a-helper-function-to-set-seeds)).\n",
"* `download_data()` to download a data source given a link (created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data)).\n",
"* `plot_loss_curves()` to inspect our model's training results (created in [04. PyTorch Custom Datasets section 7.8](https://www.learnpytorch.io/04_pytorch_custom_datasets/#78-plot-the-loss-curves-of-model-0))\n",
"\n",
"> **Note:** It may be a better idea for many of the functions in the `helper_functions.py` script to be merged into `going_modular/going_modular/utils.py`, perhaps that's an extension you'd like to try.\n"
"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 Vision Transformer (ViT) 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",
"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",
"This way we'll be comparing apples to apples (one model trained on a dataset to another model trained on the same dataset).\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) and more details in [04. PyTorch Custom Datasets section 1](https://www.learnpytorch.io/04_pytorch_custom_datasets/#1-get-data).\n",
"We can download the data using the `download_data()` function we created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data) from [`helper_functions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py). "
"Real-time in this case being ~30FPS (frames per second) because that's [about how fast the human eye can see](https://www.healthline.com/health/human-eye-fps) (there is debate on this but let's just use ~30FPS as our benchmark).\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-model-deployments-speed-vs-inference.png\" alt=\"foodvision mini goals in terms of performance and inference time.\" width=750/>\n",
"\n",
"*FoodVision Mini deployment goals. We'd like a fast predicting well-performing model (because a slow app is boring).*\n",
"We'll put an emphasis on speed, meaning, we'd prefer a model performing at 90%+ accuracy at ~30FPS than a model performing 95%+ accuracy at 10FPS.\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",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-model-deployment-two-experiments.png\" alt=\"modelling experiments for foodvision mini deployments, one effnetb2 feature extractor model and a vision transformer feature extractor model\" width=750 />\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)."
"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",
"1. Setup the pretrained weights as [`weights=torchvision.models.EfficientNet_B2_Weights.DEFAULT`](https://pytorch.org/vision/stable/models/generated/torchvision.models.efficientnet_b2.html#torchvision.models.EfficientNet_B2_Weights), 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 (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`](https://pytorch.org/vision/stable/models/generated/torchvision.models.efficientnet_b2.html#efficientnet-b2).\n",
"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",
"> **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 output, you would have to change the output layers accordingly. "
"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",
"We can do this by using the [`data_setup.create_dataloaders()`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/data_setup.py) 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",
"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."
"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",
"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 these as well as our `DataLoader`s 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)."
"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)"
"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 potential overfitting occurring from longer training)."
"To save our model we can use the [`utils.save_model()`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/utils.py) 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",
"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)."
"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",
"To check our model's size in bytes, we can use Python's [`pathlib.Path.stat(\"path_to_model\").st_size`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat) and then we can convert it (roughly) to megabytes by dividing it by `(1024*1024)`. "
"We've got a few statistics about our EffNetB2 feature extractor 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",
"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. "
"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`."
"Our ViT model has *far* more parameters than our EffNetB2 model. Perhaps this will come into play when we compare our models across speed and performance later on."
"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. "
"...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. "
"> **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)."
"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). "
"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). "
"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)`. "
"Woah, that looks like a fair bit more than our EffNetB2!\n",
"\n",
"> **Note:** A larger number of parameters (or weights/patterns) generally means a model has a higher *capacity* to learn, whether it actually uses this extra capacity is another story. In light of this, our EffNetB2 model has 7,705,221 parameters where as our ViT model has 85,800,963 (11.1x more) so we could assume that our ViT model has more of a capacity to learn, if given more data (more opportunities to learn). However, this larger capacity to learn ofen comes with an increased model filesize and a longer time to perform inference.\n",
"\n",
"Now let's create a dictionary with some important characteristics of our ViT model."
"Ideally, if we're deploying our FoodVision Mini model to a mobile device so people can take photos of their food and identify it, we'd like the predictions to happen at real-time (~30 frames per second).\n",
"\n",
"That's why our second criteria is: a fast model.\n",
"\n",
"To find out how long each of our models take to performance inference, let's create a function called `pred_and_store()` to iterate over each of the test dataset images one by one and perform a prediction. \n",
"We'll time each of the predictions as well as store the results in a common prediction format: a list of dictionaries (where each element in the list is a single prediction and each sinlge prediction is a dictionary). \n",
"> **Note:** We time the predictions one by one rather than by batch because when our model is deployed, it will likely only be making a prediction on one image at a time. As in, someone takes a photo and our model predicts on that single image.\n",
"\n",
"Since we'd like to make predictions across all the images in the test set, let's first get a list of all of the test image paths so we can iterate over them. \n",
"To do so, we'll use Python's [`pathlib.Path(\"target_dir\").glob(\"*/*.jpg\"))`](https://docs.python.org/3/library/pathlib.html#basic-use) to find all of the filepaths in a target directory with the extension `.jpg` (all of our test images)."
"1. Create a function that takes a list of paths, a trained PyTorch model, a series of transforms (to prepare images), a list of target class names and a target device.\n",
"2. Create an empty list to store prediction dictionaries (we want the function to return a list of dictionaries, one for each prediction).\n",
"3. Loop through the target input paths (steps 4-14 will happen inside the loop).\n",
"4. Create an empty dictionary for each iteration in the loop to store prediction values per sample.\n",
"8. Transform the image so it's capable of being used with the target model as well as add a batch dimension and send the image to the target device.\n",
"10. Turn on [`torch.inference_mode()`](https://pytorch.org/docs/stable/generated/torch.inference_mode.html) and pass the target transformed image to the model and calculate the prediction probability using `torch.softmax()` and the target label using `torch.argmax()`.\n",
"11. Add the prediction probability and prediction class to the prediction dictionary created in step 4. Also make sure the prediction probability is on the CPU so it can be used with non-GPU libraries such as NumPy and pandas for later inspection.\n",
"12. End the prediction timer started in step 6 and add the time to the prediction dictionary created in step 4.\n",
"13. See if the predicted class matches the ground truth class from step 5 and add the result to the prediction dictionary created in step 4.\n",
"14. Append the updated prediction dictionary to the empty list of predictions created in step 2.\n",
"15. Return the list of prediction dictionaries.\n",
"\n",
"A bunch of steps, but nothing we can't handle!\n",
"And you know what, since our `pred_and_store()` is a pretty good utility function for making and storing predictions, it could be stored to [`going_modular.going_modular.predictions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/predictions.py) for later use. That might be an extension you'd like to try, check out [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/) for ideas."
"Time to test out our `pred_and_store()` function!\n",
"\n",
"Let's start by using it to make predictions across the test dataset with our EffNetB2 model, paying attention to two details:\n",
"\n",
"1. **Device** - We'll hard code the `device` parameter to use `\"cpu\"` because when we deploy our model, we won't always have access to a `\"cuda\"` (GPU) device.\n",
" * Making the predictions on CPU will be a good indicator of speed of inference too because generally predictions on CPU devices are slower than GPU devices.\n",
"2. **Transforms** - We'll also be sure to set the `transform` parameter to `effnetb2_transforms` to make sure the images are opened and transformed in the same way our `effnetb2` model has been trained on. "
"Hmm, how does that average prediction time live up to our criteria of our model performing at real-time (~30FPS or 0.03 seconds per prediction)?\n",
"\n",
"> **Note:** Prediction times will be different across different hardware types (e.g. a local Intel i9 vs Google Colab CPU). The better and faster the hardware, generally, the faster the prediction. For example, on my local deep learning PC with an Intel i9 chip, my average prediction time with EffNetB2 is around 0.031 seconds (just under real-time). However, on Google Colab (I'm not sure what CPU hardware Colab uses but it looks like it might be an [Intel(R) Xeon(R)](https://stackoverflow.com/questions/47805170/whats-the-hardware-spec-for-google-colaboratory)), my average prediction time with EffNetB2 is about 0.1396 seconds (3-4x slower).\n",
"\n",
"Let's add our EffNetB2 average time per prediction to our `effnetb2_stats` dictionary."
"We've made predictions with our EffNetB2 model, now let's do the same for our ViT model.\n",
"\n",
"To do so, we can use the `pred_and_store()` function we created above except this time we'll pass in our `vit` model as well as the `vit_transforms`.\n",
"\n",
"And we'll keep the predictions on the CPU via `device=\"cpu\"` (a natural extension here would be to test the prediction times on CPU and on GPU)."
"And just like before, since our ViT model's predictions are in the form of a list of dictionaries, we can easily turn them into a pandas DataFrame for further inspection. "
"print(f\"ViT average time per prediction: {vit_average_time_per_pred} seconds\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Well, that looks a little slower than our EffNetB2 model's average time per prediction but how does it look in terms of our second criteria: speed?\n",
"\n",
"For now, let's add the value to our `vit_stats` dictionary so we can compare it to our EffNetB2 model's stats.\n",
"\n",
"> **Note:** The average time per prediction values will be highly dependent on the hardware you make them on. For example, for the ViT model, my average time per prediction (on the CPU) was 0.0693-0.0777 seconds on my local deep learning PC with an Intel i9 CPU. Where as on Google Colab, my average time per prediction with the ViT model was 0.6766-0.7113 seconds."
"It seems our models are quite close in terms of overall test accuracy but how do they look across the other fields?\n",
"\n",
"One way to find out would be to divide the ViT model statistics by the EffNetB2 model statistics to find out the different ratios between the models.\n",
"# Compare ViT to EffNetB2 across different characteristics\n",
"pd.DataFrame(data=(df.set_index(\"model\").loc[\"ViT\"] / df.set_index(\"model\").loc[\"EffNetB2\"]), # divide ViT statistics by EffNetB2 statistics\n",
" columns=[\"ViT to EffNetB2 ratios\"]).T"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It seems our ViT model outperforms the EffNetB2 model across the performance metrics (test loss, where lower is better and test accuracy, where higher is better) but at the expense of having:\n",
"Perhaps if we had unlimited compute power but for our use case of deploying the FoodVision Mini model to a smaller device (e.g. a mobile phone), we'd likely start out with the EffNetB2 model for faster predictions at a slightly reduced performance but dramatically smaller size."
" ax.annotate(text=row[\"model\"], # note: depending on your version of Matplotlib, you may need to use \"s=...\" or \"text=...\", see: https://github.com/faustomorales/keras-ocr/issues/183#issuecomment-977733270 \n",
"The plot really visualizes the **speed vs. performance tradeoff**, in other words, when you have a larger, better performing deep model (like our ViT model), it *generally* takes longer to perform inference (higher latency).\n",
"And it can be tempting to just deploy the *best* performing model but it's also good to take into consideration where the model is going to be performing.\n",
"In our case, the differences between our model's performance levels (on the test loss and test accuracy) aren't too extreme.\n",
"\n",
"But since we'd like to put an emphasis on speed to begin with, we're going to stick with deploying EffNetB2 since it's faster and has a much smaller footprint.\n",
"\n",
"> **Note:** Prediction times will be different across different hardware types (e.g. Intel i9 vs Google Colab CPU vs GPU) so it's important to think about and test where your model is going to end up. Asking questions like \"where is the model going to be run?\" or \"what is the ideal scenario for running the model?\" and then running experiments to try and provide answers on your way to deployment is very helpful. "
"The overall premise of Gradio is very similar to what we've been repeating throughout the course.\n",
"\n",
"What are our **inputs** and **outputs**?\n",
"\n",
"And how should we get there?\n",
"\n",
"Well that's what our machine learning model does.\n",
"\n",
"```\n",
"inputs -> ML model -> outputs\n",
"```\n",
"\n",
"In our case, for FoodVision Mini, our inputs are images of food, our ML model is EffNetB2 and our outputs are classes of food (pizza, steak or sushi).\n",
"\n",
"```\n",
"images of food -> EffNetB2 -> outputs\n",
"```\n",
"\n",
"Though the concepts of inputs and outputs can be bridged to almost any other kind of ML problem.\n",
"\n",
"Your inputs and outputs might be any combination of the following:\n",
"* Images\n",
"* Text\n",
"* Video\n",
"* Tabular data\n",
"* Audio\n",
"* Numbers\n",
"* & more\n",
"\n",
"And the ML model you build will depend on your inputs and outputs.\n",
"Gradio emulates this paradigm by creating an interface ([`gradio.Interface()`](https://gradio.app/docs/#interface-header)) from inputs to outputs.\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-gradio-workflow.png\" alt=\"gradio workflow of inputs flowing into some kind of model or function and then producing outputs\" width=900/>\n",
"\n",
"*Gradio provides a very helpful `Interface` class to easily create an inputs -> model/function -> outputs workflow where the inputs and outputs could be almost anything you want. For example, you might input Tweets (text) to see if they're about machine learning or not or [input a text prompt to generate images](https://huggingface.co/blog/stable_diffusion).*\n",
"> **Note:** Gradio has a vast number of possible `inputs` and `outputs` options known as \"Components\" from images to text to numbers to audio to videos and more. You can see all of these in the [Gradio Components documentation](https://gradio.app/docs/#components)."
"To create our FoodVision Mini demo with Gradio, we'll need a function to map our inputs to our outputs.\n",
"\n",
"We created a function earlier called `pred_and_store()` to make predictions with a given model across a list of target files and store them in a list of dictionaries.\n",
"More specifically, we want a function that takes an image as input, preprocesses (transforms) it, makes a prediction with EffNetB2 and then returns the prediction (pred or pred label for short) as well as the prediction probability (pred prob).\n",
"\n",
"And while we're here, let's return the time it took to do so too:\n",
"\n",
"```\n",
"input: image -> transform -> predict with EffNetB2 -> output: pred, pred prob, time taken\n",
"```\n",
"\n",
"This will be our `fn` parameter for our Gradio interface.\n",
"\n",
"First, let's make sure our EffNetB2 model is on the CPU (since we're sticking with CPU-only predictions, however you could change this if you have access to a GPU)."
" # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)\n",
"Running the cell above a few times we can see different prediction probabilities for each label from our EffNetB2 model as well as the time it took per prediction."
"Gradio's [`Interface`](https://gradio.app/docs/#interface) class takes a list of `examples` of as an optional parameter (`gradio.Interface(examples=List[Any])`).\n",
"Our Gradio demo will showcase these as example inputs to our demo so people can try it out and see what it does without uploading any of their own data. "
"Time to put everything together and bring our FoodVision Mini demo to life!\n",
"\n",
"Let's create a Gradio interface to replicate the workflow:\n",
"\n",
"```\n",
"input: image -> transform -> predict with EffNetB2 -> output: pred, pred prob, time taken\n",
"```\n",
"\n",
"We can do with the [`gradio.Interface()`](https://gradio.app/docs/#interface) class with the following parameters:\n",
"* `fn` - a Python function to map `inputs` to `outputs`, in our case, we'll use our `predict()` function.\n",
"* `inputs` - the input to our interface, such as an image using [`gradio.Image()`](https://gradio.app/docs/#image) or `\"image\"`. \n",
"* `outputs` - the output of our interface once the `inputs` have gone through the `fn`, such as a label using [`gradio.Label()`](https://gradio.app/docs/#label) (for our model's predicted labels) or number using [`gradio.Number()`](https://gradio.app/docs/#number) (for our model's prediction time).\n",
" * **Note:** Gradio comes with many in-built `inputs` and `outputs` options known as [\"Components\"](https://gradio.app/docs/#components).\n",
"* `examples` - a list of examples to showcase for the demo.\n",
"* `title` - a string title of the demo.\n",
"* `description` - a string description of the demo.\n",
"* `article` - a reference note at the bottom of the demo.\n",
"Once we've created our demo instance of `gr.Interface()`, we can bring it to life using [`gradio.Interface().launch()`](https://gradio.app/docs/#launch-header) or `demo.launch()` command. \n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/09-gradio-running-in-google-colab-and-in-browser.gif\" alt=\"Gradio demo running in Google Colab and on the web\" width=750/>\n",
"\n",
"*FoodVision Mini Gradio demo running in Google Colab and in the browser (the link when running from Google Colab only lasts for 72 hours). You can see the [permanent live demo on Hugging Face Spaces](https://huggingface.co/spaces/mrdbourke/foodvision_mini).*\n",
"If you set the parameter `share=True` in the `launch()` method, Gradio also provides you with a shareable link such as `https://123XYZ.gradio.app` (this link is an example only and likely expired) which is valid for 72-hours.\n",
"The link provides a proxy back to the Gradio interface you launched.\n",
"\n",
"For more permanent hosting, you can upload your Gradio app to [Hugging Face Spaces](https://huggingface.co/spaces) or anywhere that runs Python code."
"To make our FoodVision Mini demo more permanent, we can package it into an app and upload it to [Hugging Face Spaces](https://huggingface.co/spaces/launch)."
"Hugging Face Spaces is a resource that allows you to host and share machine learning apps.\n",
"\n",
"Building a demo is one of the best ways to showcase and test what you've done.\n",
"\n",
"And Spaces allows you to do just that.\n",
"\n",
"You can think of Hugging Face as the GitHub of machine learning.\n",
"\n",
"If having a good GitHub portfolio showcases your coding abilities, having a good Hugging Face portfolio can showcase your machine learning abilities.\n",
"\n",
"> **Note:** There are many other places we could upload and host our Gradio app such as, Google Cloud, AWS (Amazon Web Services) or other cloud vendors, however, we're going to use Hugging Face Spaces due to the ease of use and wide adoption by the machine learning community."
" * **Note:** `app.py` is the default filename used for Hugging Face Spaces, if you deploy your app there, Spaces will by default look for a file called `app.py` to run. This is changeable in settings.\n",
"* `requirements.txt` contains the dependencies to run our app such as `torch`, `torchvision` and `gradio`.\n",
"\n",
"Why this way?\n",
"\n",
"Because it's one of the simplest layouts we could begin with. \n",
"\n",
"Our focus is: *experiment, experiment, experiment!* \n",
"\n",
"The quicker we can run smaller experiments, the better our bigger ones will be.\n",
"\n",
"We're going to work towards recreating the structure above but you can see a live demo app running on Hugging Face Spaces as well as the file structure:\n",
"* [Live Gradio demo of FoodVision Mini 🍕🥩🍣](https://huggingface.co/spaces/mrdbourke/foodvision_mini).\n",
"* [FoodVision Mini file structure on Hugging Face Spaces](https://huggingface.co/spaces/mrdbourke/foodvision_mini/tree/main)."
"To begin, let's first create a `demos/` directory to store all of our FoodVision Mini app files.\n",
"\n",
"We can do with Python's [`pathlib.Path(\"path_to_dir\")`](https://docs.python.org/3/library/pathlib.html#basic-use) to establish the directory path and [`pathlib.Path(\"path_to_dir\").mkdir()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir) to create it. "
"Now to verify our examples are present, let's list the contents of our `demos/foodvision_mini/examples/` directory with [`os.listdir()`](https://docs.python.org/3/library/os.html#os.listdir) and then format the filepaths into a list of lists (so it's compatible with Gradio's [`gradio.Interface()`](https://gradio.app/docs/#interface) `example` parameter)."
"We previously saved our FoodVision Mini EffNetB2 feature extractor model under `models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth`.\n",
"\n",
"And rather double up on saved model files, let's move our model to our `demos/foodvision_mini` directory.\n",
"We can do so using Python's [`shutil.move()`](https://docs.python.org/3/library/shutil.html#shutil.move) method and passing in `src` (the source path of the target file) and `dst` (the destination path of the target file to be moved to) parameters. "
"[INFO] Attempting to move models/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth to demos/foodvision_mini/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth\n",
"Our current model's `state_dict` is saved to `demos/foodvision_mini/09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth`.\n",
"\n",
"To load it in we can use `model.load_state_dict()` along with `torch.load()`.\n",
"\n",
"> **Note:** For a refresh on saving and loading a model (or a model's `state_dict` in PyTorch, see [01. PyTorch Workflow Fundamentals section 5: Saving and loading a PyTorch model](https://www.learnpytorch.io/01_pytorch_workflow/#5-saving-and-loading-a-pytorch-model) or see the PyTorch recipe for [What is a `state_dict` in PyTorch?](https://pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html)\n",
"\n",
"But before we can do this, we first need a way to instantiate a `model`.\n",
"To do this in a modular fashion we'll create a script called `model.py` which contains our `create_effnetb2_model()` function we created in [section 3.1: *Creating a function to make an EffNetB2 feature extractor*](https://www.learnpytorch.io/09_pytorch_model_deployment/#31-creating-a-function-to-make-an-effnetb2-feature-extractor).\n",
"That way we can import the function in *another* script (see `app.py` below) and then use it to create our EffNetB2 `model` instance as well as get its appropriate transforms.\n",
"\n",
"Just like in [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/), we'll use the `%%writefile path/to/file` magic command to turn a cell of code into a file."
"We've now got a `model.py` script as well as a path to a saved model `state_dict` that we can load in.\n",
"\n",
"Time to construct `app.py`.\n",
"\n",
"We call it `app.py` because by default when you create a HuggingFace Space, it looks for a file called `app.py` to run and host (though you can change this in settings).\n",
"1. **Imports and class names setup** - Here we'll import the various dependencies for our demo including the `create_effnetb2_model()` function from `model.py` as well as setup the different class names for our FoodVision Mini app. \n",
"2. **Model and transforms preparation** - Here we'll create an EffNetB2 model instance along with the transforms to go with it and then we'll load in the saved model weights/`state_dict`. When we load the model we'll also set `map_location=torch.device(\"cpu\")` in [`torch.load()`](https://pytorch.org/docs/stable/generated/torch.load.html) so our model gets loaded onto the CPU regardless of the device it trained on (we do this because we won't necessarily have a GPU when we deploy and we'll get an error if our model is trained on GPU but we try to deploy it to CPU without explicitly saying so).\n",
"3. **Predict function** - Gradio's `gradio.Interface()` takes a `fn` parameter to map inputs to outputs, our `predict()` function will be the same as the one we defined above in [section 7.2: *Creating a function to map our inputs and outputs*](https://www.learnpytorch.io/09_pytorch_model_deployment/#72-creating-a-function-to-map-our-inputs-and-outputs), it will take in an image and then use the loaded transforms to preprocess it before using the loaded model to make a prediction on it.\n",
" * **Note:** We'll have to create the example list on the fly via the `examples` parameter. We can do so by creating a list of the files inside the `examples/` directory with: `[[\"examples/\" + example] for example in os.listdir(\"examples\")]`.\n",
"4. **Gradio app** - This is where the main logic of our demo will live, we'll create a `gradio.Interface()` instance called `demo` to put together our inputs, `predict()` function and outputs. And we'll finish the script by calling `demo.launch()` to launch our FoodVision Mini demo!"
" # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)\n",
" pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}\n",
"The last file we need to create for our FoodVision Mini app is a [`requirements.txt` file](https://learnpython.com/blog/python-requirements-file/).\n",
"\n",
"This will be a text file containing all of the required dependencies for our demo.\n",
"\n",
"When we deploy our demo app to Hugging Face Spaces, it will search through this file and install the dependencies we define so our app can run.\n",
"Defining the version number is not 100% required but we will for now so if any breaking updates occur in future releases, our app still runs (PS if you find any errors, feel free to post on the course [GitHub Issues](https://github.com/mrdbourke/pytorch-deep-learning/issues))."
"We've got a file containing our FoodVision Mini demo, now how do we get it to run on Hugging Face Spaces?\n",
"\n",
"There are two main options for uploading to a Hugging Face Space (also called a [Hugging Face Repository](https://huggingface.co/docs/hub/repositories-getting-started#getting-started-with-repositories), similar to a git repository): \n",
"1. [Uploading via the Hugging Face Web interface (easiest)](https://huggingface.co/docs/hub/repositories-getting-started#adding-files-to-a-repository-web-ui).\n",
"2. [Uploading via the command line or terminal](https://huggingface.co/docs/hub/repositories-getting-started#terminal).\n",
" * **Bonus:** You can also use the [`huggingface_hub` library](https://huggingface.co/docs/huggingface_hub/index) to interact with Hugging Face, this would be a good extension to the above two options.\n",
"\n",
"Feel free to read the documentation on both options but we're going to go with option two.\n",
"We can download our zip file from Google Colab using [`google.colab.files.download(\"demos/foodvision_mini.zip\")`](https://colab.research.google.com/notebooks/io.ipynb) (we'll put this inside a `try` and `except` block just in case we're not running the code inside Google Colab, and if so we'll print a message saying to manually download the files).\n",
"Otherwise, you can see the `foodvision_mini.zip` folder (and more) on the [course GitHub under the `demos/` directory](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/demos). "
" * **Note:** This step may take 5-10 minutes depending on your internet connection. And if you're facing errors, you may need to upgrade `pip` first: `pip install --upgrade pip`.\n",
"We've verified our FoodVision Mini app works locally, however, the fun of creating a machine learning demo is to show it to other people and allow them to use it.\n",
"To do so, we're going to upload our FoodVision Mini demo to Hugging Face. \n",
"\n",
"> **Note:** The following series of steps uses a Git (a file tracking system) workflow. For more on how Git works, I'd recommend going through the [Git and GitHub for Beginners tutorial](https://youtu.be/RGOj5yH7evk) on freeCodeCamp.\n",
"1. [Sign up](https://huggingface.co/join) for a Hugging Face account. \n",
"2. Start a new Hugging Face Space by going to your profile and then [clicking \"New Space\"](https://huggingface.co/new-space).\n",
" * **Note:** A Space in Hugging Face is also known as a \"code repository\" (a place to store your code/files) or \"repo\" for short.\n",
"3. Give the Space a name, for example, mine is called `mrdbourke/foodvision_mini`, you can see it here: https://huggingface.co/spaces/mrdbourke/foodvision_mini\n",
"4. Select a license (I used [MIT](https://opensource.org/licenses/MIT)).\n",
"5. Select Gradio as the Space SDK (software development kit). \n",
" * **Note:** You can use other options such as Streamlit but since our app is built with Gradio, we'll stick with that.\n",
"6. Choose whether your Space is it's public or private (I selected public since I'd like my Space to be available to others).\n",
"7. Click \"Create Space\".\n",
"8. Clone the repo locally by running something like: `git clone https://huggingface.co/spaces/[YOUR_USERNAME]/[YOUR_SPACE_NAME]` in terminal or command prompt.\n",
" * **Note:** You can also add files via uploading them under the \"Files and versions\" tab.\n",
"9. Copy/move the contents of the downloaded `foodvision_mini` folder to the cloned repo folder.\n",
"10. To upload and track larger files (e.g. files over 10MB or in our case, our PyTorch model file) you'll need to [install Git LFS](https://git-lfs.github.com/) (which stands for \"git large file storage\").\n",
"11. After you've installed Git LFS, you can activate it by running `git lfs install`.\n",
"12. In the `foodvision_mini` directory, track the files over 10MB with Git LFS with `git lfs track \"*.file_extension\"`.\n",
" * Track EffNetB2 PyTorch model file with `git lfs track \"09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth\"`.\n",
"13. Track `.gitattributes` (automatically created when cloning from HuggingFace, this file will help ensure our larger files are tracked with Git LFS). You can see an example `.gitattributes` file on the [FoodVision Mini Hugging Face Space](https://huggingface.co/spaces/mrdbourke/foodvision_mini/blob/main/.gitattributes).\n",
"If everything worked, you should see a live running example of our FoodVision Mini Gradio demo like the one here: https://huggingface.co/spaces/mrdbourke/foodvision_mini \n",
"And we can even embed our FoodVision Mini Gradio demo into our notebook as an [iframe](https://gradio.app/sharing_your_app/#embedding-with-iframes) with [`IPython.display.IFrame`](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.IFrame) and a link to our space in the format `https://hf.space/embed/[YOUR_USERNAME]/[YOUR_SPACE_NAME]/+`."
"We've spent the past few sections and chapters working on bringing FoodVision Mini to life.\n",
"\n",
"And now we've seen it working in a live demo, how about we step things up a notch?\n",
"\n",
"How?\n",
"\n",
"FoodVision Big!\n",
"\n",
"Since FoodVision Mini is trained on pizza, steak and sushi images from the [Food101 dataset](https://pytorch.org/vision/main/generated/torchvision.datasets.Food101.html) (101 classes of food x 1000 images each), how about we make FoodVision Big by training a model on all 101 classes!\n",
"From pizza, steak, sushi to pizza, steak, sushi, hot dog, apple pie, carrot cake, chocolate cake, french fries, garlic bread, ramen, nachos, tacos and more!\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/09-model-deployment-foodvision-mini-to-foodvision-big.png\" alt=\"foodvision mini model on three classes: pizza, steak, sushi and foodvision big on all of the 101 classes in the food101 dataset\" width=900/>\n",
"\n",
"*FoodVision Mini works with three food classes: pizza, steak and sushi. And FoodVision Big steps it up a notch to work across 101 food classes: all of the [classes in the Food101 dataset](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt).*"
"When creating FoodVision Mini we saw that the EffNetB2 model was a good tradeoff between speed and performance (it performed well with a fast speed).\n",
"\n",
"So we'll continue using the same model for FoodVision Big.\n",
"We can create an EffNetB2 feature extractor for Food101 by using our `create_effnetb2_model()` function we created above, in [section 3.1](https://www.learnpytorch.io/09_pytorch_model_deployment/#31-creating-a-function-to-make-an-effnetb2-feature-extractor), and passing it the parameter `num_classes=101` (since Food101 has 101 classes)."
"See how just like our EffNetB2 model for FoodVision Mini the base layers are frozen (these are pretrained on ImageNet) and the outer layers (the `classifier` layers) are trainable with an output shape of `[batch_size, 101]` (`101` for 101 classes in Food101). \n",
"Now since we're going to be dealing with a fair bit more data than usual, how about we add a little data augmentation to our transforms (`effnetb2_transforms`) to augment the training data.\n",
"\n",
"> **Note:** Data augmentation is a technique used to alter the appearance of an input training sample (e.g. rotating an image or slightly skewing it) to artificially increase the diversity of a training dataset to hopefully prevent overfitting. You can see more on data augmentation in [04. PyTorch Custom Datasets section 6](https://www.learnpytorch.io/04_pytorch_custom_datasets/#6-other-forms-of-transforms-data-augmentation).\n",
"\n",
"Let's compose a `torchvision.transforms` pipeline to use [`torchvision.transforms.TrivialAugmentWide()`](https://pytorch.org/vision/main/generated/torchvision.transforms.TrivialAugmentWide.html) (the same data augmentation used by the PyTorch team in their [computer vision recipes](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/#break-down-of-key-accuracy-improvements)) as well as the `effnetb2_transforms` to transform our training images. "
"For FoodVision Mini, we made our own [custom data splits](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/04_custom_data_creation.ipynb) of the entire Food101 dataset.\n",
"\n",
"To get the whole Food101 dataset, we can use [`torchvision.datasets.Food101()`](https://pytorch.org/vision/main/generated/torchvision.datasets.Food101.html).\n",
"\n",
"We'll first setup a path to directory `data/` to store the images. \n",
"\n",
"Then we'll download and transform the training and testing dataset splits using `food101_train_transforms` and `effnetb2_transforms` to transform each dataset respectively. \n",
"> This is because there is over 100,000 images being downloaded (101 classes x 1000 images per class). If you restart your Google Colab runtime and come back to this cell, the images will have to redownload. Alternatively, if you're running this notebook locally, the images will be cached and stored in the directory specified by the `root` parameter of `torchvision.datasets.Food101()`. "
"Ho ho! Those are some delicious sounding foods (although I've never heard of \"beignets\"... update: after a quick Google search, beignets also look delicious). \n",
" \n",
"You can see a full list of the Food101 class names on the course GitHub under [`extras/food101_class_names.txt`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt)."
"We don't *need* to create another subset of the Food101 dataset, we could train and evaluate a model across the whole 101,000 images.\n",
"\n",
"But to keep training fast, let's create a 20% split of the training and test datasets.\n",
"\n",
"Our goal will be to see if we can beat the original [Food101 paper's](https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/) best results with only 20% of the data.\n",
"\n",
"To breakdown the datasets we've used/will use:\n",
"| Extension | FoodVision Big | Food101 all data | 101 | 75750 | 25250 | \n",
"\n",
"Can you see the trend? \n",
"\n",
"Just like our model size slowly increased overtime, so has the size of the dataset we've been using for experiments.\n",
"\n",
"> **Note:** To truly beat the original Food101 paper's results with 20% of the data, we'd have to train a model on 20% of the training data and then evaluate our model on the *whole* test set rather than the split we created. I'll leave this as an extension exercise for you to try. I'd also encourage you to try training a model on the entire Food101 training dataset.\n",
"\n",
"To make our FoodVision Big (20% data) split, let's create a function called `split_dataset()` to split a given dataset into certain proportions.\n",
"\n",
"We can use [`torch.utils.data.random_split()`](https://pytorch.org/docs/stable/data.html#torch.utils.data.random_split) to create splits of given sizes using the `lengths` parameter. \n",
"\n",
"The `lengths` parameter accepts a list of desired split lengths where the total of the list must equal the overall length of the dataset.\n",
"\n",
"For example, with a dataset of size 100, you could pass in `lengths=[20, 80]` to receive a 20% and 80% split.\n",
"\n",
"We'll want our function to return two splits, one with the target length (e.g. 20% of the training data) and the other with the remaining length (e.g. the remaining 80% of the training data).\n",
"\n",
"Finally, we'll set `generator` parameter to a `torch.manual_seed()` value for reproducibility."
" print(f\"[INFO] Splitting dataset of length {len(dataset)} into splits of size: {length_1} ({int(split_size*100)}%), {length_2} ({int((1-split_size)*100)}%)\")\n",
"Now let's turn our Food101 20% dataset splits into `DataLoader`'s using `torch.utils.data.DataLoader()`.\n",
"\n",
"We'll set `shuffle=True` for the training data only and the batch size to `32` for both datasets.\n",
"\n",
"And we'll set `num_workers` to `4` if the CPU count is available or `2` if it's not (though the value of `num_workers` is very experimental and will depend on the hardware you're using, there's an [active discussion thread about this on the PyTorch forums](https://discuss.pytorch.org/t/guidelines-for-assigning-num-workers-to-dataloader/813))."
"NUM_WORKERS = 2 if os.cpu_count() <= 4 else 4 # this value is very experimental and will depend on the hardware you have available, Google Colab generally provides 2x CPUs\n",
"We'll create an optimizer using `torch.optim.Adam()` and a learning rate of `1e-3`.\n",
"\n",
"And because we've got so many classes, we'll also setup a loss function using `torch.nn.CrossEntropyLoss()` with `label_smoothing=0.1`, inline with [`torchvision`'s state-of-the-art training recipe](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/#label-smoothing).\n",
"Label smoothing is a regularization technique (regularization is another word to describe the process of [preventing overfitting](https://www.learnpytorch.io/04_pytorch_custom_datasets/#81-how-to-deal-with-overfitting)) that reduces the value a model gives to anyone label and spreads it across the other labels.\n",
"\n",
"In essence, rather than a model getting *too confident* on a single label, label smoothing gives a non-zero value to other labels to help aid in generalization.\n",
"\n",
"For example, if a model *without* label smoothing had the following outputs for 5 classes:\n",
"\n",
"```\n",
"[0, 0, 0.99, 0.01, 0]\n",
"```\n",
"\n",
"A model *with* label smoothing may have the following outputs:\n",
"\n",
"```\n",
"[0.01, 0.01, 0.96, 0.01, 0.01]\n",
"```\n",
"\n",
"The model is still confident on its prediction of class 3 but giving small values to the other labels forces the model to at least consider other options.\n",
"\n",
"Finally, to keep things quick, we'll train our model for five epochs using the `engine.train()` 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) with the goal of beating the original Food101 paper's result of 56.4% accuracy on the test set.\n",
"\n",
"Let's train our biggest model yet!\n",
"\n",
"> **Note:** Running the cell below will take ~15-20 minutes to run on Google Colab. This is because it's training the biggest model with the largest amount of data we've used so far (15,150 training images, 5050 testing images). And it's a reason we decided to split 20% of the full Food101 dataset off before (so training didn't take over an hour). "
"Looks like we beat the original Food101 paper's results of 56.4% accuracy with only 20% of the training data (though we only evaluated on 20% of the testing data too, to fully replicate the results, we could evaluate on 100% of the testing data). \n",
"It looks like our regularization techniques (data augmentation and label smoothing) helped prevent our model from overfitting (the training loss is still higher than the test loss) this indicates our model has a bit more capacity to learn and could improve with further training. "
"And then loading the saved `state_dict()` with [`torch.nn.Module.load_state_dict()`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=load_state_dict#torch.nn.Module.load_state_dict) and [`torch.load()`](https://pytorch.org/docs/stable/generated/torch.load.html). "
"Hmm, it looks like the model size stayed largely the same (30 MB for FoodVision Big and 29 MB for FoodVision Mini) despite the large increase in the number of classes.\n",
"\n",
"This is because all the extra parameters for FoodVision Big are *only* in the last layer (the classifier head). \n",
"\n",
"All of the base layers are the same between FoodVision Big and FoodVision Mini.\n",
"\n",
"Going back up and comparing the model summaries will give more details.\n",
"We've got a trained and saved EffNetB2 model on 20% of the Food101 dataset.\n",
"\n",
"And instead of letting our model live in a folder all its life, let's deploy it!\n",
"\n",
"We'll deploy our FoodVision Big model in the same way we deployed our FoodVision Mini model, as a Gradio demo on Hugging Face Spaces.\n",
"\n",
"To begin, let's create a `demos/foodvision_big/` directory to store our FoodVision Big demo files as well as a `demos/foodvision_big/examples` directory to hold an example image to test the demo with.\n",
"\n",
"When we're finished we'll have the following file structure:\n",
"For our example image, we're going to use the faithful [`pizza-dad` image](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/images/04-pizza-dad.jpeg) (a photo of my dad eating pizza).\n",
"So let's download it from the course GitHub via the `!wget` command and then we can move it to `demos/foodvision_big/examples` with the `!mv` command (short for \"move\").\n",
"\n",
"While we're here we'll move our trained Food101 EffNetB2 model from `models/09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth` to `demos/foodvision_big` as well."
"Because there are so many classes in the Food101 dataset, instead of storing them as a list in our `app.py` file, let's save them to a `.txt` file and read them in when necessary instead.\n",
"Wonderful, now we can write these to a text file by first creating a path to `demos/foodvision_big/class_names.txt` and then opening a file with Python's `open()` and then writing to it leaving a new line for each class.\n",
"\n",
"Ideally, we want our class names to be saved like:\n",
"Excellent, now let's make sure we can read them in.\n",
"\n",
"To do so we'll use Python's [`open()`](https://www.w3schools.com/python/ref_func_open.asp) in read mode (`\"r\"`) and then use the [`readlines()`](https://www.w3schools.com/python/ref_file_readlines.asp) method to read each line of our `class_names.txt` file.\n",
"\n",
"And we can save the class names to a list by stripping the newline value of each of them with a list comprehension and [`strip()`](https://www.w3schools.com/python/ref_string_strip.asp). "
"Just like the FoodVision Mini demo, let's create a script that's capable of instantiating an EffNetB2 feature extractor model along with its necessary transforms."
"We've got a FoodVision Big `model.py` script, now let's create a FoodVision Big `app.py` script.\n",
"\n",
"This will again mostly be the same as the FoodVision Mini `app.py` script except we'll change:\n",
"\n",
"1. **Imports and class names setup** - The `class_names` variable will be a list for all of the Food101 classes rather than pizza, steak, sushi. We can access these via `demos/foodvision_big/class_names.txt`.\n",
"2. **Model and transforms preparation** - The `model` will have `num_classes=101` rather than `num_classes=3`. We'll also be sure to load the weights from `\"09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth\"` (our FoodVision Big model path).\n",
"3. **Predict function** - This will stay the same as FoodVision Mini's `app.py`.\n",
"4. **Gradio app** - The Gradio interface will have different `title`, `description` and `article` parameters to reflect the details of FoodVision Big.\n",
" # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)\n",
" pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}\n",
"description = \"An EfficientNetB2 feature extractor computer vision model to classify images of food into [101 different classes](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt).\"\n",
"We'll use the same process we used for the FoodVision Mini app above in [section 9.1: *Downloading our Foodvision Mini app files*](https://www.learnpytorch.io/09_pytorch_model_deployment/#91-downloading-our-foodvision-mini-app-files)."
"Let's deploy our FoodVision Big Gradio demo to Hugging Face Spaces so we can test it interactively and let others experience the magic of our machine learning efforts!\n",
"\n",
"> **Note:** There are [several ways to upload files to Hugging Face Spaces](https://huggingface.co/docs/hub/repositories-getting-started#getting-started-with-repositories). The following steps treat Hugging Face as a git repository to track files. However, you can also upload directly to Hugging Face Spaces via the [web interface](https://huggingface.co/docs/hub/repositories-getting-started#adding-files-to-a-repository-web-ui) or by the [`huggingface_hub` library](https://huggingface.co/docs/huggingface_hub/index). \n",
"1. [Sign up](https://huggingface.co/join) for a Hugging Face account. \n",
"2. Start a new Hugging Face Space by going to your profile and then [clicking \"New Space\"](https://huggingface.co/new-space).\n",
" * **Note:** A Space in Hugging Face is also known as a \"code repository\" (a place to store your code/files) or \"repo\" for short.\n",
"3. Give the Space a name, for example, mine is called `mrdbourke/foodvision_big`, you can see it here: https://huggingface.co/spaces/mrdbourke/foodvision_big\n",
"4. Select a license (I used [MIT](https://opensource.org/licenses/MIT)).\n",
"5. Select Gradio as the Space SDK (software development kit). \n",
" * **Note:** You can use other options such as Streamlit but since our app is built with Gradio, we'll stick with that.\n",
"8. Clone the repo locally by running: `git clone https://huggingface.co/spaces/[YOUR_USERNAME]/[YOUR_SPACE_NAME]` in terminal or command prompt.\n",
" * **Note:** You can also add files via uploading them under the \"Files and versions\" tab.\n",
"9. Copy/move the contents of the downloaded `foodvision_big` folder to the cloned repo folder.\n",
"10. To upload and track larger files (e.g. files over 10MB or in our case, our PyTorch model file) you'll need to [install Git LFS](https://git-lfs.github.com/) (which stands for \"git large file storage\").\n",
"11. After you've installed Git LFS, you can activate it by running `git lfs install`.\n",
"12. In the `foodvision_big` directory, track the files over 10MB with Git LFS with `git lfs track \"*.file_extension\"`.\n",
" * Track EffNetB2 PyTorch model file with `git lfs track \"09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth\"`.\n",
" * **Note:** If you get any errors uploading images, you may have to track them with `git lfs` too, for example `git lfs track \"examples/04-pizza-dad.jpg\"`\n",
"13. Track `.gitattributes` (automatically created when cloning from HuggingFace, this file will help ensure our larger files are tracked with Git LFS). You can see an example `.gitattributes` file on the [FoodVision Big Hugging Face Space](https://huggingface.co/spaces/mrdbourke/foodvision_big/blob/main/.gitattributes).\n",
" * `git add .gitattributes`\n",
"14. Add the rest of the `foodvision_big` app files and commit them with: \n",
" * `git add *`\n",
" * `git commit -m \"first commit\"`\n",
"15. Push (upload) the files to Hugging Face:\n",
" * `git push`\n",
"16. Wait 3-5 minutes for the build to happen (future builds are faster) and your app to become live!\n",
"You can see my version here: https://huggingface.co/spaces/mrdbourke/foodvision_big/\n",
"\n",
"Or we can even embed our FoodVision Big Gradio demo right within our notebook as an [iframe](https://gradio.app/sharing_your_app/#embedding-with-iframes) with [`IPython.display.IFrame`](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.IFrame) and a link to our space in the format `https://hf.space/embed/[YOUR_USERNAME]/[YOUR_SPACE_NAME]/+`."
"We've come a long way from building PyTorch models to predict a straight line... now we're building computer vision models accessible to people all around the world!"
"* **Deployment is as important as training.** Once you’ve got a good working model, your first question should be: how can I deploy this and make it accessible to others? Deployment allows you to test your model in the real world rather than on private training and test sets.\n",
"* **Three questions for machine learning model deployment:**\n",
" 1. What’s the most ideal use case for the model (how well and how fast does it perform)?\n",
" 2. Where’s the model going to go (is it on-device or on the cloud)?\n",
" 3. How’s the model going to function (are predictions online or offline)?\n",
"* **Deployment options are a plenty.** But best to start simple. One of the best current ways (I say current because these things are always changing) is to use Gradio to create a demo and host it on Hugging Face Spaces. Start simple and scale up when needed.\n",
"* **Never stop experimenting.** Your machine learning model needs will likely change overtime so deploying a single model is not the last step. You might find the dataset changes, so you’ll have to update your model. Or new research gets released and there’s a better architecture to use.\n",
"* **Machine learning model deployment is part of the engineering practice of MLOps (machine learning operations).** MLOps is an extension of DevOps (development operations) and involves all the engineering parts around training a model: data collection and storage, data preprocessing, model deployment, model monitoring, versioning and more. It’s a rapidly evolving field but there are some solid resources out there to learn more, many of which are in [PyTorch Extra Resources](https://www.learnpytorch.io/pytorch_extra_resources/#resources-for-machine-learning-and-deep-learning-engineering)."
"* [Example solutions notebook for 09](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/solutions/09_pytorch_model_deployment_exercise_solutions.ipynb) try the exercises *before* looking at this.\n",
" * See a live [video walkthrough of the solutions on YouTube](https://youtu.be/jOX5ZCkWO-0) (errors and all).\n",
"1. Make and time predictions with both feature extractor models on the test dataset using the GPU (`device=\"cuda\"`). Compare the model's prediction times on GPU vs CPU - does this close the gap between them? As in, does making predictions on the GPU make the ViT feature extractor prediction times closer to the EffNetB2 feature extractor prediction times?\n",
" * You'll find code to do these steps in [section 5. Making predictions with our trained models and timing them](https://www.learnpytorch.io/09_pytorch_model_deployment/#5-making-predictions-with-our-trained-models-and-timing-them) and [section 6. Comparing model results, prediction times and size](https://www.learnpytorch.io/09_pytorch_model_deployment/#6-comparing-model-results-prediction-times-and-size).\n",
"2. The ViT feature extractor seems to have more learning capacity (due to more parameters) than EffNetB2, how does it go on the larger 20% split of the entire Food101 dataset?\n",
" * Train a ViT feature extractor on the 20% Food101 dataset for 5 epochs, just like we did with EffNetB2 in section [10. Creating FoodVision Big](https://www.learnpytorch.io/09_pytorch_model_deployment/#10-creating-foodvision-big).\n",
"7. Pick any dataset from [`torchvision.datasets`](https://pytorch.org/vision/stable/datasets.html) and train a feature extractor model on it using a model from [`torchvision.models`](https://pytorch.org/vision/stable/models.html) (you could use one of the models we've already created, e.g. EffNetB2 or ViT) for 5 epochs and then deploy your model as a Gradio app to Hugging Face Spaces. \n",
" * You may want to pick smaller dataset/make a smaller split of it so training doesn't take too long.\n",
" * I'd love to see your deployed models! So be sure to share them in Discord or on the [course GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions)."
"* Machine learning model deployment is generally an engineering challenge rather than a pure machine learning challenge, see the [PyTorch Extra Resources machine learning engineering section](https://www.learnpytorch.io/pytorch_extra_resources/#resources-for-machine-learning-and-deep-learning-engineering) for resources on learning more.\n",
" * Inside you'll find recommendations for resources such as Chip Huyen's book [*Designing Machine Learning Systems*](https://www.amazon.com/Designing-Machine-Learning-Systems-Production-Ready/dp/1098107969) (especially chapter 7 on model deployment) and Goku Mohandas's [Made with ML MLOps course](https://madewithml.com/#mlops).\n",
"* As you start to build more and more of your own projects, you'll likely start using Git (and potentially GitHub) quite frequently. To learn more about both, I'd recommend the [*Git and GitHub for Beginners - Crash Course*](https://youtu.be/RGOj5yH7evk) video on the freeCodeCamp YouTube channel.\n",
"* We've only scratched the surface with what's possible with Gradio. For more, I'd recommend checking out the [full documentation](https://gradio.app/docs/), especially:\n",
" * All of the different kinds of [input and output components](https://gradio.app/docs/#components).\n",
" * The [Gradio Blocks API](https://gradio.app/docs/#blocks) for more advanced workflows.\n",
" * The Hugging Face Course chapter on [how to use Gradio with Hugging Face](https://huggingface.co/course/chapter9/1).\n",
"* Edge devices aren't limited to mobile phones, they include small computers like the Raspberry Pi and the PyTorch team have a [fantastic blog post tutorial](https://pytorch.org/tutorials/intermediate/realtime_rpi.html) on deploying a PyTorch model to one.\n",
"* For a fantastic guide on developing AI and ML-powered applications, see [Google's People + AI Guidebook](https://pair.withgoogle.com/guidebook). One of my favourites is the section on [setting the right expectations](https://pair.withgoogle.com/guidebook/patterns#set-the-right-expectations).\n",
" * I covered more of these kinds of resources, including guides from Apple, Microsoft and more in the [April 2021 edition of Machine Learning Monthly](https://zerotomastery.io/blog/machine-learning-monthly-april-2021/) (a monthly newsletter I send out with the latest and greatest of the ML field).\n",
"* If you'd like to speed up your model's runtime on CPU, you should be aware of [TorchScript](https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html), [ONNX](https://pytorch.org/docs/stable/onnx.html) (Open Neural Network Exchange) and [OpenVINO](https://docs.openvino.ai/latest/notebooks/102-pytorch-onnx-to-openvino-with-output.html). Going from pure PyTorch to ONNX/OpenVINO models I've seen a ~2x+ increase in performance.\n",
"* For turning models into a deployable and scalable API, see the [TorchServe library](https://pytorch.org/serve/).\n",
"* For a terrific example and rationale as to why deploying a machine learning model in the browser (a form of edge deployment) offers several benefits (no network transfer latency delay), see Jo Kristian Bergum's article on [*Moving ML Inference from the Cloud to the Edge*](https://bergum.medium.com/moving-ml-inference-from-the-cloud-to-the-edge-d6f98dbdb2e3)."