{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving and Loading Models\n",
    "\n",
    "**Author:** [Matthew Inkawhich](https://github.com/MatthewInkawhich)\n",
    "\n",
    "This document provides solutions to a variety of use cases regarding the\n",
    "saving and loading of PyTorch models. Feel free to read the whole\n",
    "document, or just skip to the code you need for a desired use case.\n",
    "\n",
    "When it comes to saving and loading models, there are three core\n",
    "functions to be familiar with:\n",
    "\n",
    "1)  [torch.save](https://pytorch.org/docs/stable/torch.html?highlight=save#torch.save):\n",
    "    Saves a serialized object to disk. This function uses Python's\n",
    "    [pickle](https://docs.python.org/3/library/pickle.html) utility for\n",
    "    serialization. Models, tensors, and dictionaries of all kinds of\n",
    "    objects can be saved using this function.\n",
    "2)  [torch.load](https://pytorch.org/docs/stable/torch.html?highlight=torch%20load#torch.load):\n",
    "    Uses [pickle](https://docs.python.org/3/library/pickle.html)'s\n",
    "    unpickling facilities to deserialize pickled object files to memory.\n",
    "    This function also facilitates the device to load the data into (see\n",
    "    [Saving & Loading Model Across\n",
    "    Devices](#saving-loading-model-across-devices)).\n",
    "3)  [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):\n",
    "    Loads a model's parameter dictionary using a deserialized\n",
    "    *state_dict*. For more information on *state_dict*, see [What is a\n",
    "    state_dict?](#what-is-a-state-dict).\n",
    "\n",
    "**Contents:**\n",
    "\n",
    "-   [What is a state_dict?](#what-is-a-state-dict)\n",
    "-   [Saving & Loading Model for\n",
    "    Inference](#saving-loading-model-for-inference)\n",
    "-   [Saving & Loading a General\n",
    "    Checkpoint](#saving-loading-a-general-checkpoint-for-inference-and-or-resuming-training)\n",
    "-   [Saving Multiple Models in One\n",
    "    File](#saving-multiple-models-in-one-file)\n",
    "-   [Warmstarting Model Using Parameters from a Different\n",
    "    Model](#warmstarting-model-using-parameters-from-a-different-model)\n",
    "-   [Saving & Loading Model Across\n",
    "    Devices](#saving-loading-model-across-devices)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# What is a `state_dict`?\n",
    "\n",
    "In PyTorch, the learnable parameters (i.e. weights and biases) of an\n",
    "`torch.nn.Module` model are contained in the model's *parameters*\n",
    "(accessed with `model.parameters()`). A *state_dict* is simply a Python\n",
    "dictionary object that maps each layer to its parameter tensor. Note\n",
    "that only layers with learnable parameters (convolutional layers, linear\n",
    "layers, etc.) and registered buffers (batchnorm\\'s running_mean) have\n",
    "entries in the model's *state_dict*. Optimizer objects (`torch.optim`)\n",
    "also have a *state_dict*, which contains information about the\n",
    "optimizer\\'s state, as well as the hyperparameters used.\n",
    "\n",
    "Because *state_dict* objects are Python dictionaries, they can be easily\n",
    "saved, updated, altered, and restored, adding a great deal of modularity\n",
    "to PyTorch models and optimizers.\n",
    "\n",
    "## Example:\n",
    "\n",
    "Let's take a look at the *state_dict* from the simple model used in the\n",
    "[Training a\n",
    "classifier](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py)\n",
    "tutorial.\n",
    "\n",
    "``` python\n",
    "# Define model\n",
    "class TheModelClass(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(TheModelClass, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(3, 6, 5)\n",
    "        self.pool = nn.MaxPool2d(2, 2)\n",
    "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
    "        self.fc2 = nn.Linear(120, 84)\n",
    "        self.fc3 = nn.Linear(84, 10)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.pool(F.relu(self.conv1(x)))\n",
    "        x = self.pool(F.relu(self.conv2(x)))\n",
    "        x = x.view(-1, 16 * 5 * 5)\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "\n",
    "# Initialize model\n",
    "model = TheModelClass()\n",
    "\n",
    "# Initialize optimizer\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n",
    "\n",
    "# Print model's state_dict\n",
    "print(\"Model's state_dict:\")\n",
    "for param_tensor in model.state_dict():\n",
    "    print(param_tensor, \"\\t\", model.state_dict()[param_tensor].size())\n",
    "\n",
    "# Print optimizer's state_dict\n",
    "print(\"Optimizer's state_dict:\")\n",
    "for var_name in optimizer.state_dict():\n",
    "    print(var_name, \"\\t\", optimizer.state_dict()[var_name])\n",
    "```\n",
    "\n",
    "**Output:**\n",
    "\n",
    "``` sh\n",
    "Model's state_dict:\n",
    "conv1.weight     torch.Size([6, 3, 5, 5])\n",
    "conv1.bias   torch.Size([6])\n",
    "conv2.weight     torch.Size([16, 6, 5, 5])\n",
    "conv2.bias   torch.Size([16])\n",
    "fc1.weight   torch.Size([120, 400])\n",
    "fc1.bias     torch.Size([120])\n",
    "fc2.weight   torch.Size([84, 120])\n",
    "fc2.bias     torch.Size([84])\n",
    "fc3.weight   torch.Size([10, 84])\n",
    "fc3.bias     torch.Size([10])\n",
    "\n",
    "Optimizer's state_dict:\n",
    "state    {}\n",
    "param_groups     [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [4675713712, 4675713784, 4675714000, 4675714072, 4675714216, 4675714288, 4675714432, 4675714504, 4675714648, 4675714720]}]\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving & Loading Model for Inference\n",
    "\n",
    "## Save/Load `state_dict` (Recommended)\n",
    "\n",
    "**Save:**\n",
    "\n",
    "``` python\n",
    "torch.save(model.state_dict(), PATH)\n",
    "```\n",
    "\n",
    "**Load:**\n",
    "\n",
    "``` python\n",
    "model = TheModelClass(*args, **kwargs)\n",
    "model.load_state_dict(torch.load(PATH, weights_only=True))\n",
    "model.eval()\n",
    "```\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>The 1.6 release of PyTorch switched <code>torch.save</code> to use a newzip file-based format. <code>torch.load</code> still retains the ability toload files in the old format. If for any reason you want <code>torch.save</code>to use the old format, pass the <code>kwarg</code> parameter <code>_use_new_zipfile_serialization=False</code>.</p>\n",
    "\n",
    "</div>\n",
    "\n",
    "When saving a model for inference, it is only necessary to save the\n",
    "trained model's learned parameters. Saving the model's *state_dict* with\n",
    "the `torch.save()` function will give you the most flexibility for\n",
    "restoring the model later, which is why it is the recommended method for\n",
    "saving models.\n",
    "\n",
    "A common PyTorch convention is to save models using either a `.pt` or\n",
    "`.pth` file extension.\n",
    "\n",
    "Remember that you must call `model.eval()` to set dropout and batch\n",
    "normalization layers to evaluation mode before running inference.\n",
    "Failing to do this will yield inconsistent inference results.\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>Notice that the <code>load_state_dict()</code> function takes a dictionaryobject, NOT a path to a saved object. This means that you mustdeserialize the saved  before you pass it to the<code>load_state_dict()</code> function. For example, you CANNOT load using<code>model.load_state_dict(PATH)</code>.</p>\n",
    "\n",
    "</div>\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>If you only plan to keep the best performing model (according to theacquired validation loss), don't forget that <code>best_model_state = model.state_dict()</code>returns a reference to the state and not its copy! You must serialize<code>best_model_state</code> or use <code>best_model_state = deepcopy(model.state_dict())</code> otherwiseyour best <code>best_model_state</code> will keep getting updated by the subsequent trainingiterations. As a result, the final model state will be the state of the overfitted model.</p>\n",
    "\n",
    "</div>\n",
    "\n",
    "## Save/Load Entire Model\n",
    "\n",
    "**Save:**\n",
    "\n",
    "``` python\n",
    "torch.save(model, PATH)\n",
    "```\n",
    "\n",
    "**Load:**\n",
    "\n",
    "``` python\n",
    "# Model class must be defined somewhere\n",
    "model = torch.load(PATH, weights_only=False)\n",
    "model.eval()\n",
    "```\n",
    "\n",
    "This save/load process uses the most intuitive syntax and involves the\n",
    "least amount of code. Saving a model in this way will save the entire\n",
    "module using Python's\n",
    "[pickle](https://docs.python.org/3/library/pickle.html) module. The\n",
    "disadvantage of this approach is that the serialized data is bound to\n",
    "the specific classes and the exact directory structure used when the\n",
    "model is saved. The reason for this is because pickle does not save the\n",
    "model class itself. Rather, it saves a path to the file containing the\n",
    "class, which is used during load time. Because of this, your code can\n",
    "break in various ways when used in other projects or after refactors.\n",
    "\n",
    "A common PyTorch convention is to save models using either a `.pt` or\n",
    "`.pth` file extension.\n",
    "\n",
    "Remember that you must call `model.eval()` to set dropout and batch\n",
    "normalization layers to evaluation mode before running inference.\n",
    "Failing to do this will yield inconsistent inference results.\n",
    "\n",
    "### Saving an Exported Program\n",
    "\n",
    "If you are using `torch.export`, you can save and load your\n",
    "`ExportedProgram` using the `torch.export.save()` and\n",
    "`torch.export.load()` APIs. with the `.pt2` file extension:\n",
    "\n",
    "``` python\n",
    "class SimpleModel(torch.nn.Module):\n",
    "     def forward(self, x):\n",
    "         return x + 10\n",
    "\n",
    "# Create a sample input\n",
    "sample_input = torch.randn(5)\n",
    "\n",
    "# Export the model\n",
    "exported_program = torch.export.export(SimpleModel(), sample_input)\n",
    "\n",
    "# Save the exported program\n",
    "torch.export.save(exported_program, 'exported_program.pt2')\n",
    "\n",
    "# Load the exported program\n",
    "saved_exported_program = torch.export.load('exported_program.pt2')\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving & Loading a General Checkpoint for Inference and/or Resuming Training\n",
    "\n",
    "## Save:\n",
    "\n",
    "``` python\n",
    "torch.save({\n",
    "            'epoch': epoch,\n",
    "            'model_state_dict': model.state_dict(),\n",
    "            'optimizer_state_dict': optimizer.state_dict(),\n",
    "            'loss': loss,\n",
    "            ...\n",
    "            }, PATH)\n",
    "```\n",
    "\n",
    "## Load:\n",
    "\n",
    "``` python\n",
    "model = TheModelClass(*args, **kwargs)\n",
    "optimizer = TheOptimizerClass(*args, **kwargs)\n",
    "\n",
    "checkpoint = torch.load(PATH, weights_only=True)\n",
    "model.load_state_dict(checkpoint['model_state_dict'])\n",
    "optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
    "epoch = checkpoint['epoch']\n",
    "loss = checkpoint['loss']\n",
    "\n",
    "model.eval()\n",
    "# - or -\n",
    "model.train()\n",
    "```\n",
    "\n",
    "When saving a general checkpoint, to be used for either inference or\n",
    "resuming training, you must save more than just the model's\n",
    "*state_dict*. It is important to also save the optimizer\\'s\n",
    "*state_dict*, as this contains buffers and parameters that are updated\n",
    "as the model trains. Other items that you may want to save are the epoch\n",
    "you left off on, the latest recorded training loss, external\n",
    "`torch.nn.Embedding` layers, etc. As a result, such a checkpoint is\n",
    "often 2\\~3 times larger than the model alone.\n",
    "\n",
    "To save multiple components, organize them in a dictionary and use\n",
    "`torch.save()` to serialize the dictionary. A common PyTorch convention\n",
    "is to save these checkpoints using the `.tar` file extension.\n",
    "\n",
    "To load the items, first initialize the model and optimizer, then load\n",
    "the dictionary locally using `torch.load()`. From here, you can easily\n",
    "access the saved items by simply querying the dictionary as you would\n",
    "expect.\n",
    "\n",
    "Remember that you must call `model.eval()` to set dropout and batch\n",
    "normalization layers to evaluation mode before running inference.\n",
    "Failing to do this will yield inconsistent inference results. If you\n",
    "wish to resuming training, call `model.train()` to ensure these layers\n",
    "are in training mode.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving Multiple Models in One File\n",
    "\n",
    "## Save:\n",
    "\n",
    "``` python\n",
    "torch.save({\n",
    "            'modelA_state_dict': modelA.state_dict(),\n",
    "            'modelB_state_dict': modelB.state_dict(),\n",
    "            'optimizerA_state_dict': optimizerA.state_dict(),\n",
    "            'optimizerB_state_dict': optimizerB.state_dict(),\n",
    "            ...\n",
    "            }, PATH)\n",
    "```\n",
    "\n",
    "## Load:\n",
    "\n",
    "``` python\n",
    "modelA = TheModelAClass(*args, **kwargs)\n",
    "modelB = TheModelBClass(*args, **kwargs)\n",
    "optimizerA = TheOptimizerAClass(*args, **kwargs)\n",
    "optimizerB = TheOptimizerBClass(*args, **kwargs)\n",
    "\n",
    "checkpoint = torch.load(PATH, weights_only=True)\n",
    "modelA.load_state_dict(checkpoint['modelA_state_dict'])\n",
    "modelB.load_state_dict(checkpoint['modelB_state_dict'])\n",
    "optimizerA.load_state_dict(checkpoint['optimizerA_state_dict'])\n",
    "optimizerB.load_state_dict(checkpoint['optimizerB_state_dict'])\n",
    "\n",
    "modelA.eval()\n",
    "modelB.eval()\n",
    "# - or -\n",
    "modelA.train()\n",
    "modelB.train()\n",
    "```\n",
    "\n",
    "When saving a model comprised of multiple `torch.nn.Modules`, such as a\n",
    "GAN, a sequence-to-sequence model, or an ensemble of models, you follow\n",
    "the same approach as when you are saving a general checkpoint. In other\n",
    "words, save a dictionary of each model's *state_dict* and corresponding\n",
    "optimizer. As mentioned before, you can save any other items that may\n",
    "aid you in resuming training by simply appending them to the dictionary.\n",
    "\n",
    "A common PyTorch convention is to save these checkpoints using the\n",
    "`.tar` file extension.\n",
    "\n",
    "To load the models, first initialize the models and optimizers, then\n",
    "load the dictionary locally using `torch.load()`. From here, you can\n",
    "easily access the saved items by simply querying the dictionary as you\n",
    "would expect.\n",
    "\n",
    "Remember that you must call `model.eval()` to set dropout and batch\n",
    "normalization layers to evaluation mode before running inference.\n",
    "Failing to do this will yield inconsistent inference results. If you\n",
    "wish to resuming training, call `model.train()` to set these layers to\n",
    "training mode.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Warmstarting Model Using Parameters from a Different Model\n",
    "\n",
    "## Save:\n",
    "\n",
    "``` python\n",
    "torch.save(modelA.state_dict(), PATH)\n",
    "```\n",
    "\n",
    "## Load:\n",
    "\n",
    "``` python\n",
    "modelB = TheModelBClass(*args, **kwargs)\n",
    "modelB.load_state_dict(torch.load(PATH, weights_only=True), strict=False)\n",
    "```\n",
    "\n",
    "Partially loading a model or loading a partial model are common\n",
    "scenarios when transfer learning or training a new complex model.\n",
    "Leveraging trained parameters, even if only a few are usable, will help\n",
    "to warmstart the training process and hopefully help your model converge\n",
    "much faster than training from scratch.\n",
    "\n",
    "Whether you are loading from a partial *state_dict*, which is missing\n",
    "some keys, or loading a *state_dict* with more keys than the model that\n",
    "you are loading into, you can set the `strict` argument to **False** in\n",
    "the `load_state_dict()` function to ignore non-matching keys.\n",
    "\n",
    "If you want to load parameters from one layer to another, but some keys\n",
    "do not match, simply change the name of the parameter keys in the\n",
    "*state_dict* that you are loading to match the keys in the model that\n",
    "you are loading into.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving & Loading Model Across Devices\n",
    "\n",
    "## Save on GPU, Load on CPU\n",
    "\n",
    "**Save:**\n",
    "\n",
    "``` python\n",
    "torch.save(model.state_dict(), PATH)\n",
    "```\n",
    "\n",
    "**Load:**\n",
    "\n",
    "``` python\n",
    "device = torch.device('cpu')\n",
    "model = TheModelClass(*args, **kwargs)\n",
    "model.load_state_dict(torch.load(PATH, map_location=device, weights_only=True))\n",
    "```\n",
    "\n",
    "When loading a model on a CPU that was trained with a GPU, pass\n",
    "`torch.device('cpu')` to the `map_location` argument in the\n",
    "`torch.load()` function. In this case, the storages underlying the\n",
    "tensors are dynamically remapped to the CPU device using the\n",
    "`map_location` argument.\n",
    "\n",
    "## Save on GPU, Load on GPU\n",
    "\n",
    "**Save:**\n",
    "\n",
    "``` python\n",
    "torch.save(model.state_dict(), PATH)\n",
    "```\n",
    "\n",
    "**Load:**\n",
    "\n",
    "``` python\n",
    "device = torch.device(\"cuda\")\n",
    "model = TheModelClass(*args, **kwargs)\n",
    "model.load_state_dict(torch.load(PATH, weights_only=True))\n",
    "model.to(device)\n",
    "# Make sure to call input = input.to(device) on any input tensors that you feed to the model\n",
    "```\n",
    "\n",
    "When loading a model on a GPU that was trained and saved on GPU, simply\n",
    "convert the initialized `model` to a CUDA optimized model using\n",
    "`model.to(torch.device('cuda'))`. Also, be sure to use the\n",
    "`.to(torch.device('cuda'))` function on all model inputs to prepare the\n",
    "data for the model. Note that calling `my_tensor.to(device)` returns a\n",
    "new copy of `my_tensor` on GPU. It does NOT overwrite `my_tensor`.\n",
    "Therefore, remember to manually overwrite tensors:\n",
    "`my_tensor = my_tensor.to(torch.device('cuda'))`.\n",
    "\n",
    "## Save on CPU, Load on GPU\n",
    "\n",
    "**Save:**\n",
    "\n",
    "``` python\n",
    "torch.save(model.state_dict(), PATH)\n",
    "```\n",
    "\n",
    "**Load:**\n",
    "\n",
    "``` python\n",
    "device = torch.device(\"cuda\")\n",
    "model = TheModelClass(*args, **kwargs)\n",
    "model.load_state_dict(torch.load(PATH, weights_only=True, map_location=\"cuda:0\"))  # Choose whatever GPU device number you want\n",
    "model.to(device)\n",
    "# Make sure to call input = input.to(device) on any input tensors that you feed to the model\n",
    "```\n",
    "\n",
    "When loading a model on a GPU that was trained and saved on CPU, set the\n",
    "`map_location` argument in the `torch.load()` function to\n",
    "`cuda:device_id`. This loads the model to a given GPU device. Next, be\n",
    "sure to call `model.to(torch.device('cuda'))` to convert the model's\n",
    "parameter tensors to CUDA tensors. Finally, be sure to use the\n",
    "`.to(torch.device('cuda'))` function on all model inputs to prepare the\n",
    "data for the CUDA optimized model. Note that calling\n",
    "`my_tensor.to(device)` returns a new copy of `my_tensor` on GPU. It does\n",
    "NOT overwrite `my_tensor`. Therefore, remember to manually overwrite\n",
    "tensors: `my_tensor = my_tensor.to(torch.device('cuda'))`.\n",
    "\n",
    "## Saving `torch.nn.DataParallel` Models\n",
    "\n",
    "**Save:**\n",
    "\n",
    "``` python\n",
    "torch.save(model.module.state_dict(), PATH)\n",
    "```\n",
    "\n",
    "**Load:**\n",
    "\n",
    "``` python\n",
    "# Load to whatever device you want\n",
    "```\n",
    "\n",
    "`torch.nn.DataParallel` is a model wrapper that enables parallel GPU\n",
    "utilization. To save a `DataParallel` model generically, save the\n",
    "`model.module.state_dict()`. This way, you have the flexibility to load\n",
    "the model any way you want to any device you want.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
