How BERT Training Data Is Made

From raw text to a training instance.

From Raw Text to BERT Training Instances

BERT achieved state-of-the-art results across many NLP tasks. This post focuses on preparing its training data rather than reviewing the architecture or performance, so familiarity with the model will help. An introduction is available here.

These notes follow the NVIDIA BERT code.


From raw text to an instance

BERT trains on an input structured like this. We'll turn human language into that format.

BERT’s paired-sequence input and masked-token objective.

1. Bytes to Unicode

Content collected with urllib arrives as bytes. Decoding turns it into text we can inspect. The original examples discuss UTF-8 on Linux and CP949 in a Windows environment. Here are the bytes retrieved from this post, followed by the decoded text. Crawled internet text is often a source for language-model pretraining, especially when cleaned Korean datasets are scarce.

A byte-encoded response from a crawled webpage.
A byte-encoded response from a crawled webpage.
The same response decoded into readable text.
The same webpage decoded into Korean text. The passage describes batch echoing: load 512 items, train on two groups of 256, shuffle the 512 items, split again, and train on both groups a second time. This uses each batch twice.

Python provides the convenient built-in decode method.

import six

def convert_to_unicode(text):

    if six.PY3:
        if isinstance(text, str):
            return text
        elif isinstance(text, bytes):
            return text.decode("utf-8", "ignore")  # Deocde
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    else:
        raise ValueError("Not running on Python 3?")
        

2. Raw data to plain text

Raw data contains more than the text we want: metadata, markup, and other symbols. Examples include the National Institute of Korean Language newspaper corpus, Namuwiki dumps, and Korean Wikipedia.

Formats vary, including JSON and compressed archives, and files are often large. The first step is to extract only what we want to train on. That's parsing; here, the target is plain text. The right method depends on the task and training setup. This is simply my choice, but some form of this step is necessary.

There are three broad stages:

  • Clean the data.
  • Remove or transform unwanted parts.
  • Add information needed later in training.
수학</a></b>에서 <b>상수</b>란 그 값이 변하지 않는 불변량으로, <a href="/wiki/%EB%B3%80%EC%88%98_(%EC%88%98%ED%95%99)" title="변수 (수학)">변수</a>의 반대말이다. <a href="/wiki/%EB%AC%BC%EB%A6%AC_%EC%83%81%EC%88%98" title="물리 상수">물리 상수</a>와는 달리, 수학 상수는 물리적 측정과는 상관없이 정의된다.
</p><p>수학 상수는 대개 <a href="/wiki/%EC%8B%A4%EC%88%98%EC%B2%B4" class="mw-redirect" title="실수체">실수체</a>나 <a href="/wiki/%EB%B3%B5%EC%86%8C%EC%88%98%EC%B2%B4" class="mw-redirect" title="복소수체">복소수체</a>의 원소이다. 우리가 이야기할 수 있는 상수는 (거의 대부분 <a href="/wiki/%EA%B3%84%EC%82%B0_%EA%B0%80%EB%8A%A5%ED%95%9C_%EC%88%98" title="계산 가능한 수">계산 가능</a>한) <a href="/wiki/%EC%A0%95%EC%9D%98%EA%B0%80%EB%8A%A5%ED%95%9C_%EC%88%98" class="mw-redirect" title="정의가능한 수">정의가능한 수</a>이다.
</p><p>특정 수학 상수, 예를 들면 <a href="/wiki/%EA%B3%A8%EB%A1%AC-%EB%94%95%EB%A7%A8_%EC%83%81%EC%88%98" title="골롬-딕맨 상수">골롬-딕맨 상수</a>, <a href="/wiki/%ED%94%84%EB%9E%91%EC%84%B8%EC%A6%88-%EB%A1%9C%EB%B9%88%EC%8A%A8_%EC%83%81%EC%88%98" title="프랑세즈-로빈슨 상수">프랑세즈-로빈슨 상수</a>, <a href="/wiki/%EC%A0%9C%EA%B3%B1%EA%B7%BC_2" title="제곱근 2"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="display: none;"><math xmlns="http://www.w3.org/1998/Math/MathML"  alttext="{\displaystyle {\sqrt {2}}}">
  <semantics>
    <mrow class="MJX-TeXAtom-ORD">
      <mstyle displaystyle="true" scriptlevel="0">
        <mrow class="MJX-TeXAtom-ORD">
          <msqrt>
            <mn>2</mn>
          </msqrt>
        </mrow>
      </mstyle>
    </mrow>
    <annotation encoding="application/x-tex">{\displaystyle {\sqrt {2}}}</annotation>
  </semantics>
</math></span><img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/b4afc1e27d418021bf10898eb44a7f5f315735ff" class="mwe-math-fallback-image-inline" aria-hidden="true" style="vertical-align: -0.671ex; width:3.098ex; height:3.009ex;" alt="{\sqrt {2}}"/></span></a>, <a href="/wiki/%EB%A0%88%EB%B9%84_%EC%83%81%EC%88%98" title="레비 상수">레비 상수</a>와 같은 상수는 다른 수학상수 또는 함수와 약한 상관관계 또는 강한 상관관계를 갖는다.
</p>
<div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading"><input type="checkbox" role="button" id="toctogglecheckbox" class="toctogglecheckbox" style="display:none" /><div class="toctitle" lang="ko" dir="ltr"><h2 id="mw-toc-heading">목차</h2><span class="toctogglespan"><label class="toctogglelabel" for="toctogglecheckbox"></label></span></div>
<ul>
<li class="toclevel-1 tocsection-1"><a href="#수학_상수표"><span class="tocnumber">1</span> <span class="toctext">수학 상수표</span></a></li>
<li class="toclevel-1 tocsection-2"><a href="#관련_상수들"><span class="tocnumber">2</span> <span class="toctext">관련 상수들</span></a>
<ul>
<li class="toclevel-2 tocsection-3"><a href="#e_관련"><span class="tocnumber">2.1</span> <span class="toctext">e 관련</span></a></li>
<li class="toclevel-2 tocsection-4"><a href="#감마함수_관련"><span class="tocnumber">2.2</span> <span class="toctext">감마함수 관련</span></a></li>
<li class="toclevel-2 tocsection-5"><a href="#소수_관련"><span class="tocnumber">2.3</span> <span class="toctext">소수 관련</span></a></li>
<li class="toclevel-2 tocsection-6"><a href="#리만제타함수_관련"><span class="tocnumber">2.4</span> <span class="toctext">리만제타함수 관련</span></a></li>
<li class="toclevel-2 tocsection-7"><a href="#피보나치_수_관련"><span class="tocnumber">2.5</span> <span class="toctext">피보나치 수 관련</span></a></li>
<li class="toclevel-2 tocsection-8"><a href="#특정_대수방정식_관련"><span class="tocnumber">2.6</span> <span class="toctext">특정 대수방정식 관련</span></a></li>
</ul>
</li>
<li class="toclevel-1 tocsection-9"><a href="#기타_상수들"><span class="tocnumber">3</span> <span class="toctext">기타 상수들</span></a></li>
<li class="toclevel-1 tocsection-10"><a href="#같이_보기"><span class="tocnumber">4</span> <span class="toctext">같이 보기</span></a></li>
</ul>
</div>

Consider this raw excerpt from Korean Wikipedia's mathematical constants article. It contains a great deal of HTML. We need to extract the language itself.

1. Clean the data.

HTML tags describe the text, but in this training setup we don't need them. Removing that markup gives us the following.

# Article: 수학 상수
# Type: regular article

수학에서 상수란 그 값이 변하지 않는 불변량으로, 변수의 반대말이다. 물리 상수와는 달리, 수학 상수는 물리적 측정과는 상관없이 정의된다.

