How to Pretrain BERT

From prepared training instances to model predictions.

BERT achieved state-of-the-art results across many NLP tasks. This post is about the training process, not a review of its architecture or benchmarks. It assumes you already know the model; if not, this introduction may help.

These notes follow the NVIDIA BERT implementation. Read part one first.


Pretraining BERT

BERT’s pretraining input and prediction tasks.
BERT’s pretraining input and prediction tasks.

In part one, we converted text into training instances. The result contained the following fields. Korean labels and example text in the original code blocks are retained; the surrounding explanation describes each field.

<입력 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

The fields, in order, are encoded input token IDs; an input mask (1 for real tokens, 0 for padding); the original IDs of the masked tokens; their positions; the random-next label (1 means B was sampled from another document); and segment IDs (0 for A, 1 for B).

Now we can use those instances to pretrain BERT.

1. Embeddings

First we turn encoded token IDs into embeddings. Encoding? Embedding? The terminology starts to blur.

Part one assigned each token a distinct index. An index alone doesn't express relationships between words, rather like a one-hot representation. People know that father and mother are related; arbitrary IDs don't convey that. Embeddings give the model a learned representation of those relationships. There are other reasons to use them, but that's beyond this post; here is more background.

BERT combines three kinds of embedding. For this example, assume a batch size of 8, a sequence length of 128, and an embedding dimension of 768. The sequence length counts the tokens in [CLS] Seq_A [SEP] Seq_B [SEP].

1.1 Word embedding: token ID to vector

Shape: (8, 128) → (8, 128, 768). Parameter matrix: (32200, 768).

A token index, here an integer from 0 to 32199, becomes a vector of length 768. You can think of it as selecting the vector associated with a one-hot token representation.

1.2 Position embedding: position ID to vector

Shape: (8, 128) → (8, 128, 768). Parameter matrix: (128, 768).

The token ID itself doesn't say where the token occurs. Position matters in language, so we add that information. In this example, position indices run from 0 to 127.

1.3 Token-type embedding: segment ID to vector

Shape: (8, 128) → (8, 128, 768). Parameter matrix: (2, 768).

Token type indicates whether a token belongs to segment A or B: 0 for A, 1 for B. That scalar also selects an embedding vector.

All three embeddings are trainable layers. PyTorch implements them with torch.nn.Embedding; their parameter matrices can also be understood as projections of one-hot inputs. The implementation is below.

import torch.nn as nn


class BertEmbeddings(nn.Module):
    """Construct the embeddings from word, position and token_type embeddings.
    """
    
    def __init__(self, config):
        super(BertEmbeddings, self).__init__()
        self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)  # (32200, 768)
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)  # (128, 768)
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)  # (2, 768)

        # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
        # any TensorFlow checkpoint file
        self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)  # 0.1


    def forward(self, input_ids, token_type_ids):
        seq_length = input_ids.size(1)  # 128
        position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # torch.Size([128])
        position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # torch.Size([8, 128])

        words_embeddings = self.word_embeddings(input_ids)
        position_embeddings = self.position_embeddings(position_ids)
        token_type_embeddings = self.token_type_embeddings(token_type_ids)

        embeddings = words_embeddings + position_embeddings + token_type_embeddings
        embeddings = self.LayerNorm(embeddings)
        embeddings = self.dropout(embeddings)
        return embeddings  # (batchSize, sequenceLength, hidden_size)

The combined representation is:

Embedding = Dropout(Normalize(Word embedding + Position embedding + Token-type embedding))

2. BERT layers

A Transformer encoder block highlighted inside the BERT architecture.

BERT stacks Transformer encoders. The embeddings are below the highlighted block; the highlighted part is a BERT layer, or encoder block. It has three main parts.

2.1 Attention

2.1.1 Self-attention: hidden_state and attention_mask

