Parameter Management

Once we have chosen an architecture and set our hyperparameters, we proceed to the training loop, where our goal is to find parameter values that minimize our loss function. After training, we will need these parameters in order to make future predictions. Additionally, we will sometimes wish to extract the parameters either to reuse them in some other context, to save our model to disk so that it may be executed in other software, or for examination in the hope of gaining scientific understanding.

Most of the time, we will be able to ignore the nitty-gritty details of how parameters are declared and manipulated, relying on deep learning frameworks to do the heavy lifting. However, when we move away from stacked architectures with standard layers, we will sometimes need to get into the weeds of declaring and manipulating parameters. In this section, we cover the following:

  • Accessing parameters for debugging, diagnostics, and visualizations.
  • Parameter initialization.
  • Sharing parameters across different model components.

We start by focusing on an MLP with one hidden layer.

```{.python .input} from mxnet import init, np, npx from mxnet.gluon import nn npx.set_np()

net = nn.Sequential() net.add(nn.Dense(8, activation=’relu’)) net.add(nn.Dense(1)) net.initialize() # Use the default initialization method

X = np.random.uniform(size=(2, 4)) net(X) # Forward computation

  1. ```{.python .input}
  2. #@tab pytorch
  3. import torch
  4. from torch import nn
  5. net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
  6. X = torch.rand(size=(2, 4))
  7. net(X)

```{.python .input}

@tab tensorflow

import tensorflow as tf import numpy as np

net = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(4, activation=tf.nn.relu), tf.keras.layers.Dense(1), ])

X = tf.random.uniform((2, 4)) net(X)

  1. ## Parameter Access
  2. Let us start with how to access parameters
  3. from the models that you already know.
  4. When a model is defined via the `Sequential` class,
  5. we can first access any layer by indexing
  6. into the model as though it were a list.
  7. Each layer's parameters are conveniently
  8. located in its attribute.
  9. We can inspect the parameters of the second fully-connected layer as follows.
  10. ```{.python .input}
  11. print(net[1].params)

```{.python .input}

@tab pytorch

print(net[2].state_dict())

  1. ```{.python .input}
  2. #@tab tensorflow
  3. print(net.layers[2].weights)

The output tells us a few important things. First, this fully-connected layer contains two parameters, corresponding to that layer’s weights and biases, respectively. Both are stored as single precision floats (float32). Note that the names of the parameters allow us to uniquely identify each layer’s parameters, even in a network containing hundreds of layers.

Targeted Parameters

Note that each parameter is represented as an instance of the parameter class. To do anything useful with the parameters, we first need to access the underlying numerical values. There are several ways to do this. Some are simpler while others are more general. The following code extracts the bias from the second fully-connected layer (i.e. the third neural network layer), which returns a parameter class instance, and further accesses that parameter’s value.

```{.python .input} print(type(net[1].bias)) print(net[1].bias) print(net[1].bias.data())

  1. ```{.python .input}
  2. #@tab pytorch
  3. print(type(net[2].bias))
  4. print(net[2].bias)
  5. print(net[2].bias.data)

```{.python .input}

@tab tensorflow

print(type(net.layers[2].weights[1])) print(net.layers[2].weights[1]) print(tf.convert_to_tensor(net.layers[2].weights[1]))

  1. :begin_tab:`mxnet,pytorch`
  2. Parameters are complex objects,
  3. containing values, gradients,
  4. and additional information.
  5. That's why we need to request the value explicitly.
  6. In addition to the value, each parameter also allows us to access the gradient. Because we have not invoked backpropagation for this network yet, it is in its initial state.
  7. :end_tab:
  8. ```{.python .input}
  9. net[1].weight.grad()

```{.python .input}

@tab pytorch

net[2].weight.grad == None

  1. ### All Parameters at Once
  2. When we need to perform operations on all parameters,
  3. accessing them one-by-one can grow tedious.
  4. The situation can grow especially unwieldy
  5. when we work with more complex blocks (e.g., nested blocks),
  6. since we would need to recurse
  7. through the entire tree to extract
  8. each sub-block's parameters. Below we demonstrate accessing the parameters of the first fully-connected layer vs. accessing all layers.
  9. ```{.python .input}
  10. print(net[0].collect_params())
  11. print(net.collect_params())

```{.python .input}

@tab pytorch

print([(name, param.shape) for name, param in net[0].named_parameters()]) print([(name, param.shape) for name, param in net.named_parameters()])

  1. ```{.python .input}
  2. #@tab tensorflow
  3. print(net.layers[1].weights)
  4. print(net.get_weights())

This provides us with another way of accessing the parameters of the network as follows.