수학 상수는 대개 실수체나 복소수체의 원소이다. 우리가 이야기할 수 있는 상수는 (거의 대부분 계산 가능한) 정의가능한 수이다.

특정 수학 상수, 예를 들면 골롬-딕맨 상수, 프랑세즈-로빈슨 상수, {\displaystyle {\sqrt {2}}}{\sqrt {2}}, 레비 상수와 같은 상수는 다른 수학상수 또는 함수와 약한 상관관계 또는 강한 상관관계를 갖는다.


수학 상수표

관련 상수들

  e 관련

  감마함수 관련

  소수 관련

  리만제타함수 관련

  피보나치 수 관련

  특정 대수방정식 관련

기타 상수들

같이 보기

2. Transform the data.

The top still contains metadata such as Article and Type. I didn't think training on those fields directly was appropriate, since not every document has them. I converted them to a more ordinary arrangement, with the title above the body.

수학상수

수학에서 상수란 그 값이 변하지 않는 불변량으로, 변수의 반대말이다. 물리 상수와는 달리, 수학 상수는 물리적 측정과는 상관없이 정의된다.

수학 상수는 대개 실수체나 복소수체의 원소이다. 우리가 이야기할 수 있는 상수는 (거의 대부분 계산 가능한) 정의가능한 수이다.

특정 수학 상수, 예를 들면 골롬-딕맨 상수, 프랑세즈-로빈슨 상수, {\displaystyle {\sqrt {2}}}{\sqrt {2}}, 레비 상수와 같은 상수는 다른 수학상수 또는 함수와 약한 상관관계 또는 강한 상관관계를 갖는다.


수학 상수표

관련 상수들

  e 관련

  감마함수 관련

  소수 관련

  리만제타함수 관련

  피보나치 수 관련

  특정 대수방정식 관련

기타 상수들

같이 보기

3. Add training information.

BERT's preparation needs document and sentence boundaries. We add separators, which are removed during training. I also added chapter boundaries in case I needed them. That produces the final plain text below.

[DOC_SEP]

[CH_SEP]
수학에서 상수란 그 값이 변하지 않는 불변량으로, 변수의 반대말이다.[SEN_SEP]물리 상수와는 달리, 수학 상수는 물리적 측정과는 상관없이 정의된다.[SEN_SEP]

수학 상수는 대개 실수체나 복소수체의 원소이다.[SEN_SEP]우리가 이야기할 수 있는 상수는 (거의 대부분 계산 가능한) 정의가능한 수이다.[SEN_SEP]

특정 수학 상수, 예를 들면 골롬-딕맨 상수, 프랑세즈-로빈슨 상수, {\displaystyle {\sqrt {2}}}{\sqrt {2}}, 레비 상수와 같은 상수는 다른 수학상수 또는 함수와 약한 상관관계 또는 강한 상관관계를 갖는다.[SEN_SEP]

[CH_SEP]
수학 상수표[SEN_SEP]

관련 상수들[SEN_SEP]

  e 관련[SEN_SEP]

  감마함수 관련[SEN_SEP]

  소수 관련[SEN_SEP]

  리만제타함수 관련[SEN_SEP]

  피보나치 수 관련[SEN_SEP]

  특정 대수방정식 관련[SEN_SEP]

기타 상수들[SEN_SEP]

같이 보기[SEN_SEP]

3. Plain text to shards

Sharding splits text into multiple files. It makes multiprocessing easier and helps mix data.

Here, mixing means putting text from several sources into one shard. A general language model shouldn't encounter entire sources one after another and overfit to each. With kowiki.txt, namuwiki.txt, and newspaper.txt, I mixed a little from each into smaller text files.

Mixing text from several source files into shards.
Mixing text from several source files into shards.
An example of text distributed across mixed-source shards.
An example of text distributed across mixed-source shards.

4. Plain text to tokens

4.1 Basic tokenizer

