プリンキピア

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

15.6.2. Byte Pair Encoding15.6.2 バイト対符号化

In fastText, all the extracted subwords have to be of the specified lengths, such as 3 to 6, thus the vocabulary size cannot be predefined. To allow for variable-length subwords in a fixed-size vocabulary, we can apply a compression algorithm called byte pair encoding (BPE) to extract subwords (Sennrich et al., 2015).
英語のヒント
fastTextでは、抽出するサブワードはすべて、3から6のような決められた長さでなければならず、そのため語彙の大きさをあらかじめ決めることができない。固定された大きさの語彙で可変長のサブワードを扱えるようにするため、バイト対符号化(BPE)と呼ばれる圧縮アルゴリズムを当てはめてサブワードを抽出できる(Sennrich et al., 2015)。
Byte pair encoding performs a statistical analysis of the training dataset to discover common symbols within a word, such as consecutive characters of arbitrary length. Starting from symbols of length 1, byte pair encoding iteratively merges the most frequent pair of consecutive symbols to produce new longer symbols. Note that for efficiency, pairs crossing word boundaries are not considered. In the end, we can use such symbols as subwords to segment words. Byte pair encoding and its variants has been used for input representations in popular natural language processing pretraining models such as GPT-2 (Radford et al., 2019) and RoBERTa (Liu et al., 2019). In the following, we will illustrate how byte pair encoding works.
英語のヒント
バイト対符号化は、訓練データセットを統計的に分析して、任意の長さの連続した文字のような、単語の中でよく現れる記号を見つける。長さ1の記号から始めて、バイト対符号化は、最も頻度の高い連続した記号の対を反復して併合し、新しいもっと長い記号を作る。効率のため、単語の境界をまたぐ対は考えないことに注意しよう。最後に、そうした記号をサブワードとして使って単語を分割できる。バイト対符号化とその変種は、GPT-2(Radford et al., 2019)やRoBERTa(Liu et al., 2019)のような、よく使われる自然言語処理の事前学習モデルの入力表現に使われてきた。以下では、バイト対符号化がどう働くかを示す。
First, we initialize the vocabulary of symbols as all the English lowercase characters, a special end-of-word symbol '_', and a special unknown symbol '[UNK]'.
英語のヒント
まず、記号の語彙を、英語の小文字すべてと、単語の終わりを表す特殊記号'_'と、未知を表す特殊記号'[UNK]'に初期化する。
import collections

symbols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
           'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
           '_', '[UNK]']
Since we do not consider symbol pairs that cross boundaries of words, we only need a dictionary raw_token_freqs that maps words to their frequencies (number of occurrences) in a dataset. Note that the special symbol '_' is appended to each word so that we can easily recover a word sequence (e.g., “a taller man”) from a sequence of output symbols ( e.g., “a_ tall er_ man”). Since we start the merging process from a vocabulary of only single characters and special symbols, space is inserted between every pair of consecutive characters within each word (keys of the dictionary token_freqs). In other words, space is the delimiter between symbols within a word.
英語のヒント
単語の境界をまたぐ記号の対は考えないので、データセットでの単語をその頻度(出現回数)に対応させる辞書raw_token_freqsがあればよい。出力記号の系列(たとえば「a_ tall er_ man」)から単語の系列(たとえば「a taller man」)を簡単に復元できるように、各単語に特殊記号'_'を付け加えることに注意しよう。併合の処理は、一つの文字と特殊記号だけからなる語彙から始めるので、各単語の中の連続した文字のすべての対の間に空白を挿入する(辞書token_freqsのキー)。言い換えると、空白は単語の中の記号どうしの区切りである。
raw_token_freqs = {'fast_': 4, 'faster_': 3, 'tall_': 5, 'taller_': 4}
token_freqs = {}
for token, freq in raw_token_freqs.items():
    token_freqs[' '.join(list(token))] = raw_token_freqs[token]
token_freqs
{'f a s t _': 4, 'f a s t e r _': 3, 't a l l _': 5, 't a l l e r _': 4}
We define the following get_max_freq_pair function that returns the most frequent pair of consecutive symbols within a word, where words come from keys of the input dictionary token_freqs.
英語のヒント
単語の中で最も頻度の高い連続した記号の対を返す、次のget_max_freq_pair関数を定義する。ここで、単語は入力の辞書token_freqsのキーから来る。
def get_max_freq_pair(token_freqs):
    pairs = collections.defaultdict(int)
    for token, freq in token_freqs.items():
        symbols = token.split()
        for i in range(len(symbols) - 1):
            # Key of `pairs` is a tuple of two consecutive symbols
            pairs[symbols[i], symbols[i + 1]] += freq
    return max(pairs, key=pairs.get)  # Key of `pairs` with the max value
