Run this notebook online:Binder or Colab: Colab

5.4. File I/O

So far we discussed how to process data and how to build, train, and test deep learning models. However, at some point, we will hopefully be happy enough with the learned models that we will want to save the results for later use in various contexts (perhaps even to make predictions in deployment). Additionally, when running a long training process, the best practice is to periodically save intermediate results (checkpointing) to ensure that we do not lose several days worth of computation if we trip over the power cord of our server. Thus it is time we learned how to load and store both individual weight vectors and entire models. This section addresses both issues.

5.4.1. Loading and Saving Tensors

For individual tensors, we can convert NDArrays into byte[]s by calling their encode() function. We can then convert them back into NDArrays by calling the NDArray decode() function and passing in an NDManager(to manage the created NDArray) and byte[] (the wanted tensor).

We can then use FileInputStream and FileOutputStream to read and write these to files respectively.

%mavenRepo snapshots

%maven ai.djl:api:0.7.0-SNAPSHOT
%maven ai.djl:basicdataset:0.7.0-SNAPSHOT
%maven org.slf4j:slf4j-api:1.7.26
%maven org.slf4j:slf4j-simple:1.7.26

%maven ai.djl.mxnet:mxnet-engine:0.7.0-SNAPSHOT
%maven ai.djl.mxnet:mxnet-native-auto:1.7.0-a
import ai.djl.MalformedModelException;
import ai.djl.Model;
import ai.djl.inference.Predictor;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.Activation;
import ai.djl.nn.Parameter;
import ai.djl.nn.SequentialBlock;
import ai.djl.nn.core.Linear;
import ai.djl.translate.NoopTranslator;
import ai.djl.translate.TranslateException;
import ai.djl.util.PairList;
import ai.djl.util.Utils;

import java.nio.file.Files;
import java.util.Arrays;
NDManager manager = NDManager.newBaseManager();

NDArray x = manager.arange(4);
try (FileOutputStream fos = new FileOutputStream("x-file")) {
ND: (4) gpu(0) int32
[ 0,  1,  2,  3]

We can now read this data from the stored file back into memory.

NDArray x2;
try (FileInputStream fis = new FileInputStream("x-file")) {
    // We use the `Utils` method `toByteArray()` to read
    // from a `FileInputStream` and return it as a `byte[]`.
    x2 = NDArray.decode(manager, Utils.toByteArray(fis));
ND: (4) gpu(0) int32
[ 0,  1,  2,  3]

5.4.2. Model Parameters

Saving individual weight vectors (or other tensors) is useful, but it gets very tedious if we want to save (and later load) an entire model. After all, we might have hundreds of parameter groups sprinkled throughout. For this reason the framework provides built-in functionality to load and save entire networks. An important detail to note is that this saves model parameters and not the entire model. For example, if we have a 3-layer MLP, we need to specify the architecture separately. The reason for this is that the models themselves can contain arbitrary code, hence they cannot be serialized as naturally. Thus, in order to reinstate a model, we need to generate the architecture in code and then load the parameters from disk. Let us start with our familiar MLP.

public SequentialBlock createMLP() {
    SequentialBlock mlp = new SequentialBlock();
    return mlp;

SequentialBlock original = createMLP();

NDArray x = manager.randomUniform(0, 1, new Shape(2, 5));

original.setInitializer(new XavierInitializer());
original.initialize(manager, DataType.FLOAT32, x.getShape());

Model model = Model.newInstance("mlp");

Predictor predictor = model.newPredictor(new NoopTranslator());

NDArray y = ((NDList) predictor.predict(new NDList(x))).singletonOrThrow();

Next, we store the parameters of the model as a file with the name mlp.param.

// Save file
File mlpParamFile = new File("mlp.param");
DataOutputStream os = new DataOutputStream(Files.newOutputStream(mlpParamFile.toPath()));

To recover the model, we instantiate a clone of the original MLP model. Instead of randomly initializing the model parameters, we read the parameters stored in the file directly.

// Create duplicate of network architecture
SequentialBlock clone = createMLP();
// Load Parameters
clone.loadParameters(manager, new DataInputStream(Files.newInputStream(mlpParamFile.toPath())));

Now let us directly compare the parameters of both models. We get the Parameter’s respective array at each index for both PairLists and then compare the two.

Note that we cannot compare the Parameter’s directly. When we load the Parameter, a new unique id is generated for it. Instead, we can check that the NDArrays are equal.

They should be identical if loaded properly.

// Original model's parameters
PairList<String, Parameter> originalParams = original.getParameters();
// Loaded model's parameters
PairList<String, Parameter> loadedParams = clone.getParameters();

for (int i = 0; i < originalParams.size(); i++) {
    if (originalParams.valueAt(i).getArray().equals(loadedParams.valueAt(i).getArray())) {
        System.out.printf("True ");
    else {
        System.out.printf("False ");
True True True True

Since both instances have the same model parameters, the computation result of the same input x should be the same. Let us verify this.

Model modelClone = Model.newInstance("mlp");

Predictor predictor2 = modelClone.newPredictor(new NoopTranslator());

NDArray yClone = ((NDList) predictor2.predict(new NDList(x))).singletonOrThrow();

ND: (2, 10) gpu(0) boolean
[[ true,  true,  true,  true,  true,  true,  true,  true,  true,  true],
 [ true,  true,  true,  true,  true,  true,  true,  true,  true,  true],

5.4.3. Summary

  • The decode and encode functions along with FileStreams can be used to perform File I/O for tensor objects.

  • Saving the architecture has to be done in code rather than in parameters.

5.4.4. Exercises

  1. Even if there is no need to deploy trained models to a different device, what are the practical benefits of storing model parameters?

  2. Assume that we want to reuse only parts of a network to be incorporated into a network of a different architecture. How would you go about using, say the first two layers from a previous network in a new network.

  3. How would you go about saving network architecture and parameters? What restrictions would you impose on the architecture?