Before subword tokenization, clean the text:

  • Split it using document boundaries, shown as [DOC_SEP] in the example.
  • Remove invalid characters and normalize whitespace to spaces.
import unicodedata
    
    
def clean_text(text):
    """Performs invalid character removal and whitespace cleanup on text."""
    output = []
    for char in text:
        cp = ord(char)
        if cp == 0 or cp == 0xfffd or is_control(char):
            continue
        if is_whitespace(char):
            output.append(" ")
        else:
            output.append(char)
    return "".join(output)
        
 
 def is_whitespace(char):
    """Checks whether `chars` is a whitespace character."""
    # \t, \n, and \r are technically control characters but we treat them
    # as whitespace since they are generally considered as such.
    if char == " " or char == "\t" or char == "\n" or char == "\r":
        return True
    cat = unicodedata.category(char)
    if cat == "Zs":
        return True
    return False


def _is_control(char):
    """Checks whether `chars` is a control character."""
    # These are technically control characters but we count them as whitespace
    # characters.
    if char == "\t" or char == "\n" or char == "\r":
        return False
    cat = unicodedata.category(char)
    if cat.startswith("C"):
        return True
    return False

Handle language-specific cases. For Chinese characters, add spaces around individual characters before the subsequent tokenization step.

def tokenize_chinese_chars(text):
    """Adds whitespace around any CJK character."""
    
    output = []
    for char in text:
        cp = ord(char)
        if _is_chinese_char(cp):
            output.append(" ")
            output.append(char)
            output.append(" ")
        else:
            output.append(char)
            
    return "".join(output)
    
    
def is_chinese_char(cp):
    """Checks whether CP is the codepoint of a CJK character."""
    # This defines a "chinese character" as anything in the CJK Unicode block:
    #   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
    #
    # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
    # despite its name. The modern Korean Hangul alphabet is a different block,
    # as is Japanese Hiragana and Katakana. Those alphabets are used to write
    # space-separated words, so they are not treated specially and handled
    # like the all of the other languages.
    
    if ((0x4E00 <= cp <= 0x9FFF) or
            (0x3400 <= cp <= 0x4DBF) or
            (0x20000 <= cp <= 0x2A6DF) or
            (0x2A700 <= cp <= 0x2B73F) or
            (0x2B740 <= cp <= 0x2B81F) or
            (0x2B820 <= cp <= 0x2CEAF) or
            (0xF900 <= cp <= 0xFAFF) or
            (0x2F800 <= cp <= 0x2FA1F)):
        return True
        
    return False

Separate words with punctuation in mind.

import unicodedata


def _run_split_on_punc(token):
    """Splits punctuation on a piece of text."""
    if token in self.never_split:  # Don't split
        return [token]
    chars = list(token)
    i = 0
    start_new_word = True
    output = []
    while i < len(chars):
        char = chars[i]
        if is_punctuation(char):
            output.append([char])
            start_new_word = True
        else:
            if start_new_word:
                output.append([])
            start_new_word = False
            output[-1].append(char)
        i += 1
    return ["".join(x) for x in output]
       
       
def is_punctuation(char):
    """Checks whether `chars` is a punctuation character."""
    cp = ord(char)
    # We treat all non-letter/number ASCII as punctuation.
    # Characters such as "^", "$", and "`" are not in the Unicode
    # Punctuation class but we treat them as punctuation anyways, for
    # consistency.
    if (33 <= cp <= 47) or (58 <= cp <= 64) or (91 <= cp <= 96) or (123 <= cp <= 126):
        return True
    cat = unicodedata.category(char)
    if cat.startswith("P"):
        return True
    return False

4.2 Subword tokenizer: WordPiece

Next, the basic tokens become subword tokens. To understand this, start with a vocabulary: a list of tokens the model recognizes.

