プリンキピア

第6章構築者のための手引き

6.1.3. Executing Code in the Forward Propagation Method6.1.3 順伝播のメソッドの中でコードを実行する

The Sequential class makes model construction easy, allowing us to assemble new architectures without having to define our own class. However, not all architectures are simple daisy chains. When greater flexibility is required, we will want to define our own blocks. For example, we might want to execute Python’s control flow within the forward propagation method. Moreover, we might want to perform arbitrary mathematical operations, not simply relying on predefined neural network layers.
英語のヒント
Sequentialクラスはモデルの構築を簡単にし、自分のクラスを定義しなくても新しい構造を組み立てられるようにしてくれる。しかし、すべての構造が単純な数珠つなぎであるわけではない。もっと柔軟性が必要なときには、自分のブロックを定義したくなるだろう。たとえば、順伝播のメソッドの中でPythonの制御フローを実行したいことがある。さらに、あらかじめ定義されたニューラルネットワークの層に頼るだけでなく、任意の数学的な演算を行いたいこともある。
You may have noticed that until now, all of the operations in our networks have acted upon our network’s activations and its parameters. Sometimes, however, we might want to incorporate terms that are neither the result of previous layers nor updatable parameters. We call these constant parameters. Say for example that we want a layer that calculates the function f(𝐱,𝐰)=c⋅𝐰⊤𝐱, where 𝐱 is the input, 𝐰 is our parameter, and c is some specified constant that is not updated during optimization. So we implement a FixedHiddenMLP class as follows.
英語のヒント
これまで、ネットワークのすべての演算は、ネットワークの活性とパラメータに作用してきたことに気づいたかもしれない。しかし、ときには、前の層の結果でも更新できるパラメータでもない項を組み込みたいことがある。これを定数パラメータと呼ぶ。たとえば、関数f(𝐱,𝐰)=c⋅𝐰⊤𝐱を計算する層がほしいとしよう。ここで𝐱は入力、𝐰はパラメータ、cは最適化のあいだに更新されない、ある指定された定数である。そこで、次のようにFixedHiddenMLPクラスを実装する。
class FixedHiddenMLP(nn.Module):
    def __init__(self):
        super().__init__()
        # Random weight parameters that will not compute gradients and
        # therefore keep constant during training
        self.rand_weight = torch.rand((20, 20))
        self.linear = nn.LazyLinear(20)

    def forward(self, X):
        X = self.linear(X)
        X = F.relu(X @ self.rand_weight + 1)
        # Reuse the fully connected layer. This is equivalent to sharing
        # parameters with two fully connected layers
        X = self.linear(X)
        # Control flow
        while X.abs().sum() > 1:
            X /= 2
        return X.sum()
In this 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.
英語のヒント
このモデルでは、重み(self.rand_weight)がインスタンス化のときに無作為に初期化され、その後は一定である隠れ層を実装する。この重みはモデルのパラメータではないので、逆伝播で更新されることはない。それからネットワークは、この「固定された」層の出力を全結合層に通す。
Note that before returning the output, our model did something unusual. We ran a while-loop, testing on the condition its ℓ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.
英語のヒント
出力を返す前に、モデルがふつうでないことをしたことに注意してほしい。whileループを回し、ℓ1ノルムが1より大きいという条件を調べて、条件を満たすまで出力ベクトルを2で割った。最後に、Xの成分の和を返した。筆者らの知るかぎり、この演算を行う標準的なニューラルネットワークはない。この特定の演算は、現実のどんな課題でも役に立たないかもしれないことに注意してほしい。要点は、ニューラルネットワークの計算の流れに任意のコードを組み込む方法を示すことだけである。
net = FixedHiddenMLP()
net(X)
tensor(-0.3836, grad_fn=<SumBackward0>)
We can mix and match various ways of assembling modules together. In the following example, we nest modules in some creative ways.
英語のヒント
モジュールを組み立てるさまざまなやり方を、自由に組み合わせられる。次の例では、モジュールを工夫して入れ子にする。
class NestMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(nn.LazyLinear(64), nn.ReLU(),
                                 nn.LazyLinear(32), nn.ReLU())
        self.linear = nn.LazyLinear(16)

    def forward(self, X):
        return self.linear(self.net(X))

chimera = nn.Sequential(NestMLP(), nn.LazyLinear(20), FixedHiddenMLP())
chimera(X)
tensor(0.0679, grad_fn=<SumBackward0>)