```{.python .input} net.collect_params()[‘dense1_bias’].data()

  1. ```{.python .input}
  2. #@tab pytorch
  3. net.state_dict()['2.bias'].data

```{.python .input}

@tab tensorflow

net.get_weights()[1]

  1. ### Collecting Parameters from Nested Blocks
  2. Let us see how the parameter naming conventions work
  3. if we nest multiple blocks inside each other.
  4. For that we first define a function that produces blocks
  5. (a block factory, so to speak) and then
  6. combine these inside yet larger blocks.
  7. ```{.python .input}
  8. def block1():
  9. net = nn.Sequential()
  10. net.add(nn.Dense(32, activation='relu'))
  11. net.add(nn.Dense(16, activation='relu'))
  12. return net
  13. def block2():
  14. net = nn.Sequential()
  15. for _ in range(4):
  16. # Nested here
  17. net.add(block1())
  18. return net
  19. rgnet = nn.Sequential()
  20. rgnet.add(block2())
  21. rgnet.add(nn.Dense(10))
  22. rgnet.initialize()
  23. rgnet(X)

```{.python .input}

@tab pytorch

def block1(): return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4), nn.ReLU())

def block2(): net = nn.Sequential() for i in range(4):

  1. # Nested here
  2. net.add_module(f'block {i}', block1())
  3. return net

rgnet = nn.Sequential(block2(), nn.Linear(4, 1)) rgnet(X)

  1. ```{.python .input}
  2. #@tab tensorflow
  3. def block1(name):
  4. return tf.keras.Sequential([
  5. tf.keras.layers.Flatten(),
  6. tf.keras.layers.Dense(4, activation=tf.nn.relu)],
  7. name=name)
  8. def block2():
  9. net = tf.keras.Sequential()
  10. for i in range(4):
  11. # Nested here
  12. net.add(block1(name=f'block-{i}'))
  13. return net
  14. rgnet = tf.keras.Sequential()
  15. rgnet.add(block2())
  16. rgnet.add(tf.keras.layers.Dense(1))
  17. rgnet(X)

Now that we have designed the network, let us see how it is organized.

```{.python .input} print(rgnet.collect_params) print(rgnet.collect_params())

  1. ```{.python .input}
  2. #@tab pytorch
  3. print(rgnet)

```{.python .input}

@tab tensorflow

print(rgnet.summary())

  1. Since the layers are hierarchically nested,
  2. we can also access them as though
  3. indexing through nested lists.
  4. For instance, we can access the first major block,
  5. within it the second sub-block,
  6. and within that the bias of the first layer,
  7. with as follows.
  8. ```{.python .input}
  9. rgnet[0][1][0].bias.data()

```{.python .input}

@tab pytorch

rgnet[0][1][0].bias.data

  1. ```{.python .input}
  2. #@tab tensorflow
  3. rgnet.layers[0].layers[1].layers[1].weights[1]

Parameter Initialization

Now that we know how to access the parameters, let us look at how to initialize them properly. We discussed the need for proper initialization in :numref:sec_numerical_stability. The deep learning framework provides default random initializations to its layers. However, we often want to initialize our weights according to various other protocols. The framework provides most commonly used protocols, and also allows to create a custom initializer.

:begin_tab:mxnet By default, MXNet initializes weight parameters by randomly drawing from a uniform distribution $U(-0.07, 0.07)$, clearing bias parameters to zero. MXNet’s init module provides a variety of preset initialization methods. :end_tab:

:begin_tab:pytorch By default, PyTorch initializes weight and bias matrices uniformly by drawing from a range that is computed according to the input and output dimension. PyTorch’s nn.init module provides a variety of preset initialization methods. :end_tab:

:begin_tab:tensorflow By default, Keras initializes weight matrices uniformly by drawing from a range that is computed according to the input and output dimension, and the bias parameters are all set to zero. TensorFlow provides a variety of initialization methods both in the root module and the keras.initializers module. :end_tab:

Built-in Initialization

Let us begin by calling on built-in initializers. The code below initializes all weight parameters as Gaussian random variables with standard deviation 0.01, while bias parameters cleared to zero.

```{.python .input}

Here force_reinit ensures that parameters are freshly initialized even if

they were already initialized previously

net.initialize(init=init.Normal(sigma=0.01), force_reinit=True) net[0].weight.data()[0]

  1. ```{.python .input}
  2. #@tab pytorch
  3. def init_normal(m):
  4. if type(m) == nn.Linear:
  5. nn.init.normal_(m.weight, mean=0, std=0.01)
  6. nn.init.zeros_(m.bias)
  7. net.apply(init_normal)
  8. net[0].weight.data[0], net[0].bias.data[0]