이용해서
하이라
빛이
즐겁게
변환
세계로
발병
예정이며
비상대책
모두에게
##공간을
##EF
초반에는
것일까
가격으로
##오면
159
가정의
새겨
라스
있듯이
##자면
##って
##전당
돕고
적용되는
우익
##브로
덤으로
주체
##혹한
##시에서
적힌
대학이
정보기술

Tokens outside that vocabulary become [UNK]. We build a vocabulary from the training data, for example with Hugging Face's BERT tokenizer. The setup discussed here uses roughly 32,000 vocabulary items, while the GPT-3 vocabulary has 50,257.

import argparse
import json
from tokenizers import BertWordPieceTokenizer
from glob import glob

parser = argparse.ArgumentParser()

parser.add_argument('--vocab_size', type=int, default=32000)
parser.add_argument('--limit_alphabet', type=int, default=6000)

args = parser.parse_args()

tokenizer = BertWordPieceTokenizer(
    vocab=None,
    clean_text=True,
    handle_chinese_chars=True,
    strip_accents=False,
    lowercase=False,
    wordpieces_prefix="##"
)

data = glob('/data/nlp/Merged/**training**.txt')  # 텍스트 데이터들

tokenizer.train(
    files=data,
    limit_alphabet=args.limit_alphabet,
    vocab_size=args.vocab_size
)

tokenizer.save("./ch-{}-wpm-{}-pretty".format(args.limit_alphabet, args.vocab_size), True)

vocab_path = "ch-6000-wpm-32000-pretty"
vocab_file = 'vocab.txt'

f = open(vocab_file, 'w', encoding='utf-8')
with open(vocab_path) as json_file:

    json_data = json.load(json_file)
    for item in json_data["model"]["vocab"].keys():
        f.write(item+'\n')

    f.close()

Why have a vocabulary and tokenize text at all?

Text must be encoded and embedded before a model can train on it. Encoding assigns an independent value, or ID, to each token. Here is background on embeddings; part two discusses BERT's embeddings. Suppose our vocabulary looks like this.

[UNK]
아버지
##가
방
##에
들
##어
##가
##셨
##다

The Korean sentence “아버지가 방에 후다닥 들어가셨다,” meaning “Father hurried into the room,” can then be represented as follows. The Korean examples are retained because they are the data being tokenized.

아버지가 방에 후다닥 들어가셨다 

=> 아버지 ##가 방 ##에 [UNK] 들 ##어 ##가 ##셨 ##다 (Tokenize)

=>   1    2  3   4    0    5   6   7    8   9 (Encoding)

We can't assign a separate index to every possible word people could produce, so the vocabulary defines what the model knows.

But why split words instead of storing whole ones? A word tokenizer treats a word as one token; a subword tokenizer breaks it into smaller pieces. Here's whole-word tokenization.

경찰관 => 121
경찰복 => 232
경찰차 => 634
경찰소 => 32

Here is the subword version.

경찰관 => 경찰 ##관 => 12 561
경찰복 => 경찰 ##복 => 12 321
경찰차 => 경찰 ##차 => 12 1231
경찰소 => 경찰 ##소 => 12 3123

Subwords are useful for two reasons.

1. Reuse reduces the number of vocabulary entries.

A whole-word tokenizer would treat forms such as 아버지는, 아버지를, 아버지가, 아버지의, and 아버지만 as separate entries. They share the same noun with different Korean particles. Subwords let the noun and particles be reused instead of spending an entry on each combination.

2. They help with out-of-vocabulary words.

An unfamiliar word such as 경찰력 can become 경찰 plus a suffix, or a known part plus [UNK], rather than losing the entire word. Some meaning survives.

BPE, WordPiece, unigram-language-model tokenization, and SentencePiece are discussed here.

BERT uses WordPiece and a greedy longest-match-first procedure. The name is more intimidating than the idea. In the original example below, S and E are character indices marking the start and end of a candidate piece. O means the candidate is in the vocabulary; X means it is not. Shorten E until a match is found, emit that piece, and continue from its endpoint. Pieces after the first use the ## prefix. The Korean explanation is retained with the original example.

