Skip to content

Residual Networks (ResNet) and ResNeXt

As we design ever deeper networks it becomes imperative to understand how adding layers can increase the complexity and expressiveness of the network. Even more important is the ability to design networks where adding layers makes networks strictly more expressive rather than just different. To make some progress we need a bit of mathematics.

julia
using Pkg; Pkg.activate("../../d2lai")
using d2lai
using Flux 
using CUDA, cuDNN
using Statistics, Flux.Zygote
  Activating project at `/workspace/d2l-julia/d2lai`

Function Classes

Consider F, the class of functions that a specific network architecture (together with learning rates and other hyperparameter settings) can reach. That is, for all fF there exists some set of parameters (e.g., weights and biases) that can be obtained through training on a suitable dataset. Let's assume that f is the "truth" function that we really would like to find. If it is in F, we are in good shape but typically we will not be quite so lucky. Instead, we will try to find some fF which is our best bet within F. For instance, given a dataset with features X and labels y, we might try finding it by solving the following optimization problem:

fF=defargminfL(X,y,f) subject to fF.

We know that regularization [138], [139] may control complexity of F and achieve consistency, so a larger size of training data generally leads to better fF. It is only reasonable to assume that if we design a different and more powerful architecture F we should arrive at a better outcome. In other words, we would expect that fF is "better" than fF. However, if FF there is no guarantee that this should even happen. In fact, fF might well be worse. As illustrated by Figure, for non-nested function classes, a larger function class does not always move closer to the "truth" function f. For instance, on the left of Figure, though F3 is closer to f than F1, F6 moves away and there is no guarantee that further increasing the complexity can reduce the distance from f. With nested function classes where F1F6 on the right of Figure, we can avoid the aforementioned issue from the non-nested function classes.

For non-nested function classes, a larger (indicated by area) function class does not guarantee we will get closer to the "truth" function (\mathit{f}^$). This does not happen in nested function classes.*

Thus, only if larger function classes contain the smaller ones are we guaranteed that increasing them strictly increases the expressive power of the network. For deep neural networks, if we can train the newly-added layer into an identity function f(x)=x, the new model will be as effective as the original model. As the new model may get a better solution to fit the training dataset, the added layer might make it easier to reduce training errors.

This is the question that He et al. [93] considered when working on very deep computer vision models. At the heart of their proposed residual network (ResNet) is the idea that every additional layer should more easily contain the identity function as one of its elements. These considerations are rather profound but they led to a surprisingly simple solution, a residual block. With it, ResNet won the ImageNet Large Scale Visual Recognition Challenge in 2015. The design had a profound influence on how to build deep neural networks. For instance, residual blocks have been added to recurrent networks [140], [141]. Likewise, Transformers [142] use them to stack many layers of networks efficiently. It is also used in graph neural networks [143] and, as a basic concept, it has been used extensively in computer vision [86], [144]. Note that residual networks are predated by highway networks [145] that share some of the motivation, albeit without the elegant parametrization around the identity function.

Residual Blocks

Let's focus on a local part of a neural network, as depicted in Figure. Denote the input by x. We assume that f(x), the desired underlying mapping we want to obtain by learning, is to be used as input to the activation function on the top. On the left, the portion within the dotted-line box must directly learn f(x). On the right, the portion within the dotted-line box needs to learn the residual mapping g(x)=f(x)x, which is how the residual block derives its name. If the identity mapping f(x)=x is the desired underlying mapping, the residual mapping amounts to g(x)=0 and it is thus easier to learn: we only need to push the weights and biases of the upper weight layer (e.g., fully connected layer and convolutional layer) within the dotted-line box to zero. The right figure illustrates the residual block of ResNet, where the solid line carrying the layer input x to the addition operator is called a residual connection (or shortcut connection). With residual blocks, inputs can forward propagate faster through the residual connections across layers. In fact, the residual block can be thought of as a special case of the multi-branch Inception block: it has two branches one of which is the identity mapping.

