add more annotations

This commit is contained in:
Daniel Bourke committed 2022-01-26 13:04:19 +10:00
1 parent 5281017eaa
commit b803fc3e28
1 file changed
+138 -65
+138 -65
View File
@@ -1158,14 +1158,22 @@
"source": [
"## TK 5. Saving and loading a PyTorch model\n",
"\n",
"UPTOHERE: reading the article on saving and loading models in PyTorch\n",
"If you've trained a PyTorch model, chances are you'll want to save it and export it somewhere.\n",
"\n",
"See here for more: https://pytorch.org/tutorials/beginner/saving_loading_models.html\n",
"As in, you might train it on Google Colab or your local machine with a GPU but you'd like to now export it to some sort of application where others can use it. \n",
"\n",
"Or maybe you'd like to save your progress on a model and come back and load it back later.\n",
"\n",
"For saving and loading models in PyTorch, there are three main methods you should be aware of (all of below have been taken from the [PyTorch saving and loading models guide](https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference)):\n",
"\n",
"| PyTorch method | What does it do? | \n",
"| ----- | ----- |\n",
"| [`torch.save`](https://pytorch.org/docs/stable/torch.html?highlight=save#torch.save) | Saves a serialzed object to disk using Python's [`pickle`](https://docs.python.org/3/library/pickle.html) utility. Models, tensors and various other Python objects like dictionaries can be saved using `torch.save`. | \n",
"| [`torch.load`](https://pytorch.org/docs/stable/torch.html?highlight=torch%20load#torch.load) | Uses `pickle`'s unpickling features to deserialize and load pickled Python object files (like models, tensors or dictionaries) into memory. You can also set which device to load the object to (CPU, GPU etc). |\n",
"| [`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)| Loads a model's parameter dictionary (`model.state_dict()`) using a saved `state_dict()` object. | \n",
"\n",
"> **Note:** As stated in [Python's `pickle` documentation](https://docs.python.org/3/library/pickle.html), the `pickle` module **is not secure**. That means you should only ever unpickle (load) data you trust. That goes for loading PyTorch models as well. Only ever use saved PyTorch models from sources you trust.\n",
"\n",
"* 3 core functions to be aware of when saving and loading models in PyTorch:\n",
" 1. torch.save - Saves a serialized object to disk. This function uses Python's pickle utility for serialization. Models, tensors and dictionaries of all kinds of objects can be saved using this function.\n",
" 2. torch.load - Uses pickle's unpickling facilities to deserialize pickled object files to memory. This function also facilitates the device to load the data into (if you're using a different device you might want to use a different way of saving things).\n",
" 3. torch.nn.Module.load_state_dict: Loads a model's parameter dictionary using a deserialized `state_dict`.\n",
"\n",
"* TK - `path_to_my_model.pth`, it's common to use `.pt` or `.pth` as a file extension when saving PyTorch models.\n"
]
@@ -1176,26 +1184,17 @@
"id": "SdAGcH2aec05"
},
"source": [
"### Save model\n",
"### Saving a PyTorch model's `state_dict()`\n",
"\n",
"TK - can update this to be something like:\n",
"The [recommended way](https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference) for saving and loading a model for inference (making preditions) is by saving and loading a model's `state_dict()`.\n",
"\n",
"```python\n",
"from pathlib import Path\n",
"import requests\n",
"Let's see how we can do that in a few steps:\n",
"\n",
"DATA_PATH = Path(\"data\")\n",
"PATH = DATA_PATH / \"mnist\"\n",
"1. We'll create a directory for saving models to called `models` using Python's `pathlib` module.\n",
"2. We'll create a file path to save the model to.\n",
"3. We'll call `torch.save(obj, f)` where `obj` is the target model's `state_dict()` and `f` is the filename of where to save the model.\n",
"\n",
"PATH.mkdir(parents=True, exist_ok=True)\n",
"\n",
"URL = \"https://github.com/pytorch/tutorials/raw/master/_static/\"\n",
"FILENAME = \"mnist.pkl.gz\"\n",
"\n",
"if not (PATH / FILENAME).exists():\n",
" content = requests.get(URL + FILENAME).content\n",
" (PATH / FILENAME).open(\"wb\").write(content)\n",
"```"
"> **Note:** It's common convention for PyTorch saved models or objects to end with `.pt` or `.pth`, like `saved_model_01.pth`.\n"
]
},
{
@@ -1203,26 +1202,27 @@
"source": [
"from pathlib import Path\n",
"\n",
"# Create models directory \n",
"# 1. Create models directory \n",
"MODEL_PATH = Path(\"models\")\n",
"MODEL_PATH.mkdir(parents=True, exist_ok=True)\n",
"\n",
"# Create model save path \n",
"# 2. Create model save path \n",
"MODEL_NAME = \"01_pytorch_workflow_model_0.pth\"\n",
"MODEL_SAVE_PATH = MODEL_PATH / MODEL_NAME\n",
"print(f\"Saving model to: {MODEL_SAVE_PATH}\")\n",
"\n",
"# Save the model state dict \n",
"torch.save(model_0.state_dict(), MODEL_SAVE_PATH)"
"# 3. Save the model state dict \n",
"print(f\"Saving model to: {MODEL_SAVE_PATH}\")\n",
"torch.save(obj=model_0.state_dict(), # only saving the state_dict() only saves the models learned parameters\n",
" f=MODEL_SAVE_PATH) "
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "qsQhY2S2jv90",
"outputId": "bdc358d2-5310-4667-ee10-1d1c6419dd91"
"outputId": "75c1e5f7-2b19-4d41-d741-ee5012a42c2d"
},
"execution_count": 131,
"execution_count": 137,
"outputs": [
{
"output_type": "stream",
@@ -1235,36 +1235,25 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x4lsdllLec05"
},
"outputs": [],
"source": [
"# Save to file\n",
"import os\n",
"os.makedirs(\"models\", exist_ok=True)\n",
"save_path = \"models/01_pytorch_workflow_model_0.pth\"\n",
"torch.save(model_0.state_dict(), save_path) # only saving the state_dict() only saves the models learned parameters"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 138,
"metadata": {
"id": "mpQc45zwec06",
"outputId": "d1f5dcb1-11b3-4d7f-8a85-30aff74459b2"
"outputId": "7463ed04-cba6-481a-ed20-596cf7c4cfac",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"name": "stdout",
"text": [
"-rw-rw-r-- 1 daniel daniel 1063 Oct 26 12:47 models/01_pytorch_workflow_model_0.pth\n"
"-rw-r--r-- 1 root root 1063 Jan 26 02:27 models/01_pytorch_workflow_model_0.pth\n"
]
}
],
"source": [
"# Check the saved file path\n",
"!ls -l models/01_pytorch_workflow_model_0.pth"
]
},
@@ -1274,57 +1263,120 @@
"id": "jFQpRoH5ec06"
},
"source": [
"### Load model"
"### Loading a saved PyTorch model's `state_dict()`\n",
"\n",
"Since we've now got a saved model `state_dict()` at `models/01_pytorch_workflow_model_0.pth` we can now load it in using `torch.nn.Module.load_state_dict(torch.load(f))` where `f` is the filepath of our saved model `state_dict()`.\n",
"\n",
"Why call `torch.load()` inside `torch.nn.Module.load_state_dict()`? \n",
"\n",
"Because we only saved the model's `state_dict()` which is a dictionary of learned parameters and not the *entire* model, we first have to load the `state_dict()` with `torch.load()` and then pass that `state_dict()` to a new instance of our model (which is a subclass of `nn.Module`).\n",
"\n",
"Why not save the entire model?\n",
"\n",
"[Saving the entire model](https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-load-entire-model) rather than just the `state_dict()` is more intuitive, however, to quote the PyTorch documentation (italics mine):\n",
"\n",
"> The disadvantage of this approach *(saving the whole model)* is that the serialized data is bound to the specific classes and the exact directory structure used when the model is saved...\n",
">\n",
"> Because of this, your code can break in various ways when used in other projects or after refactors.\n",
"\n",
"So instead, we're using the flexible method of saving and loading just the `state_dict()`, which again is basically a dictionary of model parameters.\n",
"\n",
"Let's test it out by created another instance of `LinearRegressionModel()`, which is a subclass of `torch.nn.Module` and will hence have the in-built method `load_state_dit()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 139,
"metadata": {
"id": "1xnh3cFDec06",
"outputId": "f7033474-cceb-4521-9292-d0f031e90e5f"
"outputId": "4efbdbb8-18c6-48c7-b14a-9f4f5a2afa3e",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<All keys matched successfully>"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
"execution_count": 139
}
],
"source": [
"# Instantiate model\n",
"# Instantiate a new instance of our model (this will be instantiated with random weights)\n",
"loaded_model_0 = LinearRegressionModel()\n",
"loaded_model_0.load_state_dict(torch.load(save_path))"
"\n",
"# Load the state_dict of our saved model (this will update the new instance of our model with trained weights)\n",
"loaded_model_0.load_state_dict(torch.load(f=MODEL_SAVE_PATH))"
]
},
{
"cell_type": "markdown",
"source": [
"Excellent! It looks like things matched up.\n",
"\n",
"Now to test our loaded model, let's perform inference with it (make predictions) on the test data.\n",
"\n",
"Remember the rules for performing inference with PyTorch models?\n",
"\n",
"If not, here's a refresher:\n",
"\n",
"<details>\n",
" <summary>PyTorch inference rules</summary>\n",
" <ol>\n",
" <li> Set the model in evaluation mode (<code>model.eval()</code>). </li>\n",
" <li> Make the predictions using the inference mode context manager (<code>with torch.inference_mode(): ...</code>). </li>\n",
" <li> All predictions should be made with objects on the same device (e.g. data and model on GPU only or data and model on CPU only).</li>\n",
" </ol> \n",
"</details>\n",
"\n"
],
"metadata": {
"id": "vK8PRtY7Qgpz"
}
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 140,
"metadata": {
"id": "Ps-AuJqkec06"
},
"outputs": [],
"source": [
"# Evaluate loaded model\n",
"# 1. Put the loaded model into evaluation mode\n",
"loaded_model_0.eval()\n",
"\n",
"# 2. Use the inference mode context manager to make predictions\n",
"with torch.inference_mode():\n",
" loaded_model_preds = loaded_model_0(X_test)"
" loaded_model_preds = loaded_model_0(X_test) # perform a forward pass on the test data with the loaded model"
]
},
{
"cell_type": "markdown",
"source": [
"Now we've made some predictions with the loaded model, let's see if they're the same as the previous predictions."
],
"metadata": {
"id": "e81XpN8WSSqn"
}
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 141,
"metadata": {
"id": "il9gqj6Nec06",
"outputId": "0c72259c-41f0-4b8b-c134-9ab9e0d72ee7"
"outputId": "a4c6053a-eee8-47f0-d312-31fe0814b506",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"tensor([[True],\n",
@@ -1339,15 +1391,28 @@
" [True]])"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
"execution_count": 141
}
],
"source": [
"# Compare previous model predictions with loaded model predictions (these should be the same)\n",
"y_preds == loaded_model_preds"
]
},
{
"cell_type": "markdown",
"source": [
"Nice! \n",
"\n",
"It looks like the loaded model predictions are the same as the previous model predictions (predictions made prior to saving). This indicates our model is saving and loading as expected.\n",
"\n",
"> **Note:** There are more methods to save and load PyTorch models but I'll leave these for extra-curriculum and further reading. See the [PyTorch guide for saving and loading models](https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-and-loading-models) for more. "
],
"metadata": {
"id": "9Y4ZcxxfNcVu"
}
},
{
"cell_type": "markdown",
"metadata": {
@@ -1356,6 +1421,11 @@
"source": [
"## TK - 6. Putting it all together \n",
"\n",
"UPTOHERE: we've covered a fair bit of ground so far... but once you've had some practice, you'll be performing the above steps like the back of your hand.\n",
"\n",
"* TK - speaking of practice... let's put everything we've done so far together, except this time we'll make our code device agnostic (so if there's a GPU available, it'll use it and if not, it will default to the CPU)\n",
"* TK - the entire script should be able to run from below this point (e.g. import all the things necessary...)\n",
"\n",
"TODO:\n",
"* replicate the above but running on GPU (create data etc)\n",
"* device agnostic code (put model on GPU + data on GPU)\n",
@@ -1938,11 +2008,13 @@
},
"source": [
"## Exercises\n",
"* Read \"What is nn.module, really?\" https://pytorch.org/tutorials/beginner/nn_tutorial.html\n",
"* Read/watch up on gradient descent - https://en.wikipedia.org/wiki/Gradient_descent + https://towardsdatascience.com/gradient-descent-algorithm-a-deep-dive-cf04e8115f21 \n",
"\n",
"\n",
"\n",
"## Extra-curriculum\n",
"* https://pytorch.org/tutorials/beginner/saving_loading_models.html"
"* Read \"What is nn.module, really?\" https://pytorch.org/tutorials/beginner/nn_tutorial.html\n",
"* Read/watch up on gradient descent - https://en.wikipedia.org/wiki/Gradient_descent + https://towardsdatascience.com/gradient-descent-algorithm-a-deep-dive-cf04e8115f21\n",
"* Spend 10-minutes reading the loading and saving documentation on PyTorch website - https://pytorch.org/tutorials/beginner/saving_loading_models.html"
]
}
],
@@ -1971,6 +2043,7 @@
"name": "01_pytorch_workflow.ipynb",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true,
"include_colab_link": true
}
},