```{.python .input}

@tab tensorflow

net = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense( 4, activation=tf.nn.relu, kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.01), bias_initializer=tf.zeros_initializer()), tf.keras.layers.Dense(1)])

net(X) net.weights[0], net.weights[1]

  1. We can also initialize all the parameters
  2. to a given constant value (say, 1).
  3. ```{.python .input}
  4. net.initialize(init=init.Constant(1), force_reinit=True)
  5. net[0].weight.data()[0]

```{.python .input}

@tab pytorch

def initconstant(m): if type(m) == nn.Linear: nn.init.constant(m.weight, 1) nn.init.zeros_(m.bias) net.apply(init_constant) net[0].weight.data[0], net[0].bias.data[0]

  1. ```{.python .input}
  2. #@tab tensorflow
  3. net = tf.keras.models.Sequential([
  4. tf.keras.layers.Flatten(),
  5. tf.keras.layers.Dense(
  6. 4, activation=tf.nn.relu,
  7. kernel_initializer=tf.keras.initializers.Constant(1),
  8. bias_initializer=tf.zeros_initializer()),
  9. tf.keras.layers.Dense(1),
  10. ])
  11. net(X)
  12. net.weights[0], net.weights[1]

We can also apply different initializers for certain blocks. For example, below we initialize the first neural network layer with the Xavier initializer and initialize the third neural network layer to a constant value of 42.

```{.python .input} net[0].weight.initialize(init=init.Xavier(), force_reinit=True) net[1].initialize(init=init.Constant(42), force_reinit=True) print(net[0].weight.data()[0]) print(net[1].weight.data())

  1. ```{.python .input}
  2. #@tab pytorch
  3. def xavier(m):
  4. if type(m) == nn.Linear:
  5. torch.nn.init.xavier_uniform_(m.weight)
  6. def init_42(m):
  7. if type(m) == nn.Linear:
  8. torch.nn.init.constant_(m.weight, 42)
  9. net[0].apply(xavier)
  10. net[2].apply(init_42)
  11. print(net[0].weight.data[0])
  12. print(net[2].weight.data)

```{.python .input}

@tab tensorflow

net = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense( 4, activation=tf.nn.relu, kernel_initializer=tf.keras.initializers.GlorotUniform()), tf.keras.layers.Dense( 1, kernel_initializer=tf.keras.initializers.Constant(1)), ])

net(X) print(net.layers[1].weights[0]) print(net.layers[2].weights[0])

  1. ### Custom Initialization
  2. Sometimes, the initialization methods we need
  3. are not provided by the deep learning framework.
  4. In the example below, we define an initializer
  5. for any weight parameter $w$ using the following strange distribution:
  6. $$
  7. \begin{aligned}
  8. w \sim \begin{cases}
  9. U(5, 10) & \text{ with probability } \frac{1}{4} \\
  10. 0 & \text{ with probability } \frac{1}{2} \\
  11. U(-10, -5) & \text{ with probability } \frac{1}{4}
  12. \end{cases}
  13. \end{aligned}
  14. $$
  15. :begin_tab:`mxnet`
  16. Here we define a subclass of the `Initializer` class.
  17. Usually, we only need to implement the `_init_weight` function
  18. which takes a tensor argument (`data`)
  19. and assigns to it the desired initialized values.
  20. :end_tab:
  21. :begin_tab:`pytorch`
  22. Again, we implement a `my_init` function to apply to `net`.
  23. :end_tab:
  24. :begin_tab:`tensorflow`
  25. Here we define a subclass of `Initializer` and implement the `__call__`
  26. function that return a desired tensor given the shape and data type.
  27. :end_tab:
  28. ```{.python .input}
  29. class MyInit(init.Initializer):
  30. def _init_weight(self, name, data):
  31. print('Init', name, data.shape)
  32. data[:] = np.random.uniform(-10, 10, data.shape)
  33. data *= np.abs(data) >= 5
  34. net.initialize(MyInit(), force_reinit=True)
  35. net[0].weight.data()[:2]

```{.python .input}

@tab pytorch

def myinit(m): if type(m) == nn.Linear: print(“Init”, *[(name, param.shape) for name, param in m.named_parameters()][0]) nn.init.uniform(m.weight, -10, 10) m.weight.data *= m.weight.data.abs() >= 5

net.apply(my_init) net[0].weight[:2]

  1. ```{.python .input}
  2. #@tab tensorflow
  3. class MyInit(tf.keras.initializers.Initializer):
  4. def __call__(self, shape, dtype=None):
  5. return tf.random.uniform(shape, dtype=dtype)
  6. net = tf.keras.models.Sequential([
  7. tf.keras.layers.Flatten(),
  8. tf.keras.layers.Dense(
  9. 4,
  10. activation=tf.nn.relu,
  11. kernel_initializer=MyInit()),
  12. tf.keras.layers.Dense(1),
  13. ])
  14. net(X)
  15. print(net.layers[1].weights[0])

