プリンキピア

第8章現代の畳み込みニューラルネットワーク

8.5.3. Implementation from Scratch8.5.3 ゼロからの実装

To see how batch normalization works in practice, we implement one from scratch below.
英語のヒント
バッチ正規化が実際にどう働くかを見るため、以下でゼロから実装する。
def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum):
    # Use is_grad_enabled to determine whether we are in training mode
    if not torch.is_grad_enabled():
        # In prediction mode, use mean and variance obtained by moving average
        X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps)
    else:
        assert len(X.shape) in (2, 4)
        if len(X.shape) == 2:
            # When using a fully connected layer, calculate the mean and
            # variance on the feature dimension
            mean = X.mean(dim=0)
            var = ((X - mean) ** 2).mean(dim=0)
        else:
            # When using a two-dimensional convolutional layer, calculate the
            # mean and variance on the channel dimension (axis=1). Here we
            # need to maintain the shape of X, so that the broadcasting
            # operation can be carried out later
            mean = X.mean(dim=(0, 2, 3), keepdim=True)
            var = ((X - mean) ** 2).mean(dim=(0, 2, 3), keepdim=True)
        # In training mode, the current mean and variance are used
        X_hat = (X - mean) / torch.sqrt(var + eps)
        # Update the mean and variance using moving average
        moving_mean = (1.0 - momentum) * moving_mean + momentum * mean
        moving_var = (1.0 - momentum) * moving_var + momentum * var
    Y = gamma * X_hat + beta  # Scale and shift
    return Y, moving_mean.data, moving_var.data
We can now create a proper BatchNorm layer. Our layer will maintain proper parameters for scale gamma and shift beta, both of which will be updated in the course of training. Additionally, our layer will maintain moving averages of the means and variances for subsequent use during model prediction.
英語のヒント
これで、ちゃんとしたBatchNorm層を作れる。この層は、スケールgammaとシフトbetaのためのちゃんとしたパラメータをもち、どちらも訓練の中で更新される。さらに、この層は、後でモデルの予測に使うために、平均と分散の移動平均を保持する。
Putting aside the algorithmic details, note the design pattern underlying our implementation of the layer. Typically, we define the mathematics in a separate function, say batch_norm. We then integrate this functionality into a custom layer, whose code mostly addresses bookkeeping matters, such as moving data to the right device context, allocating and initializing any required variables, keeping track of moving averages (here for mean and variance), and so on. This pattern enables a clean separation of mathematics from boilerplate code. Also note that for the sake of convenience we did not worry about automatically inferring the input shape here; thus we need to specify the number of features throughout. By now all modern deep learning frameworks offer automatic detection of size and shape in the high-level batch normalization APIs (in practice we will use this instead).
英語のヒント
アルゴリズムの細部はさておき、この層の実装の根底にある設計パターンに注意してほしい。ふつう、数学は別の関数、たとえばbatch_normで定義する。次に、この機能を独自の層に組み込む。その層のコードは、主に、データを正しいデバイスのコンテキストへ移す、必要な変数を割り当てて初期化する、(ここでは平均と分散の)移動平均を記録し続ける、といった事務的なことを扱う。このパターンにより、数学と決まりきったコードをきれいに分けられる。また、便宜のため、ここでは入力の形状を自動で推論することは気にしなかったので、特徴量の数を最後まで指定する必要があることにも注意してほしい。今では、現代の深層学習のフレームワークはどれも、高水準のバッチ正規化のAPIで大きさと形状を自動で検出する機能を備えている(実際にはこちらを使う)。
class BatchNorm(nn.Module):
    # num_features: the number of outputs for a fully connected layer or the
    # number of output channels for a convolutional layer. num_dims: 2 for a
    # fully connected layer and 4 for a convolutional layer
    def __init__(self, num_features, num_dims):
        super().__init__()
        if num_dims == 2:
            shape = (1, num_features)
        else:
            shape = (1, num_features, 1, 1)
        # The scale parameter and the shift parameter (model parameters) are
        # initialized to 1 and 0, respectively
        self.gamma = nn.Parameter(torch.ones(shape))
        self.beta = nn.Parameter(torch.zeros(shape))
        # The variables that are not model parameters are initialized to 0 and
        # 1
        self.moving_mean = torch.zeros(shape)
        self.moving_var = torch.ones(shape)

    def forward(self, X):
        # If X is not on the main memory, copy moving_mean and moving_var to
        # the device where X is located
        if self.moving_mean.device != X.device:
            self.moving_mean = self.moving_mean.to(X.device)
            self.moving_var = self.moving_var.to(X.device)
        # Save the updated moving_mean and moving_var
        Y, self.moving_mean, self.moving_var = batch_norm(
            X, self.gamma, self.beta, self.moving_mean,
            self.moving_var, eps=1e-5, momentum=0.1)
        return Y
We used momentum to govern the aggregation over past mean and variance estimates. This is somewhat of a misnomer as it has nothing whatsoever to do with the momentum term of optimization. Nonetheless, it is the commonly adopted name for this term and in deference to API naming convention we use the same variable name in our code.
英語のヒント
過去の平均と分散の推定値の集約を左右するのに、momentumを使った。これは、最適化のモーメンタムの項とはまったく何の関係もないので、いささか誤った名前である。それでも、これはこの項に広く使われている名前であり、APIの命名の慣習に従って、コードでも同じ変数名を使う。