In a regular block (left), the portion within the dotted-line box must directly learn the mapping f(x). In a residual block (right), the portion within the dotted-line box needs to learn the residual mapping g(x)=f(x)x, making the identity mapping f(x)=x easier to learn.

ResNet has VGG's full 3×3 convolutional layer design. The residual block has two 3×3 convolutional layers with the same number of output channels. Each convolutional layer is followed by a batch normalization layer and a ReLU activation function. Then, we skip these two convolution operations and add the input directly before the final ReLU activation function. This kind of design requires that the output of the two convolutional layers has to be of the same shape as the input, so that they can be added together. If we want to change the number of channels, we need to introduce an additional 1×1 convolutional layer to transform the input into the desired shape for the addition operation. Let's have a look at the code below.

julia
struct Residual{N} <: AbstractModel
    net::N
end 

function Residual(channels_in::Int; num_channels::Int = channels_in, use_1x1conv = !isequal(channels_in, num_channels), stride = 1)
    conv_chain = Chain(
            Conv((3,3) , channels_in=>num_channels, pad = 1, stride = stride),
            BatchNorm(num_channels, relu),
            Conv((3,3) , num_channels=>num_channels, pad = 1),
            BatchNorm(num_channels),
        )
    
    net = use_1x1conv ? Parallel(+, conv_chain, Conv((1,1), channels_in=>num_channels, stride = stride)) : Parallel(+, conv_chain, Flux.identity)
    Residual(net)
end

(r::Residual)(x) = relu.(r.net(x))

This code generates two types of networks: one where we add the input to the output before applying the ReLU nonlinearity whenever use_1x1conv=False; and one where we adjust channels and resolution by means of a 1×1 convolution before adding. Figure illustrates this.

ResNet block with and without 1×1 convolution, which transforms the input into the desired shape for the addition operation.

Now let's look at [a situation where the input and output are of the same shape], where 1×1 convolution is not needed.

julia
r = Residual(3)
r(rand(4, 5, 3, 32)) |> size
┌ Warning: Layer with Float32 parameters got Float64 input.
│   The input will be converted, but any earlier layers may be very slow.
│   layer = Conv((3, 3), 3 => 3, pad=1)  # 84 parameters
│   summary(x) = "4×5×3×32 Array{Float64, 4}"
└ @ Flux ~/.julia/packages/Flux/3711C/src/layers/stateless.jl:60





(4, 5, 3, 32)

We also have the option to halve the output height and width while increasing the number of output channels. In this case we use 1×1 convolutions via use_1x1conv=True. This comes in handy at the beginning of each ResNet block to reduce the spatial dimensionality via strides=2.

julia
r = Residual(3; num_channels = 6)
r(rand(4, 5, 3, 32)) |> size
(4, 5, 6, 32)

ResNet Model

The first two layers of ResNet are the same as those of the GoogLeNet we described before: the 7×7 convolutional layer with 64 output channels and a stride of 2 is followed by the 3×3 max-pooling layer with a stride of 2. The difference is the batch normalization layer added after each convolutional layer in ResNet.

julia
struct ResNetB1{N} <: AbstractModel
    net::N
end

function ResNetB1()
    net = Chain(
        Conv((7,7), 1 => 64, pad = 3 , stride = 2),
        BatchNorm(64, relu),
        MaxPool((3,3), pad = 1, stride = 2)
    )
    ResNetB1(net)
end 
(r::ResNetB1)(x) = r.net(x)
Flux.@layer ResNetB1

GoogLeNet uses four modules made up of Inception blocks. However, ResNet uses four modules made up of residual blocks, each of which uses several residual blocks with the same number of output channels. The number of channels in the first module is the same as the number of input channels. Since a max-pooling layer with a stride of 2 has already been used, it is not necessary to reduce the height and width. In the first residual block for each of the subsequent modules, the number of channels is doubled compared with that of the previous module, and the height and width are halved.

julia
struct ResNetBlock{N} <: AbstractModel 
    net::N 
end

