プリンキピア

第15章自然言語処理:事前学習

15.9.1. Defining Helper Functions for Pretraining Tasks15.9.1 事前学習のタスクのための補助関数を定義する

In the following, we begin by implementing helper functions for the two BERT pretraining tasks: next sentence prediction and masked language modeling. These helper functions will be invoked later when transforming the raw text corpus into the dataset of the ideal format to pretrain BERT.
英語のヒント
以下では、まず二つのBERTの事前学習のタスク、つまり次文予測とマスク言語モデリングのための補助関数を実装する。これらの補助関数は、後で、生のテキストコーパスをBERTの事前学習に理想的な形式のデータセットに変換するときに呼び出す。

15.9.1.1. Generating the Next Sentence Prediction Task15.9.1.1 次文予測のタスクを生成する

According to descriptions of Section 15.8.5.2, the _get_next_sentence function generates a training example for the binary classification task.
英語のヒント
15.8.5.2節の説明に従って、_get_next_sentence関数は、二値分類のタスクのための訓練事例を生成する。
#@save
def _get_next_sentence(sentence, next_sentence, paragraphs):
    if random.random() < 0.5:
        is_next = True
    else:
        # `paragraphs` is a list of lists of lists
        next_sentence = random.choice(random.choice(paragraphs))
        is_next = False
    return sentence, next_sentence, is_next
The following function generates training examples for next sentence prediction from the input paragraph by invoking the _get_next_sentence function. Here paragraph is a list of sentences, where each sentence is a list of tokens. The argument max_len specifies the maximum length of a BERT input sequence during pretraining.
英語のヒント
次の関数は、_get_next_sentence関数を呼び出して、入力paragraphから次文予測のための訓練事例を生成する。ここで、paragraphは文のリストで、各文はトークンのリストである。引数max_lenは、事前学習のあいだのBERTの入力系列の最大の長さを指定する。
#@save
def _get_nsp_data_from_paragraph(paragraph, paragraphs, vocab, max_len):
    nsp_data_from_paragraph = []
    for i in range(len(paragraph) - 1):
        tokens_a, tokens_b, is_next = _get_next_sentence(
            paragraph[i], paragraph[i + 1], paragraphs)
        # Consider 1 '<cls>' token and 2 '<sep>' tokens
        if len(tokens_a) + len(tokens_b) + 3 > max_len:
            continue
        tokens, segments = d2l.get_tokens_and_segments(tokens_a, tokens_b)
        nsp_data_from_paragraph.append((tokens, segments, is_next))
    return nsp_data_from_paragraph

15.9.1.2. Generating the Masked Language Modeling Task15.9.1.2 マスク言語モデリングのタスクを生成する

In order to generate training examples for the masked language modeling task from a BERT input sequence, we define the following _replace_mlm_tokens function. In its inputs, tokens is a list of tokens representing a BERT input sequence, candidate_pred_positions is a list of token indices of the BERT input sequence excluding those of special tokens (special tokens are not predicted in the masked language modeling task), and num_mlm_preds indicates the number of predictions (recall 15% random tokens to predict). Following the definition of the masked language modeling task in Section 15.8.5.1, at each prediction position, the input may be replaced by a special “<mask>” token or a random token, or remain unchanged. In the end, the function returns the input tokens after possible replacement, the token indices where predictions take place and labels for these predictions.
英語のヒント
BERTの入力系列からマスク言語モデリングのタスクのための訓練事例を生成するため、次の_replace_mlm_tokens関数を定義する。その入力のうち、tokensはBERTの入力系列を表すトークンのリスト、candidate_pred_positionsは特殊トークンのものを除いたBERTの入力系列のトークンのインデックスのリスト(特殊トークンはマスク言語モデリングのタスクでは予測しない)、num_mlm_predsは予測の数(予測するのはランダムなトークンの15%だったことを思い出そう)を示す。15.8.5.1節でのマスク言語モデリングのタスクの定義に従って、各予測位置で、入力は特殊な「<mask>」トークンかランダムなトークンに置き換えられるか、変わらないままになる。最後に、この関数は、置き換えがあればその後の入力トークン、予測を行うトークンのインデックス、これらの予測のラベルを返す。
#@save
def _replace_mlm_tokens(tokens, candidate_pred_positions, num_mlm_preds,
                        vocab):
    # For the input of a masked language model, make a new copy of tokens and
    # replace some of them by '<mask>' or random tokens
    mlm_input_tokens = [token for token in tokens]
    pred_positions_and_labels = []
    # Shuffle for getting 15% random tokens for prediction in the masked
    # language modeling task
    random.shuffle(candidate_pred_positions)
    for mlm_pred_position in candidate_pred_positions:
        if len(pred_positions_and_labels) >= num_mlm_preds:
            break
        masked_token = None
        # 80% of the time: replace the word with the '<mask>' token
        if random.random() < 0.8:
            masked_token = '<mask>'
        else:
            # 10% of the time: keep the word unchanged
            if random.random() < 0.5:
                masked_token = tokens[mlm_pred_position]
            # 10% of the time: replace the word with a random word
            else:
                masked_token = random.choice(vocab.idx_to_token)
        mlm_input_tokens[mlm_pred_position] = masked_token
        pred_positions_and_labels.append(
            (mlm_pred_position, tokens[mlm_pred_position]))
    return mlm_input_tokens, pred_positions_and_labels
By invoking the aforementioned _replace_mlm_tokens function, the following function takes a BERT input sequence (tokens) as an input and returns indices of the input tokens (after possible token replacement as described in Section 15.8.5.1), the token indices where predictions take place, and label indices for these predictions.
英語のヒント
前に述べた_replace_mlm_tokens関数を呼び出して、次の関数は、BERTの入力系列(tokens)を入力にとり、(15.8.5.1節で説明したトークンの置き換えがあればその後の)入力トークンのインデックス、予測を行うトークンのインデックス、これらの予測のラベルのインデックスを返す。
#@save
def _get_mlm_data_from_tokens(tokens, vocab):
    candidate_pred_positions = []
    # `tokens` is a list of strings
    for i, token in enumerate(tokens):
        # Special tokens are not predicted in the masked language modeling
        # task
        if token in ['<cls>', '<sep>']:
            continue
        candidate_pred_positions.append(i)
    # 15% of random tokens are predicted in the masked language modeling task
    num_mlm_preds = max(1, round(len(tokens) * 0.15))
    mlm_input_tokens, pred_positions_and_labels = _replace_mlm_tokens(
        tokens, candidate_pred_positions, num_mlm_preds, vocab)
    pred_positions_and_labels = sorted(pred_positions_and_labels,
                                       key=lambda x: x[0])
    pred_positions = [v[0] for v in pred_positions_and_labels]
    mlm_pred_labels = [v[1] for v in pred_positions_and_labels]
    return vocab[mlm_input_tokens], pred_positions, vocab[mlm_pred_labels]