プリンキピア

第9章リカレントニューラルネットワーク

9.5.2. RNN-Based Language Model9.5.2 RNNにもとづく言語モデル

The following RNNLMScratch class defines an RNN-based language model, where we pass in our RNN via the rnn argument of the __init__ method. When training language models, the inputs and outputs are from the same vocabulary. Hence, they have the same dimension, which is equal to the vocabulary size. Note that we use perplexity to evaluate the model. As discussed in Section 9.3.2, this ensures that sequences of different length are comparable.
英語のヒント
次のRNNLMScratchクラスは、RNNにもとづく言語モデルを定義する。ここで、RNNは__init__メソッドの引数rnnで渡す。言語モデルを訓練するとき、入力と出力は同じ語彙から来る。そのため、それらは同じ次元をもち、その次元は語彙の大きさに等しい。モデルの評価にはパープレキシティを使うことに注意してほしい。9.3.2節で論じたように、これにより長さの異なる系列を比べられるようになる。
class RNNLMScratch(d2l.Classifier):  #@save
    """The RNN-based language model implemented from scratch."""
    def __init__(self, rnn, vocab_size, lr=0.01):
        super().__init__()
        self.save_hyperparameters()
        self.init_params()

    def init_params(self):
        self.W_hq = nn.Parameter(
            torch.randn(
                self.rnn.num_hiddens, self.vocab_size) * self.rnn.sigma)
        self.b_q = nn.Parameter(torch.zeros(self.vocab_size))

    def training_step(self, batch):
        l = self.loss(self(*batch[:-1]), batch[-1])
        self.plot('ppl', torch.exp(l), train=True)
        return l

    def validation_step(self, batch):
        l = self.loss(self(*batch[:-1]), batch[-1])
        self.plot('ppl', torch.exp(l), train=False)

9.5.2.1. One-Hot Encoding9.5.2.1 ワンホット符号化

Recall that each token is represented by a numerical index indicating the position in the vocabulary of the corresponding word/character/word piece. You might be tempted to build a neural network with a single input node (at each time step), where the index could be fed in as a scalar value. This works when we are dealing with numerical inputs like price or temperature, where any two values sufficiently close together should be treated similarly. But this does not quite make sense. The 45th and 46th words in our vocabulary happen to be “their” and “said”, whose meanings are not remotely similar.
英語のヒント
各トークンは、対応する単語・文字・単語の断片の語彙の中での位置を示す数値のインデックスで表されることを思い出そう。(各時間ステップで)入力ノードが一つのニューラルネットワークを作り、インデックスをスカラー値として入れたくなるかもしれない。これは、価格や温度のような数値の入力を扱うときにはうまくいく。そこでは、十分に近い二つの値は似たように扱われるべきだからである。しかし、これはあまり意味をなさない。語彙の45thと46thの単語はたまたま「their」と「said」だが、その意味はまったく似ていない。
When dealing with such categorical data, the most common strategy is to represent each item by a one-hot encoding (recall from Section 4.1.1). A one-hot encoding is a vector whose length is given by the size of the vocabulary N, where all entries are set to 0, except for the entry corresponding to our token, which is set to 1. For example, if the vocabulary had five elements, then the one-hot vectors corresponding to indices 0 and 2 would be the following.
英語のヒント
こうしたカテゴリカルなデータを扱うとき、最もよくある戦略は、各項目をワンホット符号化で表すことである(4.1.1節を思い出そう)。ワンホット符号化は、長さが語彙の大きさNで与えられるベクトルであり、トークンに対応する要素は1に設定され、それ以外のすべての要素は0に設定される。たとえば、語彙に要素が五つあれば、インデックス0と2に対応するワンホットベクトルは次のようになる。
F.one_hot(torch.tensor([0, 2]), 5)
tensor([[1, 0, 0, 0, 0],
        [0, 0, 1, 0, 0]])
The minibatches that we sample at each iteration will take the shape (batch size, number of time steps). Once representing each input as a one-hot vector, we can think of each minibatch as a three-dimensional tensor, where the length along the third axis is given by the vocabulary size (len(vocab)). We often transpose the input so that we will obtain an output of shape (number of time steps, batch size, vocabulary size). This will allow us to loop more conveniently through the outermost dimension for updating hidden states of a minibatch, time step by time step (e.g., in the above forward method).
英語のヒント
各反復でサンプリングするミニバッチは、(バッチサイズ、時間ステップの数)という形状をとる。各入力をワンホットベクトルで表せば、各ミニバッチは3次元のテンソルとみなせる。その3番目の軸に沿った長さは語彙の大きさ(len(vocab))で与えられる。入力はしばしば転置し、(時間ステップの数、バッチサイズ、語彙の大きさ)という形状の出力が得られるようにする。これにより、ミニバッチの隠れ状態を時間ステップごとに更新するために、一番外側の次元をもっと便利にループでたどれる(たとえば上のforwardメソッドで)。
@d2l.add_to_class(RNNLMScratch)  #@save
def one_hot(self, X):
    # Output shape: (num_steps, batch_size, vocab_size)
    return F.one_hot(X.T, self.vocab_size).type(torch.float32)

9.5.2.2. Transforming RNN Outputs9.5.2.2 RNNの出力を変換する

The language model uses a fully connected output layer to transform RNN outputs into token predictions at each time step.
英語のヒント
言語モデルは、全結合の出力層を使って、各時間ステップでRNNの出力をトークンの予測に変換する。
@d2l.add_to_class(RNNLMScratch)  #@save
def output_layer(self, rnn_outputs):
    outputs = [torch.matmul(H, self.W_hq) + self.b_q for H in rnn_outputs]
    return torch.stack(outputs, 1)

@d2l.add_to_class(RNNLMScratch)  #@save
def forward(self, X, state=None):
    embs = self.one_hot(X)
    rnn_outputs, _ = self.rnn(embs, state)
    return self.output_layer(rnn_outputs)
Let’s check whether the forward computation produces outputs with the correct shape.
英語のヒント
順方向の計算が正しい形状の出力を出すかどうか確認しよう。
model = RNNLMScratch(rnn, num_inputs)
outputs = model(torch.ones((batch_size, num_steps), dtype=torch.int64))
check_shape(outputs, (batch_size, num_steps, num_inputs))