第15章自然言語処理:事前学習
15.8.4. Input Representation15.8.4 入力表現
In natural language processing, some tasks (e.g., sentiment analysis) take single text as input, while in some other tasks (e.g., natural language inference), the input is a pair of text sequences. The BERT input sequence unambiguously represents both single text and text pairs. In the former, the BERT input sequence is the concatenation of the special classification token “<cls>”, tokens of a text sequence, and the special separation token “<sep>”. In the latter, the BERT input sequence is the concatenation of “<cls>”, tokens of the first text sequence, “<sep>”, tokens of the second text sequence, and “<sep>”. We will consistently distinguish the terminology “BERT input sequence” from other types of “sequences”. For instance, one BERT input sequence may include either one text sequence or two text sequences.
英語のヒント
自然言語処理では、単一のテキストを入力にとるタスク(たとえば感情分析)もあれば、入力がテキストの系列の対であるタスク(たとえば自然言語推論)もある。BERTの入力系列は、単一のテキストもテキストの対も、あいまいさなく表す。前者では、BERTの入力系列は、分類用の特殊トークン「<cls>」、テキストの系列のトークン、区切り用の特殊トークン「<sep>」を連結したものである。後者では、BERTの入力系列は、「<cls>」、一つ目のテキストの系列のトークン、「<sep>」、二つ目のテキストの系列のトークン、「<sep>」を連結したものである。「BERTの入力系列」という用語は、ほかの種類の「系列」と一貫して区別する。たとえば、一つのBERTの入力系列は、一つのテキストの系列を含むことも、二つのテキストの系列を含むこともある。
To distinguish text pairs, the learned segment embeddings and are added to the token embeddings of the first sequence and the second sequence, respectively. For single text inputs, only is used.
英語のヒント
テキストの対を区別するため、学習したセグメント埋め込みとを、それぞれ一つ目の系列と二つ目の系列のトークン埋め込みに加える。単一のテキストの入力では、だけを使う。
The following
get_tokens_and_segments takes either one sentence or two sentences as input, then returns tokens of the BERT input sequence and their corresponding segment IDs.英語のヒント
次の
get_tokens_and_segmentsは、一つの文か二つの文を入力にとり、BERTの入力系列のトークンと、それに対応するセグメントIDを返す。#@save
def get_tokens_and_segments(tokens_a, tokens_b=None):
"""Get tokens of the BERT input sequence and their segment IDs."""
tokens = ['<cls>'] + tokens_a + ['<sep>']
# 0 and 1 are marking segment A and B, respectively
segments = [0] * (len(tokens_a) + 2)
if tokens_b is not None:
tokens += tokens_b + ['<sep>']
segments += [1] * (len(tokens_b) + 1)
return tokens, segmentsBERT chooses the Transformer encoder as its bidirectional architecture. Common in the Transformer encoder, positional embeddings are added at every position of the BERT input sequence. However, different from the original Transformer encoder, BERT uses learnable positional embeddings. To sum up, Fig. 15.8.2 shows that the embeddings of the BERT input sequence are the sum of the token embeddings, segment embeddings, and positional embeddings.
英語のヒント
BERTは、その双方向のアーキテクチャとしてTransformerのエンコーダを選ぶ。Transformerのエンコーダでふつうに行われるように、BERTの入力系列のすべての位置に位置埋め込みを加える。しかし、元のTransformerのエンコーダとは違って、BERTは学習可能な位置埋め込みを使う。まとめると、図15.8.2が示すように、BERTの入力系列の埋め込みは、トークン埋め込み、セグメント埋め込み、位置埋め込みの和である。
Fig. 15.8.2図15.8.2
The embeddings of the BERT input sequence are the sum of the token embeddings, segment embeddings, and positional embeddings.
英語のヒント
BERTの入力系列の埋め込みは、トークン埋め込み、セグメント埋め込み、位置埋め込みの和である。
The following
BERTEncoder class is similar to the TransformerEncoder class as implemented in Section 11.7. Different from TransformerEncoder, BERTEncoder uses segment embeddings and learnable positional embeddings.英語のヒント
次の
BERTEncoderクラスは、11.7節で実装したTransformerEncoderクラスに似ている。TransformerEncoderとは違って、BERTEncoderはセグメント埋め込みと学習可能な位置埋め込みを使う。#@save
class BERTEncoder(nn.Module):
"""BERT encoder."""
def __init__(self, vocab_size, num_hiddens, ffn_num_hiddens, num_heads,
num_blks, dropout, max_len=1000, **kwargs):
super(BERTEncoder, self).__init__(**kwargs)
self.token_embedding = nn.Embedding(vocab_size, num_hiddens)
self.segment_embedding = nn.Embedding(2, num_hiddens)
self.blks = nn.Sequential()
for i in range(num_blks):
self.blks.add_module(f"{i}", d2l.TransformerEncoderBlock(
num_hiddens, ffn_num_hiddens, num_heads, dropout, True))
# In BERT, positional embeddings are learnable, thus we create a
# parameter of positional embeddings that are long enough
self.pos_embedding = nn.Parameter(torch.randn(1, max_len,
num_hiddens))
def forward(self, tokens, segments, valid_lens):
# Shape of `X` remains unchanged in the following code snippet:
# (batch size, max sequence length, `num_hiddens`)
X = self.token_embedding(tokens) + self.segment_embedding(segments)
X = X + self.pos_embedding[:, :X.shape[1], :]
for blk in self.blks:
X = blk(X, valid_lens)
return XSuppose that the vocabulary size is 10000. To demonstrate forward inference of
BERTEncoder, let’s create an instance of it and initialize its parameters.英語のヒント
語彙の大きさが10000だとしよう。
BERTEncoderの順伝播による推論を示すため、そのインスタンスを作って、パラメータを初期化しよう。vocab_size, num_hiddens, ffn_num_hiddens, num_heads = 10000, 768, 1024, 4
ffn_num_input, num_blks, dropout = 768, 2, 0.2
encoder = BERTEncoder(vocab_size, num_hiddens, ffn_num_hiddens, num_heads,
num_blks, dropout)We define
tokens to be 2 BERT input sequences of length 8, where each token is an index of the vocabulary. The forward inference of BERTEncoder with the input tokens returns the encoded result where each token is represented by a vector whose length is predefined by the hyperparameter num_hiddens. This hyperparameter is usually referred to as the hidden size (number of hidden units) of the Transformer encoder.英語のヒント
tokensを、長さ8の二つのBERTの入力系列と定める。ここで、各トークンは語彙のインデックスである。入力tokensを使ったBERTEncoderの順伝播による推論は、符号化した結果を返す。そこでは、各トークンは、長さがハイパーパラメータnum_hiddensであらかじめ決められたベクトルで表される。このハイパーパラメータは、ふつうTransformerのエンコーダの隠れ層の大きさ(隠れユニットの数)と呼ばれる。tokens = torch.randint(0, vocab_size, (2, 8))
segments = torch.tensor([[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 1]])
encoded_X = encoder(tokens, segments, None)
encoded_X.shapetorch.Size([2, 8, 768])