As a greedy approach based on frequency of consecutive symbols, byte pair encoding will use the following merge_symbols function to merge the most frequent pair of consecutive symbols to produce new symbols.
英語のヒント
連続した記号の頻度にもとづく貪欲なやり方として、バイト対符号化は次のmerge_symbols関数を使い、最も頻度の高い連続した記号の対を併合して新しい記号を作る。
def merge_symbols(max_freq_pair, token_freqs, symbols):
    symbols.append(''.join(max_freq_pair))
    new_token_freqs = dict()
    for token, freq in token_freqs.items():
        new_token = token.replace(' '.join(max_freq_pair),
                                  ''.join(max_freq_pair))
        new_token_freqs[new_token] = token_freqs[token]
    return new_token_freqs
Now we iteratively perform the byte pair encoding algorithm over the keys of the dictionary token_freqs. In the first iteration, the most frequent pair of consecutive symbols are 't' and 'a', thus byte pair encoding merges them to produce a new symbol 'ta'. In the second iteration, byte pair encoding continues to merge 'ta' and 'l' to result in another new symbol 'tal'.
英語のヒント
では、辞書token_freqsのキーに対して、バイト対符号化のアルゴリズムを反復して実行しよう。1回目の反復では、最も頻度の高い連続した記号の対は't'と'a'なので、バイト対符号化はそれらを併合して新しい記号'ta'を作る。2回目の反復では、バイト対符号化は続けて'ta'と'l'を併合し、別の新しい記号'tal'を作る。
num_merges = 10
for i in range(num_merges):
    max_freq_pair = get_max_freq_pair(token_freqs)
    token_freqs = merge_symbols(max_freq_pair, token_freqs, symbols)
    print(f'merge #{i + 1}:', max_freq_pair)
merge #1: ('t', 'a')
merge #2: ('ta', 'l')
merge #3: ('tal', 'l')
merge #4: ('f', 'a')
merge #5: ('fa', 's')
merge #6: ('fas', 't')
merge #7: ('e', 'r')
merge #8: ('er', '_')
merge #9: ('tall', '_')
merge #10: ('fast', '_')
After 10 iterations of byte pair encoding, we can see that list symbols now contains 10 more symbols that are iteratively merged from other symbols.
英語のヒント
バイト対符号化を10回反復した後、リストsymbolsには、ほかの記号から反復して併合された記号が10個増えていることがわかる。
print(symbols)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '_', '[UNK]', 'ta', 'tal', 'tall', 'fa', 'fas', 'fast', 'er', 'er_', 'tall_', 'fast_']
For the same dataset specified in the keys of the dictionary raw_token_freqs, each word in the dataset is now segmented by subwords “fast_”, “fast”, “er_”, “tall_”, and “tall” as a result of the byte pair encoding algorithm. For instance, words “faster_” and “taller_” are segmented as “fast er_” and “tall er_”, respectively.
英語のヒント
辞書raw_token_freqsのキーで指定した同じデータセットについて、バイト対符号化のアルゴリズムの結果、データセットの各単語は、いまやサブワード「fast_」「fast」「er_」「tall_」「tall」で分割される。たとえば、単語「faster_」と「taller_」は、それぞれ「fast er_」と「tall er_」と分割される。
print(list(token_freqs.keys()))
['fast_', 'fast er_', 'tall_', 'tall er_']
Note that the result of byte pair encoding depends on the dataset being used. We can also use the subwords learned from one dataset to segment words of another dataset. As a greedy approach, the following segment_BPE function tries to break words into the longest possible subwords from the input argument symbols.
英語のヒント
バイト対符号化の結果は、使うデータセットによって変わることに注意しよう。あるデータセットから学習したサブワードを使って、別のデータセットの単語を分割することもできる。貪欲なやり方として、次のsegment_BPE関数は、入力の引数symbolsから、できるだけ長いサブワードに単語を分けようとする。
def segment_BPE(tokens, symbols):
    outputs = []
    for token in tokens:
        start, end = 0, len(token)
        cur_output = []
        # Segment token with the longest possible subwords from symbols
        while start < len(token) and start < end:
            if token[start: end] in symbols:
                cur_output.append(token[start: end])
                start = end
                end = len(token)
            else:
                end -= 1
        if start < len(token):
            cur_output.append('[UNK]')
        outputs.append(' '.join(cur_output))
    return outputs
In the following, we use the subwords in list symbols, which is learned from the aforementioned dataset, to segment tokens that represent another dataset.
英語のヒント
以下では、前に述べたデータセットから学習したリストsymbolsのサブワードを使って、別のデータセットを表すトークンtokensを分割する。
tokens = ['tallest_', 'fatter_']
print(segment_BPE(tokens, symbols))
['tall e s t _', 'fa t t er_']