Layers and Blocks

:label:sec_model_construction

When we first introduced neural networks, we focused on linear models with a single output. Here, the entire model consists of just a single neuron. Note that a single neuron (i) takes some set of inputs; (ii) generates a corresponding scalar output; and (iii) has a set of associated parameters that can be updated to optimize some objective function of interest. Then, once we started thinking about networks with multiple outputs, we leveraged vectorized arithmetic to characterize an entire layer of neurons. Just like individual neurons, layers (i) take a set of inputs, (ii) generate corresponding outputs, and (iii) are described by a set of tunable parameters. When we worked through softmax regression, a single layer was itself the model. However, even when we subsequently introduced MLPs, we could still think of the model as retaining this same basic structure.

Interestingly, for MLPs, both the entire model and its constituent layers share this structure. The entire model takes in raw inputs (the features), generates outputs (the predictions), and possesses parameters (the combined parameters from all constituent layers). Likewise, each individual layer ingests inputs (supplied by the previous layer) generates outputs (the inputs to the subsequent layer), and possesses a set of tunable parameters that are updated according to the signal that flows backwards from the subsequent layer.

While you might think that neurons, layers, and models give us enough abstractions to go about our business, it turns out that we often find it convenient to speak about components that are larger than an individual layer but smaller than the entire model. For example, the ResNet-152 architecture, which is wildly popular in computer vision, possesses hundreds of layers. These layers consist of repeating patterns of groups of layers. Implementing such a network one layer at a time can grow tedious. This concern is not just hypothetical—-such design patterns are common in practice. The ResNet architecture mentioned above won the 2015 ImageNet and COCO computer vision competitions for both recognition and detection :cite:He.Zhang.Ren.ea.2016 and remains a go-to architecture for many vision tasks. Similar architectures in which layers are arranged in various repeating patterns are now ubiquitous in other domains, including natural language processing and speech.

To implement these complex networks, we introduce the concept of a neural network block. A block could describe a single layer, a component consisting of multiple layers, or the entire model itself! One benefit of working with the block abstraction is that they can be combined into larger artifacts, often recursively. This is illustrated in :numref:fig_blocks. By defining code to generate blocks of arbitrary complexity on demand, we can write surprisingly compact code and still implement complex neural networks.

Multiple layers are combined into blocks, forming repeating patterns of larger models. :label:fig_blocks

From a programing standpoint, a block is represented by a class. Any subclass of it must define a forward propagation function that transforms its input into output and must store any necessary parameters. Note that some blocks do not require any parameters at all. Finally a block must possess a backpropagation function, for purposes of calculating gradients. Fortunately, due to some behind-the-scenes magic supplied by the auto differentiation (introduced in :numref:sec_autograd) when defining our own block, we only need to worry about parameters and the forward propagation function.

To begin, we revisit the code that we used to implement MLPs (:numref:sec_mlp_concise). The following code generates a network with one fully-connected hidden layer with 256 units and ReLU activation, followed by a fully-connected output layer with 10 units (no activation function).

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

net = nn.Sequential() net.add(nn.Dense(256, activation=’relu’)) net.add(nn.Dense(10)) net.initialize()

X = np.random.uniform(size=(2, 20)) net(X)

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

```{.python .input}

@tab tensorflow

import tensorflow as tf

net = tf.keras.models.Sequential([ tf.keras.layers.Dense(256, activation=tf.nn.relu), tf.keras.layers.Dense(10), ])

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

  1. :begin_tab:`mxnet`
  2. In this example, we constructed
  3. our model by instantiating an `nn.Sequential`,
  4. assigning the returned object to the `net` variable.
  5. Next, we repeatedly call its `add` function,
  6. appending layers in the order
  7. that they should be executed.
  8. In short, `nn.Sequential` defines a special kind of `Block`,
  9. the class that presents a block in Gluon.
  10. It maintains an ordered list of constituent `Block`s.
  11. The `add` function simply facilitates
  12. the addition of each successive `Block` to the list.
  13. Note that each layer is an instance of the `Dense` class
  14. which is itself a subclass of `Block`.
  15. The forward propagation (`forward`) function is also remarkably simple:
  16. it chains each `Block` in the list together,
  17. passing the output of each as the input to the next.
  18. Note that until now, we have been invoking our models
  19. via the construction `net(X)` to obtain their outputs.
  20. This is actually just shorthand for `net.forward(X)`,
  21. a slick Python trick achieved via
  22. the `Block` class's `__call__` function.
  23. :end_tab:
  24. :begin_tab:`pytorch`
  25. In this example, we constructed
  26. our model by instantiating an `nn.Sequential`, with layers in the order
  27. that they should be executed passed as arguments.
  28. In short, `nn.Sequential` defines a special kind of `Module`,
  29. the class that presents a block in PyTorch.
  30. that maintains an ordered list of constituent `Module`s.
  31. Note that each of the two fully-connected layers is an instance of the `Linear` class
  32. which is itself a subclass of `Module`.
  33. The forward propagation (`forward`) function is also remarkably simple:
  34. it chains each block in the list together,
  35. passing the output of each as the input to the next.
  36. Note that until now, we have been invoking our models
  37. via the construction `net(X)` to obtain their outputs.
  38. This is actually just shorthand for `net.forward(X)`,
  39. a slick Python trick achieved via
  40. the Block class's `__call__` function.
  41. :end_tab:
  42. :begin_tab:`tensorflow`
  43. In this example, we constructed
  44. our model by instantiating an `keras.models.Sequential`, with layers in the order
  45. that they should be executed passed as arguments.
  46. In short, `Sequential` defines a special kind of `keras.Model`,
  47. the class that presents a block in Keras.
  48. It maintains an ordered list of constituent `Model`s.
  49. Note that each of the two fully-connected layers is an instance of the `Dense` class
  50. which is itself a subclass of `Model`.
  51. The forward propagation (`call`) function is also remarkably simple:
  52. it chains each block in the list together,
  53. passing the output of each as the input to the next.
  54. Note that until now, we have been invoking our models
  55. via the construction `net(X)` to obtain their outputs.
  56. This is actually just shorthand for `net.call(X)`,
  57. a slick Python trick achieved via
  58. the Block class's `__call__` function.
  59. :end_tab:
  60. ## A Custom Block
  61. Perhaps the easiest way to develop intuition
  62. about how a block works
  63. is to implement one ourselves.
  64. Before we implement our own custom block,
  65. we briefly summarize the basic functionality
  66. that each block must provide:
  67. 1. Ingest input data as arguments to its forward propagation function.
  68. 1. Generate an output by having the forward propagation function return a value. Note that the output may have a different shape from the input. For example, the first fully-connected layer in our model above ingests an input of arbitrary dimension but returns an output of dimension 256.
  69. 1. Calculate the gradient of its output with respect to its input, which can be accessed via its backpropagation function. Typically this happens automatically.
  70. 1. Store and provide access to those parameters necessary
  71. to execute the forward propagation computation.
  72. 1. Initialize model parameters as needed.
  73. In the following snippet,
  74. we code up a block from scratch
  75. corresponding to an MLP
  76. with one hidden layer with 256 hidden units,
  77. and a 10-dimensional output layer.
  78. Note that the `MLP` class below inherits the class that represents a block.
  79. We will heavily rely on the parent class's functions,
  80. supplying only our own constructor (the `__init__` function in Python) and the forward propagation function.
  81. ```{.python .input}
  82. class MLP(nn.Block):
  83. # Declare a layer with model parameters. Here, we declare two
  84. # fully-connected layers
  85. def __init__(self, **kwargs):
  86. # Call the constructor of the `MLP` parent class `Block` to perform
  87. # the necessary initialization. In this way, other function arguments
  88. # can also be specified during class instantiation, such as the model
  89. # parameters, `params` (to be described later)
  90. super().__init__(**kwargs)
  91. self.hidden = nn.Dense(256, activation='relu') # Hidden layer
  92. self.out = nn.Dense(10) # Output layer
  93. # Define the forward propagation of the model, that is, how to return the
  94. # required model output based on the input `X`
  95. def forward(self, X):
  96. return self.out(self.hidden(X))

