Standalone Deep Learning

KAIST Idea factory YouTube lecture


Theory

  • LR Scheduler: defines the method for decaying the lr
  • What if the loss suddenly spikes only at a specific epoch?
    • The LR is too large, so the loss explodes in a completely wrong direction

Problems of MLP

  • Too many parameters
    • Increasing the depth of the model causes the parameters to grow exponentially
    • The model capacity is too large → possibility of overfitting
    • Some parameters are actually completely meaningless (especially for image data)

    ⇒ CNN

CNN

  • Convolution Layer
    • Keeps the image as 32x32x3 in order to preserve the spatial data structure
    • Uses small filters → filtered image → activation map

    Figure

    Figure

  • Convolutional Net

    Figure

    • When multiple layers are stacked, it becomes a ‘network’
    • Number of filters → becomes the depth of the next convolutional layer
    • Just like fully-connected layers, after the matrix operation (CONV), a ReLU activation is applied to convert it into a nonlinear form → then repeated again in the next layer… this is the structure

💡

Stride and Padding

Figure

(N + 2 x padding - F) / stride + 1

  • Stride: the interval at which the filter is applied
  • Padding: filling the surroundings of the input data with specific data
    • Zero Padding: the fill value is 0
    • Used to make the output size an integer when applying stride
    • Used to preserve the size of the data as it passes through the network

💡

Neuron view of Convolutional Layer

  • When an activation map with depth 5 is created for the input layer, if each layer is regarded as a single neuron, then they share the same Receptive Field but are multiplied by different weights, so they can be seen as playing the role of extracting different features
  • As the depth of the neural net increases, the receptive field grows larger and it takes in higher-dimensional information
  • Pooling Layer
    • Down-sampling by excluding meaningless information - the image size is reduced (since it is applied to a single layer, the depth is preserved)
    • Max Pooling: pooling by taking the maximum value within the filter size and a given stride. Usually reduces to half the size

      💡

      Why use Max Pooling?

      : Mimicking the neuron - highly activated information is important information. The overall image would become a bit brighter and stronger, so why bother?

      ⇒ Don’t assume that max pooling is always the best

  • Fully Connected Layer
    • As the layers of the CNN get deeper, the data becomes higher-dimensional data with reduced size
    • MLPs work well on data that has high-dimensional information but not too large a size

      ⇒ At the end, an FC layer is applied to perform classification

Advanced Architectures of CNN


AlexNet

  • First use of ReLU
  • Uses data with heavy preprocessing
  • 8 layers
  • dropout 0.5
  • batch size 128
  • SGD Momentum 0.9
  • Learning Rate le-2
    • The step is decreased when the increase becomes small while watching the val acc graph
    • L2 weight decay is 5e-4
    • Ensembles 7 CNNs

VGGNet

Figure

Figure

  • Small filters and deep networks
    • Three 3X3 filters & one 7X7 filter ultimately have the same receptive field
    • As the layers get deeper, the receptive field becomes wider
    • However, the number of required parameters is fewer when using three 3X3 filters than when using one 7X7 filter!
      • 9 * 9 * 9 vs. 7 * 7
      • The CONV layer can be seen as the number of values within one filter

    ⇒ It is possible to catch more complex features with fewer parameters!

  • 16 ~ 19 layers
  • Uses only 3X3 CONV filters! (stride 1, pad 1)
    • 2X2 MAX POOL (stride 2)

💡

Problems

  • Too many parameters are used in the FC layers
  • It consumes a great deal of memory

    ⇒ This causes problems: the batch size has to be small, and training takes a long time

GoogleNet

  • 22 layers
  • Inception module
  • No FC layers
  • The number of parameters is far fewer than VGGNet! (5M)

Inception Module

Figure

  • Started from the idea of applying filters of various sizes simultaneously in one layer
  • Concatenating the parallel filters

Naive Inception Module

💡

Problems

  • In the process of concatenating the filters, the depth becomes too deep and the amount of computation increases

Figure

⇒ Improved through a bottleneck that performs dimension reduction!

: A process is added that uses 64 1X1 filters to reduce the original depth of 256 down to 64

Figure

Figure

ResNet

  • An extremely deep network with 152 layers

Problems of Deep CNN

Figure

  • If overfitting were the problem, only the test error should be higher… but the training error is also higher than that of a shallower model

    ⇒ The deeper the model, the harder it is to optimize the model, making training difficult

    ⇒ Solved through Residual Connections

Residual Connections

Figure

Figure

Figure

  • ResNet is a structure where several Residual blocks are connected in series
  • Instead of a separate MAX POOL, it uses stride to reduce the size of the output tensor
  • It does not place separate FC layers, and only has FC1000 for the final classification
  • For deeper ResNet models, dimension reduction using a bottleneck is also performed, like in GoogleNet

Practice

  • Using the CIFAR10 dataset, a CNN model is trained instead of an MLP.

Model Architecture

  • Differences from the MLP
    • Structure: the classifier (fully-connected layer) defined within init
      • After passing through the Conv layers, when going to the classifier, .view is used to match the dimensions
    • First use of MaxPool2d, Conv2d layers
    • Dimension check is important! Be sure to do it by making it into a function
    • Batch normalization uses BatchNorm2d (MLP: BatchNorm1d)
  • nn.Conv2d parameters
    • number of input channels
    • number of output channels (=number of kernels)
    • kernel size
    • stride
    • padding
  • nn.Sequential
    • A module that can execute multiple layers sequentially
    • Layers can be passed directly as parameters
    • Difference from nn.ModuleList:
      • The sequential layer execution functionality that nn.ModuleList does not provide
     def _make_layers(self, model_code, in_channels, use_bn):
         layers = []
         for x in cfg[model_code]:
             if x == 'M':
                 layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
             else:
                 layers += [nn.Conv2d(in_channels=in_channels,
                                      out_channels=x,
                                      kernel_size=3,
                                      stride=1,
                                      padding=1)]
                 if use_bn:
                     layers += [nn.BatchNorm2d(x)]
                 layers += [self.act]
                 in_channels = x
         return nn.Sequential(*layers)
    
    • As a return value, nn.Sequential takes the layers stored in the layers list as parameters and enables sequential layer execution
    • The part where its usage is shown more intuitively is the self.classifier section

       self.classifer = nn.Sequential(
           nn.Linear(512, 256),
           self.act,
           nn.Linear(256, out_dim)
       )
      
      • The fc layer is defined very concisely!

Train, Validation, Test

  • The .view part previously used to match the dimensions of the inputs and layers data disappears

Model Architecture

Conv Functions

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, 
                     bias=False)
  • The stride is fixed to 2 in the specific situations where the output tensor size is reduced, and 1 otherwise

BasicBlock Module

class BasicBlock(nn.Module): # nn.Module 상속
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride) # stride를 변경한다면 첫번째 conv에서 진행
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x # skip connection을 위한 초기 x 저장

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity # f(x)에 x를 더해주는 과정
        out = self.relu(out)

        return out
  • Implementation of a single Residual Block
  • Composed of two 3X3 Convs and a skip connection
  • downsample: when adding x and F(x) at the end, if F(x) has been downsampled, x must also be downsampled
  • Batch Normalization is performed after every Conv layer (requires the number of input features)

BottleNeck Module

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = conv1x1(inplanes, planes) # bottleneck 구현을 위한 conv1x1
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes, stride) # 줄인다면 stride 2로 변경
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = conv1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out
  • expansion: used in the original paper’s implementation, which always increases the depth by 4x after passing through the bottleneck layer
  • Aside from the two conv1x1 layers added for the bottleneck, it has the same structure as the basic block

ResNet

class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000, zero_init_residual=False):
        super(ResNet, self).__init__()
        self.inplanes = 64
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        
        # 다운샘플링을 위해 stride=2인 레이어들
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules(): # 모델의 모든 레이어와 하위 모듈을 돌면서
            if isinstance(m, nn.Conv2d): # conv 레이어라면 he 초기화
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d): # batchnorm 레이어라면 w=1, b=0으로 초기화
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks): # 채널 수만큼 레이어를 쌓아서 nn.Sequential로 리턴
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x) # 7x7 필터 통과
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return x
  • zero_init_residual: initializes the weights of the last BatchNorm layer of the residual block to 0
    • Used for training stability and efficiency