blob: ff7e8acdeba01ee976346f28539a8119a4917cbc [file] [log] [blame]
{
"cells": [
{
"cell_type": "markdown",
"id": "99350a11",
"metadata": {},
"source": [
"<!--- Licensed to the Apache Software Foundation (ASF) under one -->\n",
"<!--- or more contributor license agreements. See the NOTICE file -->\n",
"<!--- distributed with this work for additional information -->\n",
"<!--- regarding copyright ownership. The ASF licenses this file -->\n",
"<!--- to you under the Apache License, Version 2.0 (the -->\n",
"<!--- \"License\"); you may not use this file except in compliance -->\n",
"<!--- with the License. You may obtain a copy of the License at -->\n",
"\n",
"<!--- http://www.apache.org/licenses/LICENSE-2.0 -->\n",
"\n",
"<!--- Unless required by applicable law or agreed to in writing, -->\n",
"<!--- software distributed under the License is distributed on an -->\n",
"<!--- \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->\n",
"<!--- KIND, either express or implied. See the License for the -->\n",
"<!--- specific language governing permissions and limitations -->\n",
"<!--- under the License. -->\n",
"\n",
"# Saving and Loading Gluon Models\n",
"\n",
"Training large models take a lot of time and it is a good idea to save the trained models to files to avoid training them again and again. There are a number of reasons to do this. For example, you might want to do inference on a machine that is different from the one where the model was trained. Sometimes model's performance on validation set decreases towards the end of the training because of overfitting. If you saved your model parameters after every epoch, at the end you can decide to use the model that performs best on the validation set. Another reason would be to train your model using one language (like Python that has a lot of tools for training) and run inference using a different language (like Scala probably because your application is built on Scala).\n",
"\n",
"In this tutorial, we will learn ways to save and load Gluon models. There are two ways to save/load Gluon models:\n",
"\n",
"**1. Save/load model parameters only**\n",
"\n",
"Parameters of any Gluon model can be saved using the `save_parameters` and `load_parameters` method. This does not save model architecture. This method is used to save parameters of dynamic (non-hybrid) models. Model architecture cannot be saved for dynamic models because model architecture changes during execution.\n",
"\n",
"**2. Save/load model parameters AND architecture**\n",
"\n",
"The Model architecture of `Hybrid` models stays static and don't change during execution. Therefore both model parameters AND architecture can be saved and loaded using `export`, `imports` methods.\n",
"\n",
"Let's look at the above methods in more detail. Let's start by importing the modules we'll need."
]
},
{
"cell_type": "markdown",
"id": "87527eeb",
"metadata": {},
"source": [
"```python\n",
"from __future__ import print_function\n",
"\n",
"import mxnet as mx\n",
"import mxnet.ndarray as nd\n",
"from mxnet import nd, autograd, gluon\n",
"from mxnet.gluon.data.vision import transforms\n",
"\n",
"import numpy as np\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "041ee6b7",
"metadata": {},
"source": [
"## Setup: build and train a simple model\n",
"\n",
"We need a trained model before we can save it to a file. So let's go ahead and build a very simple convolutional network and train it on MNIST data.\n",
"\n",
"Let's define a helper function to build a LeNet model and another helper to train LeNet with MNIST."
]
},
{
"cell_type": "markdown",
"id": "c5f8a4b9",
"metadata": {},
"source": [
"```python\n",
"# Use GPU if one exists, else use CPU\n",
"ctx = mx.gpu() if mx.context.num_gpus() else mx.cpu()\n",
"\n",
"# MNIST images are 28x28. Total pixels in input layer is 28x28 = 784\n",
"num_inputs = 784\n",
"# Clasify the images into one of the 10 digits\n",
"num_outputs = 10\n",
"# 64 images in a batch\n",
"batch_size = 64\n",
"\n",
"# Load the training data\n",
"train_data = gluon.data.DataLoader(gluon.data.vision.MNIST(train=True).transform_first(transforms.ToTensor()),\n",
" batch_size, shuffle=True)\n",
"\n",
"# Build a simple convolutional network\n",
"def build_lenet(net): \n",
" with net.name_scope():\n",
" # First convolution\n",
" net.add(gluon.nn.Conv2D(channels=20, kernel_size=5, activation='relu'))\n",
" net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n",
" # Second convolution\n",
" net.add(gluon.nn.Conv2D(channels=50, kernel_size=5, activation='relu'))\n",
" net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n",
" # Flatten the output before the fully connected layers\n",
" net.add(gluon.nn.Flatten())\n",
" # First fully connected layers with 512 neurons\n",
" net.add(gluon.nn.Dense(512, activation=\"relu\"))\n",
" # Second fully connected layer with as many neurons as the number of classes\n",
" net.add(gluon.nn.Dense(num_outputs))\n",
"\n",
" return net\n",
"\n",
"# Train a given model using MNIST data\n",
"def train_model(model):\n",
" # Initialize the parameters with Xavier initializer\n",
" model.collect_params().initialize(mx.init.Xavier(), ctx=ctx)\n",
" # Use cross entropy loss\n",
" softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()\n",
" # Use Adam optimizer\n",
" trainer = gluon.Trainer(model.collect_params(), 'adam', {'learning_rate': .001})\n",
"\n",
" # Train for one epoch\n",
" for epoch in range(1):\n",
" # Iterate through the images and labels in the training data\n",
" for batch_num, (data, label) in enumerate(train_data):\n",
" # get the images and labels\n",
" data = data.as_in_context(ctx)\n",
" label = label.as_in_context(ctx)\n",
" # Ask autograd to record the forward pass\n",
" with autograd.record():\n",
" # Run the forward pass\n",
" output = model(data)\n",
" # Compute the loss\n",
" loss = softmax_cross_entropy(output, label)\n",
" # Compute gradients\n",
" loss.backward()\n",
" # Update parameters\n",
" trainer.step(data.shape[0])\n",
"\n",
" # Print loss once in a while\n",
" if batch_num % 50 == 0:\n",
" curr_loss = nd.mean(loss).asscalar()\n",
" print(\"Epoch: %d; Batch %d; Loss %f\" % (epoch, batch_num, curr_loss))\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "e1a00606",
"metadata": {},
"source": [
"Let's build a model and train it. After training, we will save and restore this model from a file."
]
},
{
"cell_type": "markdown",
"id": "7a8488e1",
"metadata": {},
"source": [
"```python\n",
"net = build_lenet(gluon.nn.Sequential())\n",
"train_model(net)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "73a3e851",
"metadata": {},
"source": [
"<pre>Epoch: 0; Batch 0; Loss 2.288904 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 50; Loss 0.269372 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 100; Loss 0.238990 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 150; Loss 0.320592 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 200; Loss 0.048619 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 250; Loss 0.121555 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 300; Loss 0.083645 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 350; Loss 0.040627 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 400; Loss 0.195946 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 450; Loss 0.155514 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 500; Loss 0.031762 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 550; Loss 0.056516 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 600; Loss 0.095174 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 650; Loss 0.054901 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 700; Loss 0.030067 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 750; Loss 0.102611 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 800; Loss 0.010036 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 850; Loss 0.051853 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 900; Loss 0.008402 <!--notebook-skip-line-->\n",
"</pre> <!--notebook-skip-line-->\n",
"\n",
"## Saving model parameters to file\n",
"\n",
"Okay, we now have a model (`net`) that we can save to a file. Let's save the parameters of this model to a file using the `save_parameters` function."
]
},
{
"cell_type": "markdown",
"id": "a31d54d8",
"metadata": {},
"source": [
"```python\n",
"file_name = \"net.params\"\n",
"net.save_parameters(file_name)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "61b4e9a0",
"metadata": {},
"source": [
"We have successfully saved the parameters of the model into a file.\n",
"\n",
"Note: `Block.collect_params().save()` is not a recommended way to save parameters of a Gluon network if you plan to load the parameters back into a Gluon network using `Block.load_parameters()`.\n",
"\n",
"## Loading model parameters from file\n",
"\n",
"Let's now create a network with the parameters we saved into the file. We build the network again using the helper first and then load the weights from the file we saved using the `load_parameters` function."
]
},
{
"cell_type": "markdown",
"id": "e2b8f86e",
"metadata": {},
"source": [
"```python\n",
"new_net = build_lenet(gluon.nn.Sequential())\n",
"new_net.load_parameters(file_name, ctx=ctx)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "bb4f7c16",
"metadata": {},
"source": [
"Note that to do this, we need the definition of the network as Python code. If we want to recreate this network on a different machine using the saved weights, we need the same Python code (`build_lenet`) that created the network to create the `new_net` object shown above. This means Python code needs to be copied over to any machine where we want to run this network.\n",
"\n",
"If our network is [Hybrid](https://mxnet.apache.org/tutorials/gluon/hybrid.html), we can even save the network architecture into files and we won't need the network definition in a Python file to load the network. We'll see how to do it in the next section.\n",
"\n",
"Let's test the model we just loaded from file."
]
},
{
"cell_type": "markdown",
"id": "8fabcc1e",
"metadata": {},
"source": [
"```python\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def verify_loaded_model(net):\n",
" \"\"\"Run inference using ten random images.\n",
" Print both input and output of the model\"\"\"\n",
"\n",
" def transform(data, label):\n",
" return data.astype(np.float32)/255, label.astype(np.float32)\n",
"\n",
" # Load ten random images from the test dataset\n",
" sample_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train=False, transform=transform),\n",
" 10, shuffle=True)\n",
"\n",
" for data, label in sample_data:\n",
"\n",
" # Display the images\n",
" img = nd.transpose(data, (1,0,2,3))\n",
" img = nd.reshape(img, (28,10*28,1))\n",
" imtiles = nd.tile(img, (1,1,3))\n",
" plt.imshow(imtiles.asnumpy())\n",
" plt.show()\n",
"\n",
" # Display the predictions\n",
" data = nd.transpose(data, (0, 3, 1, 2))\n",
" out = net(data.as_in_context(ctx))\n",
" predictions = nd.argmax(out, axis=1)\n",
" print('Model predictions: ', predictions.asnumpy())\n",
"\n",
" break\n",
"\n",
"verify_loaded_model(new_net)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "cb212ad5",
"metadata": {},
"source": [
"![Model inputs](https://raw.githubusercontent.com/indhub/web-data/4a9c100aa996df3dff0e7f493029d411c2b526c3/mxnet/tutorials/gluon/save_load_params/mnist_in_1.png) <!--notebook-skip-line-->\n",
"\n",
"Model predictions: [1. 1. 4. 5. 0. 5. 7. 0. 3. 6.] <!--notebook-skip-line-->\n",
"\n",
"## Saving model parameters AND architecture to file\n",
"\n",
"[Hybrid](https://mxnet.apache.org/tutorials/gluon/hybrid.html) models can be serialized as JSON files using the `export` function. Once serialized, these models can be loaded from other language bindings like C++ or Scala for faster inference or inference in different environments.\n",
"\n",
"Note that the network we created above is not a Hybrid network and therefore cannot be serialized into a JSON file. So, let's create a Hybrid version of the same network and train it."
]
},
{
"cell_type": "markdown",
"id": "bc020fa9",
"metadata": {},
"source": [
"```python\n",
"net = build_lenet(gluon.nn.HybridSequential())\n",
"net.hybridize()\n",
"train_model(net)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "d6b5b8aa",
"metadata": {},
"source": [
"<pre>Epoch: 0; Batch 0; Loss 2.323284 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 50; Loss 0.444733 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 100; Loss 0.103407 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 150; Loss 0.166772 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 200; Loss 0.227569 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 250; Loss 0.069515 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 300; Loss 0.074086 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 350; Loss 0.074382 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 400; Loss 0.026569 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 450; Loss 0.097248 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 500; Loss 0.059895 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 550; Loss 0.053194 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 600; Loss 0.076294 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 650; Loss 0.047274 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 700; Loss 0.007898 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 750; Loss 0.039478 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 800; Loss 0.031342 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 850; Loss 0.059289 <!--notebook-skip-line-->\n",
"Epoch: 0; Batch 900; Loss 0.037809 <!--notebook-skip-line-->\n",
"</pre> <!--notebook-skip-line-->\n",
"\n",
"We now have a trained hybrid network. This can be exported into files using the `export` function. The `export` function will export the model architecture into a `.json` file and model parameters into a `.params` file."
]
},
{
"cell_type": "markdown",
"id": "ea7369c4",
"metadata": {},
"source": [
"```python\n",
"net.export(\"lenet\", epoch=1)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "4589b2c3",
"metadata": {},
"source": [
"`export` in this case creates `lenet-symbol.json` and `lenet-0001.params` in the current directory.\n",
"\n",
"## Loading model parameters AND architecture from file\n",
"\n",
"### From a different frontend\n",
"\n",
"One of the main reasons to serialize model architecture into a JSON file is to load it from a different frontend like C, C++ or Scala. Here is a couple of examples:\n",
"1. [Loading serialized Hybrid networks from C](https://github.com/apache/mxnet/blob/master/example/image-classification/predict-cpp/image-classification-predict.cc)\n",
"2. [Loading serialized Hybrid networks from Scala](https://github.com/apache/mxnet/blob/master/scala-package/infer/src/main/scala/org/apache/mxnet/infer/ImageClassifier.scala)\n",
"\n",
"### From Python\n",
"\n",
"Serialized Hybrid networks (saved as .JSON and .params file) can be loaded and used inside Python frontend using `gluon.nn.SymbolBlock`. To demonstrate that, let's load the network we serialized above."
]
},
{
"cell_type": "markdown",
"id": "f4e2d9cf",
"metadata": {},
"source": [
"```python\n",
"import warnings\n",
"with warnings.catch_warnings():\n",
" warnings.simplefilter(\"ignore\")\n",
" deserialized_net = gluon.nn.SymbolBlock.imports(\"lenet-symbol.json\", ['data'], \"lenet-0001.params\", ctx=ctx)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "6c7b2609",
"metadata": {},
"source": [
"`deserialized_net` now contains the network we deserialized from files. Let's test the deserialized network to make sure it works."
]
},
{
"cell_type": "markdown",
"id": "c635175c",
"metadata": {},
"source": [
"```python\n",
"verify_loaded_model(deserialized_net)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "22da5562",
"metadata": {},
"source": [
"![Model inputs](https://raw.githubusercontent.com/indhub/web-data/4a9c100aa996df3dff0e7f493029d411c2b526c3/mxnet/tutorials/gluon/save_load_params/mnist_in_2.png) <!--notebook-skip-line-->\n",
"\n",
"Model predictions: [4. 8. 0. 1. 5. 5. 8. 8. 1. 9.] <!--notebook-skip-line-->\n",
"\n",
"That's all! We learned how to save and load Gluon networks from files. Parameters of any Gluon network can be persisted into files. For hybrid networks, both the architecture of the network and the parameters can be saved to and loaded from files.\n",
"\n",
"<!-- INSERT SOURCE DOWNLOAD BUTTONS -->"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}