```{.python .input}

@tab pytorch

class MLP(nn.Module):

  1. # Declare a layer with model parameters. Here, we declare two fully
  2. # connected layers
  3. def __init__(self):
  4. # Call the constructor of the `MLP` parent class `Block` to perform
  5. # the necessary initialization. In this way, other function arguments
  6. # can also be specified during class instantiation, such as the model
  7. # parameters, `params` (to be described later)
  8. super().__init__()
  9. self.hidden = nn.Linear(20, 256) # Hidden layer
  10. self.out = nn.Linear(256, 10) # Output layer
  11. # Define the forward propagation of the model, that is, how to return the
  12. # required model output based on the input `X`
  13. def forward(self, X):
  14. # Note here we use the funtional version of ReLU defined in the
  15. # nn.functional module.
  16. return self.out(F.relu(self.hidden(X)))
  1. ```{.python .input}
  2. #@tab tensorflow
  3. class MLP(tf.keras.Model):
  4. # Declare a layer with model parameters. Here, we declare two fully
  5. # connected layers
  6. def __init__(self):
  7. # Call the constructor of the `MLP` parent class `Block` to perform
  8. # the necessary initialization. In this way, other function arguments
  9. # can also be specified during class instantiation, such as the model
  10. # parameters, `params` (to be described later)
  11. super().__init__()
  12. # Hidden layer
  13. self.hidden = tf.keras.layers.Dense(units=256, activation=tf.nn.relu)
  14. self.out = tf.keras.layers.Dense(units=10) # Output layer
  15. # Define the forward propagation of the model, that is, how to return the
  16. # required model output based on the input `X`
  17. def call(self, X):
  18. return self.out(self.hidden((X)))

Let us first focus on the forward propagation function. Note that it takes X as the input, calculates the hidden representation with the activation function applied, and outputs its logits. In this MLP implementation, both layers are instance variables. To see why this is reasonable, imagine instantiating two MLPs, net1 and net2, and training them on different data. Naturally, we would expect them to represent two different learned models.

We instantiate the MLP’s layers in the constructor and subsequently invoke these layers on each call to the forward propagation function. Note a few key details. First, our customized __init__ function invokes the parent class’s __init__ function via super().__init__() sparing us the pain of restating boilerplate code applicable to most blocks. We then instantiate our two fully-connected layers, assigning them to self.hidden and self.out. Note that unless we implement a new operator, we need not worry about the backpropagation function or parameter initialization. The system will generate these functions automatically. Let us try this out.

```{.python .input} net = MLP() net.initialize() net(X)

  1. ```{.python .input}
  2. #@tab pytorch
  3. net = MLP()
  4. net(X)

```{.python .input}

@tab tensorflow

net = MLP() net(X)

  1. A key virtue of the block abstraction is its versatility.
  2. We can subclass a block to create layers
  3. (such as the fully-connected layer class),
  4. entire models (such as the `MLP` class above),
  5. or various components of intermediate complexity.
  6. We exploit this versatility
  7. throughout the following chapters,
  8. such as when addressing
  9. convolutional neural networks.
  10. ## The Sequential Block
  11. We can now take a closer look
  12. at how the `Sequential` class works.
  13. Recall that `Sequential` was designed
  14. to daisy-chain other blocks together.
  15. To build our own simplified `MySequential`,
  16. we just need to define two key function:
  17. 1. A function to append blocks one by one to a list.
  18. 2. A forward propagation function to pass an input through the chain of blocks, in the same order as they were appended.
  19. The following `MySequential` class delivers the same
  20. functionality of the default `Sequential` class.
  21. ```{.python .input}
  22. class MySequential(nn.Block):
  23. def add(self, block):
  24. # Here, `block` is an instance of a `Block` subclass, and we assume
  25. # that it has a unique name. We save it in the member variable
  26. # `_children` of the `Block` class, and its type is OrderedDict. When
  27. # the `MySequential` instance calls the `initialize` function, the
  28. # system automatically initializes all members of `_children`
  29. self._children[block.name] = block
  30. def forward(self, X):
  31. # OrderedDict guarantees that members will be traversed in the order
  32. # they were added
  33. for block in self._children.values():
  34. X = block(X)
  35. return X