function ResNetBlock(channel_in, num_residuals, num_channels; first_block = false)
    block = if first_block
        blocks = map(1:num_residuals) do i
            Residual(channel_in)
        end |> Chain
    else
        blocks = map(1:num_residuals) do i
            if i == 1
                return Residual(channel_in; num_channels, stride = 2)
            else
                return Residual(num_channels)
            end
        end |> Chain
    end 
    ResNetBlock(block)
end
Flux.@layer ResNetBlock
(r::ResNetBlock)(x) = r.net(x)

Then, we add all the modules to ResNet. Here, two residual blocks are used for each module. Lastly, just like GoogLeNet, we add a global average pooling layer, followed by the fully connected layer output.

julia
struct ResNet{N} <: AbstractClassifier 
    net::N
end
Flux.@layer ResNet 

function ResNet(arch::Tuple, num_classes::Int = 10)
    channel_ins = last.(arch[1:end-1]) 
    net = Flux.@autosize (96, 96, 1, 1) Chain(
        ResNetB1(),
        ResNetBlock(64, arch[1]..., first_block = true),
        map(arch[2:end], channel_ins) do (num_residuals, num_channels), channel_in 
            ResNetBlock(channel_in, num_residuals, num_channels)
        end |> Chain, 
        GlobalMeanPool(),
        Flux.flatten,
        Dense(_ => num_classes),
        softmax
        
    )
    ResNet(net)
end
(r::ResNet)(x) = r.net(x)

There are four convolutional layers in each module (excluding the 1×1 convolutional layer). Together with the first 7×7 convolutional layer and the final fully connected layer, there are 18 layers in total. Therefore, this model is commonly known as ResNet-18. By configuring different numbers of channels and residual blocks in the module, we can create different ResNet models, such as the deeper 152-layer ResNet-152. Although the main architecture of ResNet is similar to that of GoogLeNet, ResNet's structure is simpler and easier to modify. All these factors have resulted in the rapid and widespread use of ResNet. Figure depicts the full ResNet-18.

The ResNet-18 architecture.

Before training ResNet, let's [observe how the input shape changes across different modules in ResNet]. As in all the previous architectures, the resolution decreases while the number of channels increases up until the point where a global average pooling layer aggregates all features.

julia
arch = ((2, 64), (2, 128), (2, 256), (2, 512))
model = ResNet(arch)
ResNet(
  Chain(
    ResNetB1(
      Chain(
        Conv((7, 7), 1 => 64, pad=3, stride=2),  # 3_200 parameters
        BatchNorm(64, relu),            # 128 parameters, plus 128
        MaxPool((3, 3), pad=1, stride=2),
      ),
    ),
    ResNetBlock(
      Chain(
        [
          Residual(
            Parallel(
              +,
              Chain(
                Conv((3, 3), 64 => 64, pad=1),  # 36_928 parameters
                BatchNorm(64, relu),    # 128 parameters, plus 128
                Conv((3, 3), 64 => 64, pad=1),  # 36_928 parameters
                BatchNorm(64),          # 128 parameters, plus 128
              ),
              identity,
            ),
          ),
          Residual(
            Parallel(
              +,
              Chain(
                Conv((3, 3), 64 => 64, pad=1),  # 36_928 parameters
                BatchNorm(64, relu),    # 128 parameters, plus 128
                Conv((3, 3), 64 => 64, pad=1),  # 36_928 parameters
                BatchNorm(64),          # 128 parameters, plus 128
              ),
              identity,
            ),
          ),
        ],
      ),
    ),
    Chain(
      ResNetBlock(
        Chain(
          [
            Residual(
              Parallel(
                +,
                Chain(
                  Conv((3, 3), 64 => 128, pad=1, stride=2),  # 73_856 parameters
                  BatchNorm(128, relu),  # 256 parameters, plus 256
                  Conv((3, 3), 128 => 128, pad=1),  # 147_584 parameters
                  BatchNorm(128),       # 256 parameters, plus 256
                ),
                Conv((1, 1), 64 => 128, stride=2),  # 8_320 parameters
              ),
            ),
            Residual(
              Parallel(
                +,
                Chain(
                  Conv((3, 3), 128 => 128, pad=1),  # 147_584 parameters
                  BatchNorm(128, relu),  # 256 parameters, plus 256
                  Conv((3, 3), 128 => 128, pad=1),  # 147_584 parameters
                  BatchNorm(128),       # 256 parameters, plus 256
                ),
                identity,
              ),
            ),
          ],
        ),
      ),
      ResNetBlock(
        Chain(
          [
            Residual(
              Parallel(
                +,
                Chain(
                  Conv((3, 3), 128 => 256, pad=1, stride=2),  # 295_168 parameters
                  BatchNorm(256, relu),  # 512 parameters, plus 512
                  Conv((3, 3), 256 => 256, pad=1),  # 590_080 parameters
                  BatchNorm(256),       # 512 parameters, plus 512
                ),
                Conv((1, 1), 128 => 256, stride=2),  # 33_024 parameters
              ),
            ),
            Residual(
              Parallel(
                +,
                Chain(
                  Conv((3, 3), 256 => 256, pad=1),  # 590_080 parameters
                  BatchNorm(256, relu),  # 512 parameters, plus 512
                  Conv((3, 3), 256 => 256, pad=1),  # 590_080 parameters
                  BatchNorm(256),       # 512 parameters, plus 512
                ),
                identity,
              ),
            ),
          ],
        ),
      ),
      ResNetBlock(
        Chain(
          [
            Residual(
              Parallel(
                +,
                Chain(
                  Conv((3, 3), 256 => 512, pad=1, stride=2),  # 1_180_160 parameters
                  BatchNorm(512, relu),  # 1_024 parameters, plus 1_024
                  Conv((3, 3), 512 => 512, pad=1),  # 2_359_808 parameters
                  BatchNorm(512),       # 1_024 parameters, plus 1_024
                ),
                Conv((1, 1), 256 => 512, stride=2),  # 131_584 parameters
              ),
            ),
            Residual(
              Parallel(
                +,
                Chain(
                  Conv((3, 3), 512 => 512, pad=1),  # 2_359_808 parameters
                  BatchNorm(512, relu),  # 1_024 parameters, plus 1_024
                  Conv((3, 3), 512 => 512, pad=1),  # 2_359_808 parameters
                  BatchNorm(512),       # 1_024 parameters, plus 1_024
                ),
                identity,
              ),
            ),
          ],
        ),
      ),
    ),
    GlobalMeanPool(),
    Flux.flatten,
    Dense(512 => 10),                   # 5_130 parameters
    NNlib.softmax,
  ),
)         # Total: 76 trainable arrays, 11_178_378 parameters,
          # plus 34 non-trainable, 7_808 parameters, summarysize 42.680 MiB.

Training

We train ResNet on the Fashion-MNIST dataset, just like before. ResNet is quite a powerful and flexible architecture. The plot capturing training and validation loss illustrates a significant gap between both graphs, with the training loss being considerably lower. For a network of this flexibility, more training data would offer distinct benefit in closing the gap and improving accuracy.

julia
data = d2lai.FashionMNISTData(batchsize = 128, resize = (96,96));
opt = Descent(0.01)
trainer = Trainer(model, data, opt; max_epochs = 10, gpu = true, board_yscale = :identity)
d2lai.fit(trainer);
    [ Info: Train Loss: 0.19277047, Val Loss: 0.19109984, Val Acc: 0.9375
    [ Info: Train Loss: 0.12554948, Val Loss: 0.14957266, Val Acc: 0.9375
    [ Info: Train Loss: 0.22092374, Val Loss: 0.14626466, Val Acc: 1.0
    [ Info: Train Loss: 0.04200567, Val Loss: 0.088903934, Val Acc: 1.0
    [ Info: Train Loss: 0.19900467, Val Loss: 0.1520779, Val Acc: 0.9375
    [ Info: Train Loss: 0.032146264, Val Loss: 0.08688806, Val Acc: 1.0
    [ Info: Train Loss: 0.06265808, Val Loss: 0.07228865, Val Acc: 1.0
    [ Info: Train Loss: 0.008486914, Val Loss: 0.22081932, Val Acc: 0.9375
    [ Info: Train Loss: 0.0028302989, Val Loss: 0.14812489, Val Acc: 0.9375
    [ Info: Train Loss: 0.008302619, Val Loss: 0.14797957, Val Acc: 0.9375
julia

ResNeXt

One of the challenges one encounters in the design of ResNet is the trade-off between nonlinearity and dimensionality within a given block. That is, we could add more nonlinearity by increasing the number of layers, or by increasing the width of the convolutions. An alternative strategy is to increase the number of channels that can carry information between blocks. Unfortunately, the latter comes with a quadratic penalty since the computational cost of ingesting ci channels and emitting co channels is proportional to O(cico) (see our discussion in :numref:sec_channels).

We can take some inspiration from the Inception block of Figure which has information flowing through the block in separate groups. Applying the idea of multiple independent groups to the ResNet block of Figure led to the design of ResNeXt [80]. Different from the smorgasbord of transformations in Inception, ResNeXt adopts the same transformation in all branches, thus minimizing the need for manual tuning of each branch.

The ResNeXt block. The use of grouped convolution with g groups is g times faster than a dense convolution. It is a bottleneck residual block when the number of intermediate channels b is less than c.

Breaking up a convolution from ci to co channels into one of g groups of size ci/g generating g outputs of size co/g is called, quite fittingly, a grouped convolution. The computational cost (proportionally) is reduced from O(cico) to O(g(ci/g)(co/g))=O(cico/g), i.e., it is g times faster. Even better, the number of parameters needed to generate the output is also reduced from a ci×co matrix to g smaller matrices of size (ci/g)×(co/g), again a g times reduction. In what follows we assume that both ci and co are divisible by g.

The only challenge in this design is that no information is exchanged between the g groups. The ResNeXt block of Figure amends this in two ways: the grouped convolution with a 3×3 kernel is sandwiched in between two 1×1 convolutions. The second one serves double duty in changing the number of channels back. The benefit is that we only pay the O(cb) cost for 1×1 kernels and can make do with an O(b2/g) cost for 3×3 kernels. Similar to the residual block implementation in :numref:subsec_residual-blks, the residual connection is replaced (thus generalized) by a 1×1 convolution.

The right-hand figure in Figure provides a much more concise summary of the resulting network block. It will also play a major role in the design of generic modern CNNs in :numref:sec_cnn-design. Note that the idea of grouped convolutions dates back to the implementation of AlexNet [90]. When distributing the network across two GPUs with limited memory, the implementation treated each GPU as its own channel with no ill effects.

The following implementation of the ResNeXtBlock class takes as argument groups (g), with bot_channels (b) intermediate (bottleneck) channels. Lastly, when we need to reduce the height and width of the representation, we add a stride of 2 by setting use_1x1conv=True, strides=2.

julia
struct ResNeXtBlock{N} <: AbstractClassifier 
    net::N
end

function ResNeXtBlock(channel_in::Int, groups::Int, bot_mul; num_channels = channel_in, 
        
        use_1x1conv = !isequal(channel_in, num_channels),
        stride = 1)
    bot_channels = Int(round(num_channels*bot_mul))
    bottleneck_net = Chain(
        Conv((1,1), channel_in => bot_channels),
        BatchNorm(bot_channels, relu),
        Conv((3,3), bot_channels => bot_channels, pad = 1, stride = stride, groups = groups),
        BatchNorm(bot_channels, relu),
        Conv((1,1), bot_channels => num_channels, stride = 1),
        BatchNorm(num_channels, relu)
    )
    net = if !use_1x1conv
        Parallel(+, Flux.identity, bottleneck_net)
    else
        sidenet = Chain(
            Conv((1,1), channel_in => num_channels, stride = stride),
            BatchNorm(num_channels, relu)
        )
        Parallel(+, sidenet, bottleneck_net)
    end
    ResNeXtBlock(net)
end
Flux.@layer ResNeXtBlock 
(r::ResNeXtBlock)(x) = r.net(x)

Its use is entirely analogous to that of the ResNetBlock discussed previously. For instance, when using (use_1x1conv=False, strides=1), the input and output are of the same shape. Alternatively, setting use_1x1conv=True, strides=2 halves the output height and width.

julia
blk = ResNeXtBlock(32, 16, 1)
ResNeXtBlock(
  Parallel(
    +,
    identity,
    Chain(
      Conv((1, 1), 32 => 32),           # 1_056 parameters
      BatchNorm(32, relu),              # 64 parameters, plus 64
      Conv((3, 3), 32 => 32, pad=1, groups=16),  # 608 parameters
      BatchNorm(32, relu),              # 64 parameters, plus 64
      Conv((1, 1), 32 => 32),           # 1_056 parameters
      BatchNorm(32, relu),              # 64 parameters, plus 64
    ),
  ),
)         # Total: 12 trainable arrays, 2_912 parameters,
          # plus 6 non-trainable, 192 parameters, summarysize 13.344 KiB.
julia
blk = ResNeXtBlock(32, 16, 2; num_channels = 64)
ResNeXtBlock(
  Parallel(
    +,
    Chain(
      Conv((1, 1), 32 => 64),           # 2_112 parameters
      BatchNorm(64, relu),              # 128 parameters, plus 128
    ),
    Chain(
      Conv((1, 1), 32 => 128),          # 4_224 parameters
      BatchNorm(128, relu),             # 256 parameters, plus 256
      Conv((3, 3), 128 => 128, pad=1, groups=16),  # 9_344 parameters
      BatchNorm(128, relu),             # 256 parameters, plus 256
      Conv((1, 1), 128 => 64),          # 8_256 parameters
      BatchNorm(64, relu),              # 128 parameters, plus 128
    ),
  ),
)         # Total: 16 trainable arrays, 24_704 parameters,
          # plus 8 non-trainable, 768 parameters, summarysize 101.125 KiB.

Summary and Discussion

Nested function classes are desirable since they allow us to obtain strictly more powerful rather than also subtly different function classes when adding capacity. One way of accomplishing this is by letting additional layers to simply pass through the input to the output. Residual connections allow for this. As a consequence, this changes the inductive bias from simple functions being of the form f(x)=0 to simple functions looking like f(x)=x.

The residual mapping can learn the identity function more easily, such as pushing parameters in the weight layer to zero. We can train an effective deep neural network by having residual blocks. Inputs can forward propagate faster through the residual connections across layers. As a consequence, we can thus train much deeper networks. For instance, the original ResNet paper [93] allowed for up to 152 layers. Another benefit of residual networks is that it allows us to add layers, initialized as the identity function, during the training process. After all, the default behavior of a layer is to let the data pass through unchanged. This can accelerate the training of very large networks in some cases.

Prior to residual connections, bypassing paths with gating units were introduced to effectively train highway networks with over 100 layers [145]. Using identity functions as bypassing paths, ResNet performed remarkably well on multiple computer vision tasks. Residual connections had a major influence on the design of subsequent deep neural networks, of either convolutional or sequential nature. As we will introduce later, the Transformer architecture [142] adopts residual connections (together with other design choices) and is pervasive in areas as diverse as language, vision, speech, and reinforcement learning.

ResNeXt is an example for how the design of convolutional neural networks has evolved over time: by being more frugal with computation and trading it off against the size of the activations (number of channels), it allows for faster and more accurate networks at lower cost. An alternative way of viewing grouped convolutions is to think of a block-diagonal matrix for the convolutional weights. Note that there are quite a few such "tricks" that lead to more efficient networks. For instance, ShiftNet [95] mimicks the effects of a 3×3 convolution, simply by adding shifted activations to the channels, offering increased function complexity, this time without any computational cost.

A common feature of the designs we have discussed so far is that the network design is fairly manual, primarily relying on the ingenuity of the designer to find the "right" network hyperparameters. While clearly feasible, it is also very costly in terms of human time and there is no guarantee that the outcome is optimal in any sense. In :numref:sec_cnn-design we will discuss a number of strategies for obtaining high quality networks in a more automated fashion. In particular, we will review the notion of network design spaces that led to the RegNetX/Y models [97].

Exercises

  1. What are the major differences between the Inception block in Figure and the residual block? How do they compare in terms of computation, accuracy, and the classes of functions they can describe?

  2. Refer to Table 1 in the ResNet paper [93] to implement different variants of the network.

  3. For deeper networks, ResNet introduces a "bottleneck" architecture to reduce model complexity. Try to implement it.

  4. In subsequent versions of ResNet, the authors changed the "convolution, batch normalization, and activation" structure to the "batch normalization, activation, and convolution" structure. Make this improvement yourself. See Figure 1 in He et al. [146] for details.

  5. Why can't we just increase the complexity of functions without bound, even if the function classes are nested?

julia
## 3.
struct ResNetBottleNeck{N} <: AbstractModel
    net::N 
end

Flux.@layer ResNetBottleNeck 

(rbn::ResNetBottleNeck)(x) = r.net(x)


function ResNetBottleNeck(channel_in, bot_mul)
    bottled_channels = Int(round(channel_in*bot_mul))
    main_net = Chain(
        Conv((1,1), channel_in => bottled_channels),
        BatchNorm(bottled_channels, relu),
        Conv((3,3), bottled_channels => bottled_channels, pad = 1, stride = 1),
        BatchNorm(bottled_channels, relu),
        Conv((1,1), bottled_channels => channel_in),
        BatchNorm(channel_in, relu),
    )
    net = Parallel(+, Flux.identity, main_net)
    ResNetBottleNeck(net)
end

b_neck = ResNetBottleNeck(64, 0.25)
ResNetBottleNeck(
  Parallel(
    +,
    identity,
    Chain(
      Conv((1, 1), 64 => 16),           # 1_040 parameters
      BatchNorm(16, relu),              # 32 parameters, plus 32
      Conv((3, 3), 16 => 16, pad=1),    # 2_320 parameters
      BatchNorm(16, relu),              # 32 parameters, plus 32
      Conv((1, 1), 16 => 64),           # 1_088 parameters
      BatchNorm(64, relu),              # 128 parameters, plus 128
    ),
  ),
)         # Total: 12 trainable arrays, 4_640 parameters,
          # plus 6 non-trainable, 192 parameters, summarysize 20.094 KiB.
julia
Flux.outputsize(b_neck.net, (96, 96, 64, 1))
(96, 96, 64, 1)
julia
## 4.
struct ResidualBlockNew{N} <: AbstractModel
    net::N 
end
Flux.@layer ResidualBlockNew
(rbn::ResidualBlockNew)(x) = rbn.net(x)

function ResidualBlockNew(channel_in::Int; num_channels = channel_in, use_1x1conv = !isequal(channel_in, num_channels), stride = 1)
    main_net = Chain(
        BatchNorm(channel_in, relu),
        Conv((3,3), channel_in => num_channels, stride = stride, pad = 1),
        BatchNorm(num_channels, relu),
        Conv((3,3), num_channels => num_channels, stride = 1, pad = 1),
    )
    shortcut_connection = if use_1x1conv
        Conv((1,1), channel_in => num_channels, stride = stride)
    else
        Flux.identity
    end
    net = Parallel(+, shortcut_connection, main_net)
    ResidualBlockNew(net)
end

rb_new = ResidualBlockNew(64; num_channels = 128, stride = 2)
ResidualBlockNew(
  Parallel(
    +,
    Conv((1, 1), 64 => 128, stride=2),  # 8_320 parameters
    Chain(
      BatchNorm(64, relu),              # 128 parameters, plus 128
      Conv((3, 3), 64 => 128, pad=1, stride=2),  # 73_856 parameters
      BatchNorm(128, relu),             # 256 parameters, plus 256
      Conv((3, 3), 128 => 128, pad=1),  # 147_584 parameters
    ),
  ),
)         # Total: 10 trainable arrays, 230_144 parameters,
          # plus 4 non-trainable, 384 parameters, summarysize 901.500 KiB.
julia
Flux.outputsize(rb_new.net, (96, 96, 64, 1))
(48, 48, 128, 1)
julia