class BertSelfAttention(nn.Module):

    def __init__(self, config):
        super(BertSelfAttention, self).__init__()
        # hidden_size = 768, num_attention_heads = 12
        if config.hidden_size % config.num_attention_heads != 0:
            raise ValueError(
                "The hidden size (%d) is not a multiple of the number of attention "
                "heads (%d)" % (config.hidden_size, config.num_attention_heads))
        self.num_attention_heads = config.num_attention_heads  # 12
        self.attention_head_size = int(config.hidden_size / config.num_attention_heads)  # 64
        self.all_head_size = self.num_attention_heads * self.attention_head_size  # 768

        self.query = nn.Linear(config.hidden_size, self.all_head_size)  # (768, 768)
        self.key = nn.Linear(config.hidden_size, self.all_head_size)  # (768, 768)
        self.value = nn.Linear(config.hidden_size, self.all_head_size)  # (768, 768)

        self.dropout = nn.Dropout(config.attention_probs_dropout_prob)  # 0.1


    def transpose_for_scores(self, x):
        #  (batch_size, seq_length, num_attention_heads, attention_head_size)
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        # Multi-Head Self Attention
        # (batch_size, seq_length, all_head_size) -> (batch_size, seq_length, num_attention_heads, attention_head_size)
        x = torch.reshape(x, new_x_shape)
        
        return x.permute(0, 2, 1, 3)  # (batch_size, 12, 128, 64)


    def transpose_key_for_scores(self, x):
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = torch.reshape(x, new_x_shape)
        
        return x.permute(0, 2, 3, 1)   # (batch_size, 12, 64, 128)


    def forward(self, hidden_states, attention_mask):
        mixed_query_layer = self.query(hidden_states)  # (batchSize, 128, 768)
        mixed_key_layer = self.key(hidden_states)  # (batchSize, 128, 768)
        mixed_value_layer = self.value(hidden_states)  # (batchSize, 128, 768)

        query_layer = self.transpose_for_scores(mixed_query_layer)  # (batch_size, 12, 128, 64)
        key_layer = self.transpose_key_for_scores(mixed_key_layer)  # (batch_size, 12, 64, 128)
        value_layer = self.transpose_for_scores(mixed_value_layer)  # (batch_size, 12, 128, 64)

        # Take the dot product between "query" and "key" to get the raw attention scores.
        attention_scores = torch.matmul(query_layer, key_layer)  # (batch_size, 12, 128, 128)
        attention_scores = attention_scores / math.sqrt(self.attention_head_size)
        attention_scores = attention_scores + attention_mask 

        # Normalize the attention scores to probabilities.
        attention_probs = F.softmax(attention_scores, dim=-1)

        # This is actually dropping out entire tokens to attend to, which might
        # seem a bit unusual, but is taken from the original Transformer paper.
        attention_probs = self.dropout(attention_probs)

        context_layer = torch.matmul(attention_probs, value_layer)  # (batch_size, 12, 128, 64)
        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()  # (batch_size, 128, 12, 64)
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = torch.reshape(context_layer, new_context_layer_shape)  # (batch_size, 128, 768)
        
        return context_layer

Each token produces query, key, and value vectors for self-attention. With multiple heads, each length-768 vector is split into twelve vectors of length 64.

2.1.2 Self-output: context and hidden_state

class BertSelfOutput(nn.Module):

    def __init__(self, config):
        super(BertSelfOutput, self).__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)  # (768, 768)
        self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)


    def forward(self, hidden_states, input_tensor):
        hidden_states = self.dense(hidden_states)  # (batch_size, 128, 768)
        hidden_states = self.dropout(hidden_states)  # (batch_size, 128, 768)
        hidden_states = self.LayerNorm(hidden_states + input_tensor) # Skip Connection
		
        return hidden_states

The attention result passes through a feed-forward projection and a residual connection.

2.2 Intermediate layer

class BertIntermediate(nn.Module):

    def __init__(self, config):
        super(BertIntermediate, self).__init__()
        # (8, 128, 768) -> (8, 128, 3072)
        self.dense_act = LinearActivation(config.hidden_size, config.intermediate_size, act=config.hidden_act)

    def forward(self, hidden_states):
        hidden_states = self.dense_act(hidden_states)
        
        return hidden_states

A feed-forward layer expands the dimension from 768 to 3072, four times larger. GELU is the activation function.

2.3 Output layer

class BertOutput(nn.Module):

    def __init__(self, config):
        super(BertOutput, self).__init__()
        # (8, 128, 3072) -> (8, 128, 768)
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(self, hidden_states, input_tensor):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        
        return hidden_states  # (8, 128, 768)

The dimension returns from 3072 to 768, followed by dropout and normalization. Its result becomes the next BERT layer's input.

3. Pooling and pretraining predictions

For pretraining, we ultimately need two predictions:

  1. A prediction from the first token's final hidden state, processed through the pooled representation, for next-sentence classification. The classification result here has shape (8, 2).

  2. Token predictions from the final hidden states. Vocabulary logits have shape (8, 128, 32200).

The first decides whether A and B are consecutive. The second predicts the masked words.

The 768-dimensional token states are projected to vocabulary size using the word-embedding weights. It's satisfying how the dimensions fit together.


Wrapping up

I feel this second post isn't as polished as the first. Explaining what I know clearly in writing is hard. If I get the chance, I'd love to give a seminar on this; it's something I want to share.