```{.python .input}

@tab pytorch

class MySequential(nn.Module): def init(self, *args): super().init() for block in args:

  1. # Here, `block` is an instance of a `Module` subclass. We save it
  2. # in the member variable `_modules` of the `Module` class, and its
  3. # type is OrderedDict
  4. self._modules[block] = block
  5. def forward(self, X):
  6. # OrderedDict guarantees that members will be traversed in the order
  7. # they were added
  8. for block in self._modules.values():
  9. X = block(X)
  10. return X
  1. ```{.python .input}
  2. #@tab tensorflow
  3. class MySequential(tf.keras.Model):
  4. def __init__(self, *args):
  5. super().__init__()
  6. self.modules = []
  7. for block in args:
  8. # Here, `block` is an instance of a `tf.keras.layers.Layer`
  9. # subclass
  10. self.modules.append(block)
  11. def call(self, X):
  12. for module in self.modules:
  13. X = module(X)
  14. return X

:begin_tab:mxnet The add function adds a single block to the ordered dictionary _children. You might wonder why every Gluon Block possesses a _children attribute and why we used it rather than just define a Python list ourselves. In short the chief advantage of _children is that during our block’s parameter initialization, Gluon knows to look inside the _children dictionary to find sub-blocks whose parameters also need to be initialized. :end_tab:

:begintab:pytorch In the `_initmethod, we add every block to the ordered dictionary_modulesone by one. You might wonder why everyModulepossesses a_modulesattribute and why we used it rather than just define a Python list ourselves. In short the chief advantage of_modulesis that during our block's parameter initialization, the system knows to look inside the_modules` dictionary to find sub-blocks whose parameters also need to be initialized. :end_tab:

When our MySequential‘s forward propagation function is invoked, each added block is executed in the order in which they were added. We can now reimplement an MLP using our MySequential class.

```{.python .input} net = MySequential() net.add(nn.Dense(256, activation=’relu’)) net.add(nn.Dense(10)) net.initialize() net(X)

  1. ```{.python .input}
  2. #@tab pytorch
  3. net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
  4. net(X)