Note that we always have the option of setting parameters directly.

```{.python .input} net[0].weight.data()[:] += 1 net[0].weight.data()[0, 0] = 42 net[0].weight.data()[0]

  1. ```{.python .input}
  2. #@tab pytorch
  3. net[0].weight.data[:] += 1
  4. net[0].weight.data[0, 0] = 42
  5. net[0].weight.data[0]

```{.python .input}

@tab tensorflow

net.layers[1].weights[0][:].assign(net.layers[1].weights[0] + 1) net.layers[1].weights[0][0, 0].assign(42) net.layers[1].weights[0]

  1. :begin_tab:`mxnet`
  2. A note for advanced users:
  3. if you want to adjust parameters within an `autograd` scope,
  4. you need to use `set_data` to avoid confusing
  5. the automatic differentiation mechanics.
  6. :end_tab:
  7. ## Tied Parameters
  8. Often, we want to share parameters across multiple layers.
  9. Let us see how to do this elegantly.
  10. In the following we allocate a dense layer
  11. and then use its parameters specifically
  12. to set those of another layer.
  13. ```{.python .input}
  14. net = nn.Sequential()
  15. # We need to give the shared layer a name so that we can refer to its
  16. # parameters
  17. shared = nn.Dense(8, activation='relu')
  18. net.add(nn.Dense(8, activation='relu'),
  19. shared,
  20. nn.Dense(8, activation='relu', params=shared.params),
  21. nn.Dense(10))
  22. net.initialize()
  23. X = np.random.uniform(size=(2, 20))
  24. net(X)
  25. # Check whether the parameters are the same
  26. print(net[1].weight.data()[0] == net[2].weight.data()[0])
  27. net[1].weight.data()[0, 0] = 100
  28. # Make sure that they are actually the same object rather than just having the
  29. # same value
  30. print(net[1].weight.data()[0] == net[2].weight.data()[0])

```{.python .input}

@tab pytorch

We need to give the shared layer a name so that we can refer to its

parameters

shared = nn.Linear(8, 8) net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), shared, nn.ReLU(), shared, nn.ReLU(), nn.Linear(8, 1)) net(X)

Check whether the parameters are the same

print(net[2].weight.data[0] == net[4].weight.data[0]) net[2].weight.data[0, 0] = 100

Make sure that they are actually the same object rather than just having the

same value

print(net[2].weight.data[0] == net[4].weight.data[0])

  1. ```{.python .input}
  2. #@tab tensorflow
  3. # tf.keras behaves a bit differently. It removes the duplicate layer
  4. # automatically
  5. shared = tf.keras.layers.Dense(4, activation=tf.nn.relu)
  6. net = tf.keras.models.Sequential([
  7. tf.keras.layers.Flatten(),
  8. shared,
  9. shared,
  10. tf.keras.layers.Dense(1),
  11. ])
  12. net(X)
  13. # Check whether the parameters are different
  14. print(len(net.layers) == 3)

:begin_tab:mxnet This example shows that the parameters of the second and third layer are tied. They are not just equal, they are represented by the same exact tensor. Thus, if we change one of the parameters, the other one changes, too. You might wonder, when parameters are tied what happens to the gradients? Since the model parameters contain gradients, the gradients of the second hidden layer and the third hidden layer are added together during backpropagation. :end_tab:

:begin_tab:pytorch This example shows that the parameters of the third and fifth neural network layer are tied. They are not just equal, they are represented by the same exact tensor. Thus, if we change one of the parameters, the other one changes, too. You might wonder, when parameters are tied what happens to the gradients? Since the model parameters contain gradients, the gradients of the second hidden layer (i.e. the third neural network layer) and the third hidden layer (i.e. the fifth neural network layer) are added together during backpropagation. :end_tab:

Summary

  • We have several ways to access, initialize, and tie model parameters.
  • We can use custom initialization.

Exercises

  1. Use the FancyMLP model defined in :numref:sec_model_construction and access the parameters of the various layers.
  2. Look at the initialization module document to explore different initializers.
  3. Construct an MLP containing a shared parameter layer and train it. During the training process, observe the model parameters and gradients of each layer.
  4. Why is sharing parameters a good idea?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab:

:begin_tab:tensorflow Discussions :end_tab: