第6章構築者のための手引き
6.1. Layers and Modules6.1 層とモジュール
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.
英語のヒント
ニューラルネットワークを最初に紹介したときには、出力が一つの線形モデルに焦点を当てた。ここでは、モデル全体がたった一つのニューロンからなる。一つのニューロンは、(i)何らかの入力の組を受け取り、(ii)対応するスカラーの出力を生成し、(iii)関心のある何らかの目的関数を最適化するために更新できる、対応するパラメータの組をもつことに注意してほしい。そして、複数の出力をもつネットワークを考え始めると、ベクトル化した算術を活用して、ニューロンの層全体を記述した。個々のニューロンと同じく、層は(i)入力の組を受け取り、(ii)対応する出力を生成し、(iii)調整できるパラメータの組によって記述される。ソフトマックス回帰に取り組んだときには、一つの層がそれ自体でモデルだった。しかし、その後MLPを紹介したときでさえ、モデルは同じ基本構造を保っていると考えることができた。
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.
英語のヒント
興味深いことに、MLPでは、モデル全体もそれを構成する層も、この構造を共有している。モデル全体は、生の入力(特徴量)を受け取り、出力(予測)を生成し、パラメータ(構成するすべての層のパラメータを合わせたもの)をもつ。同様に、個々の層は、(前の層から与えられた)入力を取り込み、出力(次の層への入力)を生成し、次の層から逆向きに流れてくる信号に従って更新される、調整できるパラメータの組をもつ。
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 (He et al., 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.
英語のヒント
ニューロン、層、モデルがあれば、仕事を進めるのに十分な抽象化がそろっていると思うかもしれないが、実は、個々の層より大きくモデル全体より小さい部品について語るのが便利なことがよくある。たとえば、コンピュータビジョンで大人気のResNet-152の構造には、何百もの層がある。これらの層は、層のまとまりが繰り返すパターンからなる。そうしたネットワークを一層ずつ実装するのは、うんざりする作業になりうる。この懸念は単なる仮定の話ではない。そうした設計のパターンは、実際によく見られる。上で触れたResNetの構造は、2015年のImageNetとCOCOのコンピュータビジョンのコンペティションで、認識と検出の両部門で優勝し(He et al., 2016)、今も多くの視覚の課題で定番の構造である。層がさまざまな繰り返しのパターンで並べられた似た構造は、今では自然言語処理や音声を含むほかの領域でもいたるところに見られる。
To implement these complex networks, we introduce the concept of a neural network module. A module could describe a single layer, a component consisting of multiple layers, or the entire model itself! One benefit of working with the module abstraction is that they can be combined into larger artifacts, often recursively. This is illustrated in Fig. 6.1.1. By defining code to generate modules of arbitrary complexity on demand, we can write surprisingly compact code and still implement complex neural networks.
英語のヒント
こうした複雑なネットワークを実装するため、ニューラルネットワークのモジュールという概念を導入する。モジュールは、一つの層を表すことも、複数の層からなる部品を表すことも、さらにはモデル全体そのものを表すこともできる!モジュールという抽象化を使うことの利点の一つは、モジュールを組み合わせて、多くの場合は再帰的に、より大きな成果物にできることである。これを図6.1.1に図示する。任意の複雑さのモジュールを必要に応じて生成するコードを定義すれば、驚くほど簡潔なコードを書きながら、複雑なニューラルネットワークを実装できる。
Fig. 6.1.1図6.1.1
Multiple layers are combined into modules, forming repeating patterns of larger models.
英語のヒント
複数の層がモジュールにまとめられ、より大きなモデルの繰り返しのパターンを形作る。
From a programming standpoint, a module is represented by a class. Any subclass of it must define a forward propagation method that transforms its input into output and must store any necessary parameters. Note that some modules do not require any parameters at all. Finally a module must possess a backpropagation method, for purposes of calculating gradients. Fortunately, due to some behind-the-scenes magic supplied by the auto differentiation (introduced in Section 2.5) when defining our own module, we only need to worry about parameters and the forward propagation method.
英語のヒント
プログラミングの観点からは、モジュールはクラスで表される。その任意のサブクラスは、入力を出力に変換する順伝播のメソッドを定義し、必要なパラメータを保存しなければならない。パラメータをまったく必要としないモジュールもあることに注意してほしい。最後に、モジュールは、勾配を計算するための逆伝播のメソッドをもたなければならない。幸い、自分でモジュールを定義するときには、(2.5節で紹介した)自動微分が舞台裏で魔法のように働いてくれるので、パラメータと順伝播のメソッドのことだけを気にすればよい。
import torch
from torch import nn
from torch.nn import functional as FTo begin, we revisit the code that we used to implement MLPs (Section 5.1). 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 ten units (no activation function).
英語のヒント
まず、MLPを実装するのに使ったコード(5.1節)を見直そう。次のコードは、256個のユニットとReLU活性化をもつ全結合の隠れ層が一つあり、その後に(活性化関数のない)10個のユニットをもつ全結合の出力層が続くネットワークを生成する。
net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(), nn.LazyLinear(10))
X = torch.rand(2, 20)
net(X).shapetorch.Size([2, 10])In this example, we constructed our model by instantiating an
nn.Sequential, with layers in the order that they should be executed passed as arguments. In short, nn.Sequential defines a special kind of Module, the class that presents a module in PyTorch. It maintains an ordered list of constituent Modules. Note that each of the two fully connected layers is an instance of the Linear class which is itself a subclass of Module. The forward propagation (forward) method is also remarkably simple: it chains each module in the list together, passing the output of each as input to the next. Note that until now, we have been invoking our models via the construction net(X) to obtain their outputs. This is actually just shorthand for net.__call__(X).英語のヒント
この例では、実行すべき順に並べた層を引数として渡して
nn.Sequentialをインスタンス化することで、モデルを組み立てた。要するに、nn.Sequentialは、PyTorchでモジュールを表すクラスであるModuleの特別な種類を定義する。それは、構成するModuleの順序付きのリストを保持する。二つの全結合層はどちらもLinearクラスのインスタンスであり、そのクラス自体がModuleのサブクラスであることに注意してほしい。順伝播(forward)のメソッドも驚くほど単純である。リストの各モジュールを鎖のようにつなぎ、それぞれの出力を次への入力として渡すのである。これまで、出力を得るためにnet(X)という書き方でモデルを呼び出してきたことに注意してほしい。これは実はnet.__call__(X)の省略形にすぎない。