```{.python .input}

@tab tensorflow

net = MySequential( tf.keras.layers.Dense(units=256, activation=tf.nn.relu), tf.keras.layers.Dense(10)) net(X)

  1. Note that this use of `MySequential`
  2. is identical to the code we previously wrote
  3. for the `Sequential` class
  4. (as described in :numref:`sec_mlp_concise`).
  5. ## Executing Code in the Forward Propagation Function
  6. The `Sequential` class makes model construction easy,
  7. allowing us to assemble new architectures
  8. without having to define our own class.
  9. However, not all architectures are simple daisy chains.
  10. When greater flexibility is required,
  11. we will want to define our own blocks.
  12. For example, we might want to execute
  13. Python's control flow within the forward propagation function.
  14. Moreover, we might want to perform
  15. arbitrary mathematical operations,
  16. not simply relying on predefined neural network layers.
  17. You might have noticed that until now,
  18. all of the operations in our networks
  19. have acted upon our network's activations
  20. and its parameters.
  21. Sometimes, however, we might want to
  22. incorporate terms
  23. that are neither the result of previous layers
  24. nor updatable parameters.
  25. We call these *constant parameters*.
  26. Say for example that we want a layer
  27. that calculates the function
  28. $f(\mathbf{x},\mathbf{w}) = c \cdot \mathbf{w}^\top \mathbf{x}$,
  29. where $\mathbf{x}$ is the input, $\mathbf{w}$ is our parameter,
  30. and $c$ is some specified constant
  31. that is not updated during optimization.
  32. So we implement a `FixedHiddenMLP` class as follows.
  33. ```{.python .input}
  34. class FixedHiddenMLP(nn.Block):
  35. def __init__(self, **kwargs):
  36. super().__init__(**kwargs)
  37. # Random weight parameters created with the `get_constant` function
  38. # are not updated during training (i.e., constant parameters)
  39. self.rand_weight = self.params.get_constant(
  40. 'rand_weight', np.random.uniform(size=(20, 20)))
  41. self.dense = nn.Dense(20, activation='relu')
  42. def forward(self, X):
  43. X = self.dense(X)
  44. # Use the created constant parameters, as well as the `relu` and `dot`
  45. # functions
  46. X = npx.relu(np.dot(X, self.rand_weight.data()) + 1)
  47. # Reuse the fully-connected layer. This is equivalent to sharing
  48. # parameters with two fully-connected layers
  49. X = self.dense(X)
  50. # Control flow
  51. while np.abs(X).sum() > 1:
  52. X /= 2
  53. return X.sum()

```{.python .input}

@tab pytorch

class FixedHiddenMLP(nn.Module): def init(self): super().init()

  1. # Random weight parameters that will not compute gradients and
  2. # therefore keep constant during training
  3. self.rand_weight = torch.rand((20, 20), requires_grad=False)
  4. self.linear = nn.Linear(20, 20)
  5. def forward(self, X):
  6. X = self.linear(X)
  7. # Use the created constant parameters, as well as the `relu` and `mm`
  8. # functions
  9. X = F.relu(torch.mm(X, self.rand_weight) + 1)
  10. # Reuse the fully-connected layer. This is equivalent to sharing
  11. # parameters with two fully-connected layers
  12. X = self.linear(X)
  13. # Control flow
  14. while X.abs().sum() > 1:
  15. X /= 2
  16. return X.sum()
  1. ```{.python .input}
  2. #@tab tensorflow
  3. class FixedHiddenMLP(tf.keras.Model):
  4. def __init__(self):
  5. super().__init__()
  6. self.flatten = tf.keras.layers.Flatten()
  7. # Random weight parameters created with `tf.constant` are not updated
  8. # during training (i.e., constant parameters)
  9. self.rand_weight = tf.constant(tf.random.uniform((20, 20)))
  10. self.dense = tf.keras.layers.Dense(20, activation=tf.nn.relu)
  11. def call(self, inputs):
  12. X = self.flatten(inputs)
  13. # Use the created constant parameters, as well as the `relu` and
  14. # `matmul` functions
  15. X = tf.nn.relu(tf.matmul(X, self.rand_weight) + 1)
  16. # Reuse the fully-connected layer. This is equivalent to sharing
  17. # parameters with two fully-connected layers
  18. X = self.dense(X)
  19. # Control flow
  20. while tf.reduce_sum(tf.math.abs(X)) > 1:
  21. X /= 2
  22. return tf.reduce_sum(X)

In this FixedHiddenMLP model, we implement a hidden layer whose weights (self.rand_weight) are initialized randomly at instantiation and are thereafter constant. This weight is not a model parameter and thus it is never updated by backpropagation. The network then passes the output of this “fixed” layer through a fully-connected layer.

Note that before returning the output, our model did something unusual. We ran a while-loop, testing on the condition its $L_1$ norm is larger than $1$, and dividing our output vector by $2$ until it satisfied the condition. Finally, we returned the sum of the entries in X. To our knowledge, no standard neural network performs this operation. Note that this particular operation may not be useful in any real-world task. Our point is only to show you how to integrate arbitrary code into the flow of your neural network computations.

```{.python .input} net = FixedHiddenMLP() net.initialize() net(X)

  1. ```{.python .input}
  2. #@tab pytorch, tensorflow
  3. net = FixedHiddenMLP()
  4. net(X)

We can mix and match various ways of assembling blocks together. In the following example, we nest blocks in some creative ways.

```{.python .input} class NestMLP(nn.Block): def init(self, kwargs): super().init(kwargs) self.net = nn.Sequential() self.net.add(nn.Dense(64, activation=’relu’), nn.Dense(32, activation=’relu’)) self.dense = nn.Dense(16, activation=’relu’)

  1. def forward(self, X):
  2. return self.dense(self.net(X))

chimera = nn.Sequential() chimera.add(NestMLP(), nn.Dense(20), FixedHiddenMLP()) chimera.initialize() chimera(X)

  1. ```{.python .input}
  2. #@tab pytorch
  3. class NestMLP(nn.Module):
  4. def __init__(self):
  5. super().__init__()
  6. self.net = nn.Sequential(nn.Linear(20, 64), nn.ReLU(),
  7. nn.Linear(64, 32), nn.ReLU())
  8. self.linear = nn.Linear(32, 16)
  9. def forward(self, X):
  10. return self.linear(self.net(X))
  11. chimera = nn.Sequential(NestMLP(), nn.Linear(16, 20), FixedHiddenMLP())
  12. chimera(X)

```{.python .input}

@tab tensorflow

class NestMLP(tf.keras.Model): def init(self): super().init() self.net = tf.keras.Sequential() self.net.add(tf.keras.layers.Dense(64, activation=tf.nn.relu)) self.net.add(tf.keras.layers.Dense(32, activation=tf.nn.relu)) self.dense = tf.keras.layers.Dense(16, activation=tf.nn.relu)

  1. def call(self, inputs):
  2. return self.dense(self.net(inputs))

chimera = tf.keras.Sequential() chimera.add(NestMLP()) chimera.add(tf.keras.layers.Dense(20)) chimera.add(FixedHiddenMLP()) chimera(X) ```

Compilation

:begin_tab:mxnet, tensorflow The avid reader might start to worry about the efficiency of some of these operations. After all, we have lots of dictionary lookups, code execution, and lots of other Pythonic things taking place in what is supposed to be a high-performance deep learning library. The problems of Python’s global interpreter lock are well known. In the context of deep learning, we worry that our extremely fast GPU(s) might have to wait until a puny CPU runs Python code before it gets another job to run. The best way to speed up Python is by avoiding it altogether. :end_tab:

:begin_tab:mxnet One way that Gluon does this is by allowing for hybridization, which will be described later. Here, the Python interpreter executes a block the first time it is invoked. The Gluon runtime records what is happening and the next time around it short-circuits calls to Python. This can accelerate things considerably in some cases but care needs to be taken when control flow (as above) leads down different branches on different passes through the net. We recommend that the interested reader checks out the hybridization section (:numref:sec_hybridize) to learn about compilation after finishing the current chapter. :end_tab:

Summary

  • Layers are blocks.
  • Many layers can comprise a block.
  • Many blocks can comprise a block.
  • A block can contain code.
  • Blocks take care of lots of housekeeping, including parameter initialization and backpropagation.
  • Sequential concatenations of layers and blocks are handled by the Sequential block.

Exercises

  1. What kinds of problems will occur if you change MySequential to store blocks in a Python list?
  2. Implement a block that takes two blocks as an argument, say net1 and net2 and returns the concatenated output of both networks in the forward propagation. This is also called a parallel block.
  3. Assume that you want to concatenate multiple instances of the same network. Implement a factory function that generates multiple instances of the same block and build a larger network from it.

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab:

:begin_tab:tensorflow Discussions :end_tab: