プリンキピア

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

6.6.2. Loading and Saving Model Parameters6.6.2 モデルのパラメータの読み込みと保存

Saving individual weight vectors (or other tensors) is useful, but it gets very tedious if we want to save (and later load) an entire model. After all, we might have hundreds of parameter groups sprinkled throughout. For this reason the deep learning framework provides built-in functionalities to load and save entire networks. An important detail to note is that this saves model parameters and not the entire model. For example, if we have a 3-layer MLP, we need to specify the architecture separately. The reason for this is that the models themselves can contain arbitrary code, hence they cannot be serialized as naturally. Thus, in order to reinstate a model, we need to generate the architecture in code and then load the parameters from disk. Let’s start with our familiar MLP.
英語のヒント
個々の重みベクトル(やほかのテンソル)を保存するのは役に立つが、モデル全体を保存し(後で読み込み)たいときには、とても面倒になる。何しろ、パラメータのまとまりが何百も、あちこちに散らばっているかもしれないのである。そのため、深層学習のフレームワークは、ネットワーク全体を読み込み、保存する組み込みの機能を提供している。注意すべき重要な細部は、これが保存するのはモデルのパラメータであって、モデル全体ではないことである。たとえば、3層のMLPがあるなら、構造は別に指定する必要がある。その理由は、モデルそのものは任意のコードを含みうるので、それほど自然には直列化できないからである。したがって、モデルを復元するには、構造をコードで生成し、それからディスクからパラメータを読み込む必要がある。おなじみのMLPから始めよう。
class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.LazyLinear(256)
        self.output = nn.LazyLinear(10)

    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))

net = MLP()
X = torch.randn(size=(2, 20))
Y = net(X)
Next, we store the parameters of the model as a file with the name “mlp.params”.
英語のヒント
次に、モデルのパラメータを「mlp.params」という名前のファイルとして保存する。
torch.save(net.state_dict(), 'mlp.params')
To recover the model, we instantiate a clone of the original MLP model. Instead of randomly initializing the model parameters, we read the parameters stored in the file directly.
英語のヒント
モデルを復元するには、元のMLPモデルの複製をインスタンス化する。モデルのパラメータを無作為に初期化する代わりに、ファイルに保存したパラメータを直接読み込む。
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()
MLP(
  (hidden): LazyLinear(in_features=0, out_features=256, bias=True)
  (output): LazyLinear(in_features=0, out_features=10, bias=True)
)
Since both instances have the same model parameters, the computational result of the same input X should be the same. Let’s verify this.
英語のヒント
両方のインスタンスは同じモデルのパラメータをもつので、同じ入力Xに対する計算結果は同じになるはずである。確かめてみよう。
Y_clone = clone(X)
Y_clone == Y
tensor([[True, True, True, True, True, True, True, True, True, True],
        [True, True, True, True, True, True, True, True, True, True]])