プリンキピア

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

9.5.5. Decoding9.5.5 復号

Once a language model has been learned, we can use it not only to predict the next token but to continue predicting each subsequent one, treating the previously predicted token as though it were the next in the input. Sometimes we will just want to generate text as though we were starting at the beginning of a document. However, it is often useful to condition the language model on a user-supplied prefix. For example, if we were developing an autocomplete feature for a search engine or to assist users in writing emails, we would want to feed in what they had written so far (the prefix), and then generate a likely continuation.
英語のヒント
言語モデルを学習したら、それを使って次のトークンを予測するだけでなく、前に予測したトークンを入力の次のトークンであるかのように扱って、続く各トークンを予測し続けられる。ときには、文書の初めから始めるかのように、単にテキストを生成したいこともある。しかし、ユーザーが与える最初の部分を言語モデルの条件とすることが役に立つことも多い。たとえば、検索エンジンのための自動補完の機能を開発したり、ユーザーがメールを書くのを手助けしたりする場合には、ユーザーがそれまでに書いたもの(最初の部分)を入れ、ありそうな続きを生成したいだろう。
The following predict method generates a continuation, one character at a time, after ingesting a user-provided prefix. When looping through the characters in prefix, we keep passing the hidden state to the next time step but do not generate any output. This is called the warm-up period. After ingesting the prefix, we are now ready to begin emitting the subsequent characters, each of which will be fed back into the model as the input at the next time step.
英語のヒント
以下のpredictメソッドは、ユーザーが与えたprefixを取り込んだ後、一度に1文字ずつ続きを生成する。prefixの文字をループでたどるあいだは、隠れ状態を次の時間ステップへ渡し続けるが、出力は何も生成しない。これはウォームアップ期間と呼ばれる。最初の部分を取り込んだ後、続く文字を出し始める準備が整う。各文字は、次の時間ステップでの入力としてモデルに戻される。
@d2l.add_to_class(RNNLMScratch)  #@save
def predict(self, prefix, num_preds, vocab, device=None):
    state, outputs = None, [vocab[prefix[0]]]
    for i in range(len(prefix) + num_preds - 1):
        X = torch.tensor([[outputs[-1]]], device=device)
        embs = self.one_hot(X)
        rnn_outputs, state = self.rnn(embs, state)
        if i < len(prefix) - 1:  # Warm-up period
            outputs.append(vocab[prefix[i + 1]])
        else:  # Predict num_preds steps
            Y = self.output_layer(rnn_outputs)
            outputs.append(int(Y.argmax(axis=2).reshape(1)))
    return ''.join([vocab.idx_to_token[i] for i in outputs])
In the following, we specify the prefix and have it generate 20 additional characters.
英語のヒント
以下では、最初の部分を指定し、20個の追加の文字を生成させる。
model.predict('it has', 20, data.vocab, d2l.try_gpu())
'it has in the the the the '
While implementing the above RNN model from scratch is instructive, it is not convenient. In the next section, we will see how to leverage deep learning frameworks to whip up RNNs using standard architectures, and to reap performance gains by relying on highly optimized library functions.
英語のヒント
上のRNNのモデルをゼロから実装するのは学ぶところが多いが、便利ではない。次の節では、深層学習のフレームワークを活用して、標準的な構造を使ってRNNを手早く作り、高度に最適化されたライブラリ関数に頼って性能を上げる方法を見る。