[설명]

각 단어를 토큰화 할 때 Start (S) 와 End (E) 가 있다.
S, E는 각 단어의 Character Index를 의미한다.

단어 (S, E) : 타겟 -> 결과
타겟은 단어[S:E] 이다.
결과는 해당 토큰이 Vocab에 있는지 없는지이다. (있으면 O / 없으면 X)

결과가 X 이면 E를 1을 줄인다.
결과가 O 이면 당시 E 값을 S에 주고 다시 끝 Index부터 시작한다.
결과가 O 일 때 S가 0이 아니면 앞에 ##을 붙인다.
예시로 unaffable 이라는 단어를 토큰화 해보자.


[예시]

unaffable (0, 9) : unaffable → X

unaffable (0, 8) : unaffabl → X

...


un (0, 2) : un → O  => un

unaffable (2, 9) : affable → X

unaffable (2, 8) : affabl → X

...


aff (2, 5) : aff → O => ##aff

able (5, 9) : able → O => ##able


[결과]

unaffable => un ##aff ##able

5. Tokens to paired sequences

The BERT input format: CLS, sequence A, SEP, sequence B, SEP.

BERT pretraining predicts masked tokens and whether sequences A and B follow each other. We package tokens and labels into an instance. Formats such as npy, HDF5, and LMDB are useful for large datasets.

5.1 Target sequence length

The input is [CLS] Seq_A [SEP] Seq_B [SEP]. With a maximum length of 128, the three special tokens leave 125 places for A and B. That is the target number of content tokens. A short-sequence probability of 0.1 introduces variation; the code chooses a smaller target rather than always using the maximum.

import random

rng = random.Random(args.random_seed)  # Give random a seed (To maintain the result)

target_seq_length = max_num_tokens - 3  # 125 = 128 - 3

if rng.random() < 0.1: 
    target_seq_length = rng.randint(2, max_num_tokens)  # 0.1의 확률로 125보다 작은 것

5.2 Add sentences until the chunk exceeds the target

Suppose a document contains twenty-six sentences, S1 through S26, each with ten tokens. Add sentences from S1 onward until the total reaches the target. With the example target, the candidate chunk extends through S13.

current_chunk = []
current_length = 0
i = 0

while i < len(document):  # 한 문서에 있는 문장의 개수
    segment = document[i]  # 한 문장
    current_chunk.append(segment)  # 한 문장 append
    current_length += len(segment)  # 한 문장에 있는 토큰의 개수를 더함

    # 마지막 문장이거나 거나 / 현재 청크의 토큰 개수가 이미 target 이상이면 (보통 125)
    if i == len(document) - 1 or current_length >= target_seq_length:
    	break
    else:
    	i += 1

5.3 Choose the split

Choose a split between the chunk's sentences. In the example, a split at six puts S1 through S5 into A.

# `a_end` is how many segments from `current_chunk` go into the `A`
if len(current_chunk) >= 2:  # number of sentences added to chunk
	a_end = rng.randint(1, len(current_chunk) - 1)  # 분기점을 정함
else:
	a_end = 1

seq_a = []
for j in range(a_end):  # 분리점으로 이전 segment 들은 Token_A 에 포함
	seq_a.extend(current_chunk[j])

5.4 Choose whether B is a random next sequence

If it isn't random, put the remaining sentences, S6 through S13, into B.

is_random_next = False
for j in range(a_end, len(current_chunk)):
	seq_b.extend(current_chunk[j])

If it is random, which happens with probability 0.5, take B from another document instead.

if len(current_chunk) == 1 or rng.random() < 0.5:  # 청크에 문장이 1개이거나 50%의 확률로 다른 문장 이어붙임
    
    is_random_next = True
    target_b_length = target_seq_length - len(seq_a)  # Seq_B 에 들어갈 토큰의 개수를 구한다

    for _ in range(10):  # B에 들어갈 토큰들을 가져올 문서를 정함
        random_document_index = rng.randint(0, len(all_documents) - 1)  # 무작위 문서
        if random_document_index != document_index:  # A를 가져온 문서와 다른 문서여야 한다
            break 

    # If picked random document is the same as the current document
    if random_document_index == document_index:
        is_random_next = False  # 혹여나 같으면 random_next를 False로 만든다

    random_document = all_documents[random_document_index]
    random_start = rng.randint(0, len(random_document) - 1)  # 고른 문서에서 랜덤 시작점 고름

    for j in range(random_start, len(random_document)):
        tokens_b.extend(random_document[j])  # 토큰화된 문장 하나씩 넣는다
        if len(seq_b) >= seq_b_length:  # Seq_B
            break

    # 분기점 이후로 문장들은 실제로 안썼다 (S6~S13) -> 다시 보관한다
    num_unused_segments = len(current_chunk) - a_end
    i -= num_unused_segments
    

5.5 Truncate

If A plus B exceeds the target length, remove tokens from the beginning or end of the longer segment, one at a time.

def truncate_seq_pair(seq_a, seq_b, target_seq_length, rng):
    """Truncates a pair of sequences to a maximum sequence length."""
    
    while True:
        total_length = len(seq_a) + len(seq_b)  
        if total_length <= target_seq_length:  # 합이 target_seq_length 보다 클 때
            break

        trunc_tokens = seq_a if len(seq_a) > len(seq_b) else seq_b  # 더 긴 것 선택
        assert len(trunc_tokens) >= 1

        # We want to sometimes truncate from the front and sometimes from the
        # back to add more randomness and avoid biases.
        if rng.random() < 0.5:  # 0.5의 확률로 
            del trunc_tokens[0]  # 맨 앞 토큰 제거 
        else:
        	trunc_tokens.pop()  # 맨 뒤 토큰 제거

After those steps, we get the following.

[CLS] Seq_A [SEP] Seq_B [SEP]

  0   0...0   0   1...1   1

The zeros and ones indicate whether each token belongs to A or B.

6. Mask some tokens

The remaining step is to choose tokens to mask. Here's the implementation.

def create_masked_lm_predictions(tokens, masked_lm_prob,  max_predictions_per_seq, vocab_words, rng):
    """Creates the predictions for the masked LM objective."""

    cand_indexes = []
    for (i, token) in enumerate(tokens):
        if token == "[CLS]" or token == "[SEP]":  # [CLS], [SEP]는 마스킹 후보에서 제외
            continue
        cand_indexes.append(i)

    rng.shuffle(cand_indexes)

    output_tokens = list(tokens)

    # 몇개를 마스킹 할 것이냐 -> 토큰 개수 * 0.15 (최대 20개)
    num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob))))

    masked_lms = []  # 마스킹 된 토큰 객체 (인데스와 라벨이 포함되어있다)
    covered_indexes = set()  # 마스킹할 토큰의 인덱스
    for index in cand_indexes:
        if len(masked_lms) >= num_to_predict:  # 목표치 채웠으면 끝내고
            break
        if index in covered_indexes:  # 이미 마스킹된 index 면 건너뛰기
            continue
        covered_indexes.add(index)  # 해당 Index 마스킹 할 것이다.

        # 80% of the time, replace with [MASK]
        if rng.random() < 0.8:
            masked_token = "[MASK]"  # 0.8의 확률로 마스킹
        else:
            if rng.random() < 0.5:
                masked_token = tokens[index]  # 0.1의 확률로 그대로
            else:
                masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]  # 0.1의 확률로 랜덤 토큰

        output_tokens[index] = masked_token  # 마스킹된 토큰으로 교체
        masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))  # 마스킹한 토큰의 인덱스와 라벨 저장

    masked_lms = sorted(masked_lms, key=lambda x: x.index)  # Index 로 정렬

    masked_lm_positions = []
    masked_lm_labels = []

    for p in masked_lms:
        masked_lm_positions.append(p.index)  # 마스킹한 토큰의 인덱스 저장
        masked_lm_labels.append(p.label)  # 마스킹한 토큰의 라 저장

    # (전체 토큰들 - 마스킹 반영, 마스킹 된 토큰의 위치, 마스킹된 토큰의 라)
    return output_tokens, masked_lm_positions, masked_lm_labels

First decide how many tokens to select, then choose positions at random and save their original labels. Of the selected tokens, 80% become [MASK], 10% stay unchanged, and 10% become a random token.

<Original Sequence>

[CLS] 아버지 ##가 방 ##에 [UNK] 들 ##어 기 ##셨 ##다 [SEP] 코딩 ##은 재미 ##있 ##다 [SEP]


<Masked Sequence>

[CLS] [MASK] ##가 방 ##에 [UNK] 들 ##어 [Mask] ##셨 ##다 [SEP] 코딩 ##은 재미 ##있 ##다 [SEP]


<Masked Token Index>

1, 8
 
 
<Masked Token Label>

아버지, 가

7. Encode and pad

Convert the sequence tokens and masked-token labels into vocabulary indices.

<Masked SequencE>

[CLS] [MASK] ##가 방 ##에 [UNK] 들 ##어 [Mask] ##셨 ##다 [SEP] 코딩 ##은 재미 ##있 ##다 [SEP]


<Encoded Sequence>

 2      4    523  8 312   1   53 5234   4   323  123   3    21  33  22   21  123   3
 
 
<Original Label>
 
1, 8
 
 
<Encoded Label>

3444, 553

If the sequence is shorter than 128, fill the rest with [PAD].

while len(masked_lm_positions) < max_predictions_per_seq:  # Fill empty space in tokens [PAD]
	
    masked_lm_positions.append(0)
	masked_lm_ids.append(0)
  

8. Store a training instance

An instance holds:

  • The encoded input IDs, including masked positions.
  • Masked-token positions.
  • Their original labels.
  • Whether B is a random next sequence.
  • Segment IDs distinguishing A and B.

The Korean headings in the original example below label, in order: encoded input IDs; an input mask with zeros for padding; encoded masked-token labels; masked-token positions; the random-next flag; and segment IDs distinguishing A from B.

<입력 Sequence - 인코딩 됨>

 2      4    523  8 312   1   53 5234   4   323  123   3    21  33  22   21  123   3


<입력 Mask> (Padding을 마스킹하기 위해서)

1 ... 1 0 ... 0 (뒤에 0들은 padding 된 index들)


<마스킹 된 토큰의 라벨 - 인코딩 됨>

3444, 553


<마스킹 된 토큰의 위치>

1, 8


<Random Nex>

1 (True)


<Sequence ID> (해당 토큰이 Seq_A에 속하는지 Seq_B에 속하는지)

0 ... 0 1 ... 1

Store that information in one object:

features["input_ids"][inst_index] = input_ids  # 토큰 -> id
features["input_mask"][inst_index] = input_mask  # 패딩 Masking
features["segment_ids"][inst_index] = segment_ids  # 해당 토큰이 A인지 B인지
features["masked_lm_positions"][inst_index] = masked_lm_positions  # 어떤 토큰이 마스킹 됐는지 (INDEX)
features["masked_lm_ids"][inst_index] = masked_lm_ids   # 마스킹 된 토큰의 라벨 -> id
features["next_sentence_labels"][inst_index] = next_sentence_label  # 랜덤 문장 : 1 / 랜덤 문장 X : 0

Wrapping up

Explaining familiar knowledge clearly is harder than I expected. Perhaps I haven't organized it well enough in my own head. Still, after that long sequence of steps, raw data is finally in a form BERT can train on. Part two follows the training itself.