BERT: In-Depth Exploration of Architecture, Workflow, Code, and Mathematical Foundations [Updated]
From the publisher’s feed, collected in the ZeroLabs newsroom.
BERT: In-Depth Exploration of Architecture, Workflow, Code, and Mathematical FoundationsEmbeddings, Masked Language Model Tasks, Attention Mechanisms, and Feed-Forward Networks Explained Through Equations, Matrix Transformations, and CodeBERT was introduced in 2018, and it has been a topic of interest for many, with lots of articles and YouTube videos explaining it. This article explains BERT through its architecture, workflow, code, and mathematical foundations, and follows one example sentence through every matrix transformation, from the word embeddings to the softmax output. Whether you are looking to deepen your existing knowledge of BERT or are just starting your career in AI, this article aims to give you a complete understanding of it.Linkedin: jaiganesan-n 🌏❤️Note: This article is an updated edition of my original BERT guide, published two years ago (June 2024). I have updated the infographics, workflows and revised the context for better reading and understanding.Before going into how BERT works, we need to understand the difference between BERT and today’s LLMs, because both use the Transformer architecture.An LLM is a probabilistic, auto-regressive model. Auto-regressive means the LLM is trained to predict the next token (the next-token prediction task) from the current context. It gets this property from a causal mask in the attention layer, which lets each token attend only to the tokens before it (left context), never to the tokens after it. That is what allows the model to predict the next token from the current and previous tokens.BERT does not use a causal mask, so each token attends to the other tokens in both directions (left and right context). The objective of BERT is also different. It was designed and trained on two tasks, the Masked Language Model (MLM) and Next Sentence Prediction (NSP). After pre-training, BERT can be fine-tuned for tasks such as classification and question answering.Figure 1: The causal mask of a decoder (left) and BERT’s bidirectional attention (right) on the running example.Figure 1 places the difference on one grid. Each row is the token doing the looking, and each column is the token being looked at. On the left, the decoder sets every score above the diagonal to −∞ before the softmax, so the [MASK] row can see only the five tokens up to itself. On the right, BERT keeps all 64 cells, and the [MASK] row reads "Bidirectional" before it and "Representation from Transformer" after it. This second pattern is the reason BERT is good at filling in a blank.Two BERT architectures were released in 2018, BERT Base and BERT Large. A Transformer with this bidirectional attention is usually called an Encoder model. A Transformer with the causal mask applied (left context only) is usually called a Decoder model, the family today’s LLMs belong to. Both BERT models use the WordPiece tokenizer, which has a vocabulary of 30,522 tokens for the uncased models.BERT Base: 12 encoder layers, 12 attention heads, a feed-forward hidden size of 3072, and about 110M parameters in total. The embedding size is 768.BERT Large: 24 encoder layers, 16 attention heads, a feed-forward hidden size of 4096, and about 340M parameters in total. The embedding size is 1024.Figure 2: BERT Base and BERT Large. Parameter counts from the Hugging Face BertModel at each configuration.Figure 2 lines the two up. The head dimension is 64 in both, because 768 / 12 and 1024 / 16 are both 64, and the feed-forward hidden size is four times the model dimension in both. The paper’s 110M and 340M are rounded values. Counting the actual weights gives 109.48M and 335.14M.In this article, we explore BERT based on the BERT Base architecture and its properties.A note on the figures: Each figure shows a transformation: the tensors going in, the operation, and the tensor coming out, labeled with the symbols the equations use and with the equation the figure draws set above it. To keep the shapes concrete, every figure uses one running example: the MLM sentence from Section 1, cut into 8 tokens, one per word. The sizes are those of BERT Base: model dimension d = 768, 12 heads of d_k = 64, feed-forward hidden size d_ff = 3072, a vocabulary of 30,522, and 512 positions. A sequence is a matrix with one row per token, so the input to every encoder layer is 8 × 768. The numbers inside the vectors and along the edges of the matrices are coordinate indices, 0 up to 767, so you can follow one coordinate through a product. The exceptions are the attention scores, the softmax weights, and the predicted probabilities, where the values are the point. Those are example values, and each figure says so. Weight matrices are pink, inputs blue, hidden activations peach, outputs green, and the row or column being followed is yellow.Figure 3: BERT Base end to end, with the shape on every arrow. Running example: 8 tokens, d = 768.Figure 3 shows the BERT Base architecture end to end, from word embeddings to the linear and softmax layers. Eight token ids are looked up in the word-embedding table, added to the position embeddings and the segment embeddings (segment 0 for every token in a single sentence), and normalized. The resulting 8 × 768 matrix passes through 12 identical encoder layers. Each layer is multi-head attention and a feed-forward network, and each of the two is followed by Add & Norm. The MLM head at the end turns every 768-vector back into a score for each of the 30,522 vocabulary entries. Every arrow between the encoder layers carries the same 8 × 768 shape. Only the embeddings at the start and the MLM head at the end change it.BERT was specifically designed for the Masked Language Model (MLM) and Next Sentence Prediction (NSP) tasks. Here, we focus only on the MLM task to understand the BERT Base architecture.Note: This article does not go into segment embeddings from an architectural or theoretical perspective, because it explores BERT through the Masked Language Modeling (MLM) task, which can be explained on a single sentence. Segment embeddings mark which sentence of a pair a token belongs to, which is what the Next Sentence Prediction (NSP) task needs. BERT still adds them for a single sentence. Every token is then in segment 0, so the segment embedding is the same row for every token. Figure 3, Figure 9, Equation 5, and the code in Section 4 include it to keep the shapes accurate.1. Masked Language Model (MLM)The Masked Language Model task is a Cloze task: we train the model to fill in the blanks in a sentence. To illustrate this, take a simple example, the sentence “BERT Stands for Bidirectional Encoder Representation from Transformer”.In this sentence, we remove the word “Encoder” and replace it with a special [MASK] token that marks the blank. The resulting sentence is "BERT Stands for Bidirectional [MASK] Representation from Transformer". We give this sentence to BERT and train the model to predict the token "Encoder". By understanding the rest of the input, the model predicts the missing token.In pre-training, BERT picks 15% of the token positions at random. Of those, 80% are replaced with [MASK], 10% with a random token, and 10% are left unchanged, so the model cannot learn to pay attention only when it sees [MASK]. Our example masks one token.Figure 4: The masked language model task on one sentence. Only the masked position enters the loss. The probabilities are example values.In Figure 4, the eight input tokens enter at the bottom, with [MASK] at position 4. The encoder returns one 768-vector per position, T₀ to T₇, and every one of them has seen the whole sentence. Only T₄ enters the loss. The MLM head scores all 30,522 vocabulary entries and turns the scores into probabilities. The panel on the right is that distribution for position 4, with example values. "encoder" gets 0.62, and every other token shares the remaining 0.38. The loss is the negative log of the probability given to the correct answer:Equation 1: Masked language model loss over the masked positions M.Here, M is the set of masked positions (just {4} in our example), x̃ is the corrupted input, and the probability is the one the model gives the original token at that position. With 0.62 on “encoder”, the loss is −log 0.62 = 0.48, and a perfect prediction would make it 0. The other seven outputs carry no loss for this sentence. They still matter, because in every layer below the top, position 4 reads from all of them.Note: Figure 4 follows the original TensorFlow code, which gathers the masked positions before the MLM head, so only T₄ is scored. The Hugging Face implementation, like the code in Section 8, passes all 8 rows through the head and ignores the unmasked rows in the loss (Figure 26). The loss is the same either way, because the head works on each row independently.2. Word EmbeddingsThis section answers three questions about word embeddings: what, how, and why. First, what are word embeddings? In simple terms, word embeddings are numerical representations of words or tokens in the form of vectors.Next, how are sentences converted into word embeddings? Take the example from the Masked Language Modeling (MLM) section. The sentence “BERT Stands for Bidirectional [MASK] Representation from Transformer” is broken down into tokens. Tokens are the smallest units of data, and can be words, special characters, or subwords.Figure 5: The WordPiece tokens and ids of the MLM sentence (top) and the 8-token running example used in this article (bottom).Figure 5 shows what the real WordPiece tokenizer does with that sentence. Common words like “stands” and “representation” are one token each, while “bidirectional” splits into four subword pieces and “transformer” into two, with ## marking a piece that continues a word. [CLS] and [SEP] are added at the start and the end, which gives 14 tokens. Every token has an id, its row number in the vocabulary, and [MASK] is id 103. To keep the figures readable, the rest of this article keeps one token per word, the 8 tokens in the lower panel. The shapes work the same way for 8 rows or 14.After that, these token ids are converted into vectors. An id is an index into the vocabulary, which is simply the collection of unique tokens, and it can be written as a one-hot vector: a vector of 30,522 values, all zero except a single 1 at the token’s index. Multiplying that one-hot vector by the embedding matrix gives the token’s vector, a 768-dimensional representation of the word or token.Equation 2: Word embedding lookup.Note: The numbers you see in the figures are coordinate indices or example values, for illustration.Figure 6: Word embeddings as a one-hot product and as a row lookup. Numbers are coordinate indices.In the upper half of Figure 6, the one-hot row for [MASK] has its 1 in column 103. E_word is the word-embedding matrix, 30,522 rows of 768, one row per vocabulary entry. Multiplying the one-hot row by E_word adds up every row of E_word weighted by 0, except row 103, which is weighted by 1. So the product is row 103, the [MASK] embedding x_4. This is why frameworks do not perform this multiplication explicitly: a one-hot product is a table lookup, and nn.Embedding does the lookup directly.The lower half does the same for all eight tokens at once. The 8 ids select 8 rows, and stacking them gives X_word, one row per token. In this example there are 8 tokens (in real-world scenarios, the number of tokens for this sentence differs, as Figure 5 showed), so the input embedding shape is (8, 768), where 768 is the dimension of the BERT Base model.Finally, why do we need word embeddings? Models (computers) cannot understand words. They only understand numbers. Therefore, words need to be converted into embeddings, which represent them in a multi-dimensional space.As humans, we can easily understand the meaning of words and the relationships between them. For example, we know that “happy” and “joy” have similar meanings. Models understand these relationships through vectors. In the multi-dimensional space, words with similar meanings are located close together, while words with unrelated meanings are far apart from each other. “Close” usually means pointing in a similar direction, and the standard way to measure it is the cosine similarity:Equation 3: Cosine similarity.Figure 7: Embeddings in two dimensions, with the cosine similarity of two pairs. Illustration.Figure 7 shows the idea in two dimensions. Words about technology sit together in the upper left, living things in the upper right, and short function words near the middle. “happy” and “joy” point almost the same way, a cosine of 0.99, while “happy” and “machine” point in nearly opposite directions, −0.89. The real space has 768 dimensions, but the measure is the same sum over coordinates.How do similar embeddings end up near each other in the multi-dimensional space? The answer is by training the model. Initially, the embeddings are randomly initialized. As the model trains, the loss pulls the vectors of tokens that are used in similar contexts toward similar positions, and tokens that are similar in meaning start to cluster together in the multi-dimensional space.The following code defines the word embedding layer in PyTorch: an nn.Embedding table with one 768-dimensional vector for each of the 30,522 WordPiece token ids.import torchimport torch.nn as nnclass TokenEmbedding(nn.Embedding): """E_word: one learned 768-vector per WordPiece id.""" def __init__(self, vocab_size=30522, embed_size=768): super().__init__(vocab_size, embed_size, padding_idx=0) # [PAD] has id 0# vocab_size is 30,522 for bert-base-uncased and embed_size is 768, so# nn.Embedding creates a (30522, 768) table: 23.44 million learned numbers.3. Position EmbeddingsPosition embeddings give the model information about the position of each token in the sequence. Without them, the model would not be able to understand the position of a token in the sequence. Attention compares every token with every other token, and nothing in that comparison depends on order, so the same word in different positions would be treated the same. For example, in “BERT is a great model” and “Is BERT a great model?”, the word “BERT” appears in different positions, but without position embeddings the model would fail to recognize the difference.In BERT, position embeddings are created the same way as word embeddings, as a learned table, rather than with the sinusoidal function from the “Attention Is All You Need” paper. BERT has 512 position embeddings, which means only 512 tokens get their positional information. This is one of the reasons BERT cannot take long inputs directly, and why long documents have to be split into chunks. This positional information is learnable: it gets updated during backpropagation, and BERT learns the 512 positions during training. These position embeddings are absolute: each one represents a token’s position counted from the start of the sequence.Equation 4: Position embeddings.Figure 8: Learned position embeddings. An 8-token sequence reads the first 8 of 512 rows.On the left of Figure 8, E_pos is 512 rows of 768, one per position, and a sequence of 8 tokens takes the first 8 rows. That slice is P, one position vector per row of the input. The panel on the right is the example above. In "BERT is a great model", BERT sits at position 0 and its input is e_BERT + p_0. In "Is BERT a great model ?" it sits at position 1 and its input is e_BERT + p_1. The word vector is the same, but the position row is different, so the two inputs differ and the model can tell the sentences apart.The official BERT implementation is in TensorFlow. The following code shows the same logic in PyTorch: it creates the 512 × 768 position table, reads the rows for an 8-token sequence, and adds them to the word embeddings.# Official BERT code is TensorFlow; this is the same logic in PyTorch. See [3, 4].seq_length = 8 # the running examplemax_position_embeddings = 512embed_size = 768# One learned row per position, created and trained for the maximum length (512)full_position_embeddings = nn.Embedding(max_position_embeddings, embed_size)# A sequence of 8 tokens reads only rows 0 ... 7position_ids = torch.arange(seq_length, dtype=torch.long) # [0, 1, ..., 7]position_embeddings = full_position_embeddings(position_ids) # (8, 768)# Added point-wise to the word embeddingsword_embeddings = TokenEmbedding()(torch.randint(1000, 30522, (seq_length,))) # (8, 768)input_embeddings = word_embeddings + position_embeddings # (8, 768)4. Input EmbeddingsThe word embeddings are added (point-wise addition) to the position embeddings. The segment embeddings are added as well (segment 0 for every token in a single sentence), and the sum is normalized with LayerNorm before it reaches the first encoder layer. These input embeddings carry both the word and its position in the sequence.Equation 5: Input embeddings.Figure 9: Input embeddings: word, position and segment embeddings added, then LayerNorm.In Figure 9, the three cards are all 8 × 768, so they add cell by cell. The highlighted cell is row 4, coordinate 0: the first number of the [MASK] word embedding, plus the first number of position 4, plus the first number of segment 0. Since every token here is in segment 0, S is the same row repeated 8 times. LayerNorm then rescales each row on its own (Section 6 shows how), and dropout is applied during training. The result X is the 8 × 768 input to the first encoder layer.The following code combines the word, position, and segment embeddings, then applies LayerNorm and dropout. When no segment ids are given, every token is assigned segment 0, as in our single-sentence example.class BertEmbeddings(nn.Module): """X = LayerNorm(E_word[t] + E_pos[0:n] + E_seg[s]), then dropout.""" def __init__(self, vocab_size=30522, d_model=768, max_len=512, n_segments=2, dropout=0.1): super().__init__() self.word = TokenEmbedding(vocab_size, d_model) self.position = nn.Embedding(max_len, d_model) self.segment = nn.Embedding(n_segments, d_model) self.norm = nn.LayerNorm(d_model, eps=1e-12) self.dropout = nn.Dropout(dropout)def forward(self, input_ids, segment_ids=None): # input_ids: (B, n) n = input_ids.size(1) pos_ids = torch.arange(n, device=input_ids.device) # 0 ... n-1 if segment_ids is None: # one sentence: segment 0 segment_ids = torch.zeros_like(input_ids) x = self.word(input_ids) + self.position(pos_ids) + self.segment(segment_ids) return self.dropout(self.norm(x)) # (B, n, 768)5. Self AttentionWith the input embeddings in place, the next component is the self-attention mechanism. To fully understand multi-head attention, we first need to understand self-attention clearly.Self-attention has three key components: the Query, the Key, and the Value. All three are computed from the same input: the input embeddings in the first layer, or the output of the previous encoder layer after that. That shared source is what “self” means. In the full model, each of them comes from its own learned projection, which is the subject of Section 6. To see the mechanism on its own first, this section takes those projections to be the identity, so Q = K = V = X, each 8 × 768.What is self-attention?In simple terms, self-attention is a method where the input sequence is compared against itself to determine the importance of other words or tokens with respect to the current word. This allows the model to capture dependencies and relationships between words within the sequence, regardless of their positions. As a result, the model can understand the semantic and syntactic relationships between words in the input sequence.Equation 6: Scaled dot-product attention. Source: Attention Is All You Need.Equation 6 gives the mathematical form of self-attention. The Query matrix is multiplied by the transposed Key matrix, and the result is divided by the square root of the key dimension d_k (√768 in this section). Next, a softmax function is applied to each row of the resulting matrix. Finally, the output is multiplied by the Value matrix, which gives the self-attention output.Figure 10: One self-attention layer, single head, with Q = K = V = X.Figure 10 is Equation 6 in blocks. X is copied into Q, K and V. Q and K meet in the score block, which compares every pair of tokens and returns S, 8 × 8. The softmax turns each row of S into weights A that add up to 1, and A multiplies V to give Z, the same 8 × 768 shape as X. The dashed identity boxes are where Section 6 places its weight matrices.Equation 7: Attention scores.Figure 11: Self-attention part 1, the scores QKᵀ / √768. Numbers are coordinate indices.As shown in Figure 11, the Query and the transposed Key matrices are multiplied and divided by √768 = 27.71. The resulting matrix is 8 × 8 and holds the attention logits of each token with every other token in the sequence. The highlighted row 4 of Q is the [MASK] token's query, and the highlighted column 3 of Kᵀ is the key of "Bidirectional". Their dot product, 768 multiplications added up, is the single score S₄,₃. Every other cell of S is the same calculation with a different row and column. Without the division, dot products of 768-dimensional vectors become large, and the softmax would push almost all of the weight onto one token and pass back very small gradients.Equation 8: Row-wise softmax.Figure 12: Self-attention part 2, the row-wise softmax. Example values.The resulting matrix is then fed into a softmax function, which outputs a set of probabilities, the attention scores. These attention scores show how much each token depends on the other tokens in the sequence, through semantic and syntactic relationships. In other words, they show how important each token is to every other token in the sequence.Figure 12 uses example values. Because Q = K in this section, S is symmetric, and the diagonal is the largest entry in every row, since a vector is most similar to itself. This is one more reason the real model gives queries and keys their own projections. After the softmax, the [MASK] row puts 0.409 on itself, 0.193 on "Bidirectional", 0.166 on "Representation", and the remaining 0.232 on the other five tokens. Every row adds up to 1.000, as the column on the right shows.Equation 9: Self-attention output.Figure 13: Self-attention part 3, the output Z = AV.Then the attention matrix (8, 8) is multiplied by the Value matrix (8, 768), which gives the attention output (8, 768). In this output, each token’s row now holds information from the other tokens. As Figure 13 writes out for row 4, the [MASK] token's new vector z_4 is a weighted sum of all eight value rows, with the weights from Figure 12. Most of it comes from its own row and its two neighbors, "Bidirectional" and "Representation", which is the context it needs to predict the missing word. This combined information then moves on through the rest of the layer.The following code implements Equation 6. The optional mask is a padding mask, not a causal mask, so every token can still attend to every other token in the sequence.import mathimport torch.nn.functional as Fclass Attention(nn.Module): """softmax(Q K^T / sqrt(d_k)) V (Equation 6).""" def forward(self, query, key, value, mask=None, dropout=None): scores = torch.matmul(query, key.transpose(-2, -1)) \ / math.sqrt(query.size(-1)) # S, (..., n, n) if mask is not None: # padding mask, never causal scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim=-1) # A, every row sums to 1 if dropout is not None: p_attn = dropout(p_attn) return torch.matmul(p_attn, value), p_attn # Z = A V, and A6. Multi-Head AttentionSelf-attention captures the relationships between words. Then why do we need multi-head attention? Self-attention captures the relationships between words from one perspective (it may capture the order of the sequence, grammatical structure, context, or dependencies between words). Multi-head attention captures the relationships between words from several perspectives at once, with the help of learned weights (parameters). Self-attention above works at the model dimension, while multi-head attention works at each head’s dimension.Equation 10: Multi-head attention. Source: Attention Is All You Need paper.The Query (Q), Key (K) and Value (V) all come from the same input, the input embeddings or the output of the previous encoder layer.BERT Base’s model dimension is 768, and the multi-head attention layer has 12 heads. To calculate the dimension of each head, we divide 768 by 12, which gives 64.For each of these 12 heads, we need three components: the query, key, and value matrices. This means there are 12 separate attention mechanisms in the multi-head attention layer, and each one captures a different perspective of the input sequence.These query, key, and value matrices are created with weight matrices. As shown in Equation 10 and illustrated in Figures 14 and 15, to create the query matrices, we multiply the input by 12 query weight matrices, each of size (768, 64). In practice this is organized a little differently, as explained in the code section. This gives 12 query matrices, one for each head, each of size (8, 64). Here, 64 is the dimension of the head, and 8 is the number of tokens in our example. The same process is repeated to create the key and value matrices for all heads. Each of these weight matrices is a linear layer.Equation 11: The linear layer as computed by torch.nn.Linear.Figure 14: A linear layer as matrices, nn.Linear(768, 3072).Important note to understand the linear layer: PyTorch stores the weight matrix as (current layer’s number of neurons, previous layer’s or input layer’s number of neurons), that is, output size × input size. We initialize the layer with the input size and the output size, nn.Linear(input vector size, output vector size). For example, the FFN of BERT Base has 768 input units and 3072 neurons in its hidden layer, so nn.Linear(768, 3072) holds a weight matrix W of size (3072, 768). The input vectors are multiplied by this matrix, transposed, which gives new vectors, and then the bias vector is added. This is a linear transformation of vectors: they move from one dimension (768) to another (3072), or to the same dimension.Equation 11 is the linear layer operation in PyTorch. As emphasized in my previous articles, when it comes to linear layers or neural networks, it is essential to think in terms of matrices and vectors rather than neurons. In Figure 14, the input row x (768 numbers) is multiplied by Wᵀ, 768 rows of 3072. Column 2 of Wᵀ, which is row 2 of the stored W, dotted with x, plus the bias b_2, gives the output coordinate y_2, and each of the 3072 outputs is one such dot product. When x has 8 rows instead of one, the same bias row is added to every row of the result, which is called broadcasting.Equation 12: Per-head projections in BERT Base.Figure 15: Query, key and value projections for each head.The top of Figure 15 is head 1’s query with all its indices. X is 8 × 768, W₁^Q is 768 × 64, and Q₁ is 8 × 64: each token keeps its row, but the row is now 64 numbers. The bottom half shows all 36 projections at once, 12 heads for each of query, key and value, with every weight 768 × 64 = 49,152 numbers and every output 8 × 64.Figure 16: Multi-head notation: 12 heads, each with its own Q, K and V of 8 × 64Figure 16 lays out the result per head. Each head holds its own Q_h, K_h and V_h, all 8 × 64. Every head sees all 8 tokens but only its own 64 coordinates, and 12 × 64 = 768 brings the heads back to the model dimension.Within each head, the same self-attention operation from Section 5 takes place, using that head’s query, key, and value matrices. Taking the first head as an example, the Q₁ matrix (8, 64) is multiplied by the transposed K₁ matrix (64, 8), resulting in an 8 × 8 matrix.Next, this matrix is divided by the square root of the key’s dimension, which is 8 (since the key’s dimension is 64). The softmax is applied to each row, and the result is multiplied by the value matrix V₁, producing the attention output for head 1, with a size of (8, 64).Equation 13: Attention inside one head.Figure 17: Attention inside each head. The attention maps are example patterns.This same operation is repeated for all 12 heads, generating 12 attention head outputs, each of size (8, 64). Figure 17 shows why several heads help, with example attention maps. One head may learn to look one token back, another one token ahead, and another lets the [MASK] row gather from "Bidirectional", "Representation" and "Transformer" on both sides. Each head can learn its own pattern because each has its own weights, and studies of trained BERT models have found heads that specialize in this way.Figure 18: Concatenating the 12 heads, then the output projection W^O.Finally, the outputs from all the heads are concatenated, resulting in a single output of size (8, 768). In Figure 18, head 1 fills columns 0–63, head 2 columns 64–127, and head 12 columns 704–767. The concatenated output is linearly projected with a weight matrix W^O of size (768, 768), giving the multi-head attention layer output of size (8, 768). Concatenation only places the heads side by side. W^O is the step that mixes them, so every coordinate of the output can draw on every head.The PyTorch implementation follows the same mathematics, with one difference in how the weights are organized, shown in Figure 19.Figure 19: How the code computes all 12 heads with one projection and a reshape.Instead of 12 separate 768 × 64 matrices, the code keeps one 768 × 768 matrix per role, with the 12 head matrices side by side. One product X W^Q gives an 8 × 768 Q whose columns 0–63 are exactly Q₁, columns 64–127 are Q₂, and so on. .view(B, n, 12, 64) splits each token's 768 numbers into 12 groups of 64, and .transpose(1, 2) moves the head axis in front of the tokens, giving one 8 × 64 matrix per head. Both ways give the same queries and the same number of parameters, but the fused version is one large matrix product instead of twelve small ones. The following code snippet will give you a better understanding of how MHA works in practice.class MultiHeadedAttention(nn.Module): def __init__(self, h=12, d_model=768, dropout=0.1): super().__init__() assert d_model % h == 0 # 768 / 12 = 64, so the heads tile d_model exactly self.d_k = d_model // h # head dimension, 64 self.h = h # number of heads, 12 # W^Q, W^K, W^V: each one nn.Linear(768, 768) = 12 heads of (768, 64) side by side self.linear_layers = nn.ModuleList([nn.Linear(d_model, d_model) for _ in range(3)]) self.output_linear = nn.Linear(d_model, d_model) # W^O, (768, 768) self.attention = Attention() self.dropout = nn.Dropout(p=dropout)def forward(self, query, key, value, mask=None): # each (B, n, 768), all X in BERT batch_size = query.size(0) # B, the batch size """ The theory (Figure 15) uses 12 separate (768, 64) weight matrices per role. In practice one nn.Linear(768, 768) holds all 12 side by side (Figure 19). One matrix product gives (B, n, 768), .view splits the 768 columns into 12 heads of 64, and .transpose moves the head axis in front of the tokens. Same outputs and the same parameter count, in one matrix product. """ # 1) project, then split: (B, n, 768) -> (B, n, 12, 64) -> (B, 12, n, 64) query, key, value = [l(x).view(batch_size, -1, self.h, self.d_k).transpose(1, 2) for l, x in zip(self.linear_layers, (query, key, value))] # 2) attention in all 12 heads at once: (B, 12, n, 64) x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout) # 3) concat: (B, 12, n, 64) -> (B, n, 12, 64) -> (B, n, 768) x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_k) return self.output_linear(x) # W^O, (B, n, 768)One more step comes before the feed-forward network: the Add & Norm block that follows attention in Figure 3.Equation 14: Add & Norm, and LayerNorm.Figure 20: Add & Norm after multi-head attention, with LayerNorm on one row.The attention output is added to the layer’s own input, which is the residual connection, and the sum is normalized. LayerNorm works on each token’s row by itself, as Figure 20 shows for row 4. It computes the mean μ₄ and the variance σ₄² of the row’s 768 numbers, subtracts the mean, divides by the standard deviation, and then scales and shifts the result with γ and β, two learned 768-vectors shared by every token. BERT applies the normalization after the addition (post-norm), the arrangement used in the original Transformer. The same block follows the feed-forward network.7. Feed Forward NetworkIn its simplest form, a feed-forward network is a type of neural network that consists of three layers: an input layer, a hidden layer, and an output layer. The number of input units in the input layer and the number of neurons in the output layer equal the model’s dimension (768). In the case of BERT, the hidden layer is four times (3072) the model’s dimension.The FFN (Feed Forward Network) has a different role from attention. The attention mechanism gathers information from across the sequence. The attention layer captures the semantic and syntactic relationships between words and builds a contextual understanding of the sequence. The Feed Forward Network then processes that gathered information for each token on its own. It holds most of the model’s parameters, more than half of BERT Base (Figure 27), and it learns the patterns of the language humans use to communicate. By learning them, the model can predict the tokens.Equation 15: The feed-forward network of BERT Base.Figure 21: The feed-forward network of BERT Base drawn as neurons.The output from the multi-head attention layer, after Add & Norm, has a size of (8, 768) and is fed into the input layer of the Feed-Forward Network (FFN). Think of the input layer as a bridge that simply passes on the information without performing any operation.Figure 21 shows the network as neurons, for one token. Each of the 3072 hidden units is connected to all 768 inputs, which is a 3072 × 768 weight matrix, and each of the 768 outputs is connected to all 3072 hidden units, a 768 × 3072 matrix. That is 2.36 million parameters on each side.Figure 22: The feed-forward network on one token. Numbers are coordinate indicesFigure 22 shows the same token as matrices. Row 2 of W₁ dotted with x, plus the bias, then passed through GELU, gives the hidden coordinate h₂, and all 3072 rows together give h. W₂ takes h back to a 768-vector y. The hidden layer is four times wider than the token, which gives the nonlinearity room to work.For the whole sequence, the input (8, 768) is multiplied by the transpose of the FFN hidden-layer weight matrix, which is stored with a size of (3072, 768), resulting in a matrix of size (8, 3072). Next, a bias vector (1, 3072) is added to each row of the resulting matrix, a process known as broadcasting. GELU applied to this matrix gives the hidden layer output.Figure 23: FFN hidden layer and output layer operations on the whole sequence.The output from the hidden layer (8, 3072) is then multiplied by the transpose of the FFN output-layer weight matrix, stored with a size of (768, 3072), resulting in a matrix of size (8, 768). Finally, an output-layer bias vector (1, 768) is added to each row, completing the FFN layer output. Both halves are shown in Figure 23. Every token passes through the same weights, independently of the others, which is why the “Attention Is All You Need” paper calls it position-wise. After Add & Norm, this output is passed on to the next encoder layer, or to the MLM head after the last layer. The bias vectors give every unit a learned offset, so a neuron can still be active when its weighted input adds up to zero.In BERT, the GELU (Gaussian Error Linear Unit) activation function is used. GELU weights each input by the probability that a standard Gaussian variable is smaller than it, x·Φ(x), which makes it a smooth version of ReLU. It can be approximated with the tanh formula in Equation 16, or more simply as GELU ≈ x·sigmoid(1.702x).Equation 16: GELU and its two approximations.Figure 24: GELU, its tanh and sigmoid approximations, and ReLU.In Figure 24, GELU is almost the identity for large positive inputs and almost 0 for large negative inputs, like ReLU. In between, it bends smoothly and dips slightly below zero, to −0.170 at x = −0.75, so small negative inputs still pass a little signal and a gradient. The tanh form, which the original BERT code uses, stays within 0.0005 of the exact curve. The sigmoid form is simpler and stays within about 0.02.The following code implements the FFN and one encoder layer. With both halves in place, one encoder layer is attention and the FFN, each wrapped in Add & Norm, and BERT Base stacks 12 of them.class PositionwiseFeedForward(nn.Module): # d_model is the model dimension (768), d_ff the hidden size (3072) def __init__(self, d_model=768, d_ff=3072): super().__init__() self.w_1 = nn.Linear(d_model, d_ff) # W_1: weight (3072, 768), bias (3072) self.w_2 = nn.Linear(d_ff, d_model) # W_2: weight (768, 3072), bias (768) self.activation = nn.GELU() # x * Phi(x), Equation 16def forward(self, x): # (B, n, 768) return self.w_2(self.activation(self.w_1(x))) # (B, n, 3072) -> (B, n, 768)class EncoderLayer(nn.Module): """Post-norm, as in BERT: X' = LN(X + MHA(X)), X'' = LN(X' + FFN(X')).""" def __init__(self, d_model=768, h=12, d_ff=3072, dropout=0.1): super().__init__() self.attention = MultiHeadedAttention(h, d_model, dropout) self.norm1 = nn.LayerNorm(d_model, eps=1e-12) self.ffn = PositionwiseFeedForward(d_model, d_ff) self.norm2 = nn.LayerNorm(d_model, eps=1e-12) self.dropout = nn.Dropout(dropout) def forward(self, x, mask=None): # (B, n, 768) x = self.norm1(x + self.dropout(self.attention(x, x, x, mask))) # Add & Norm 1 return self.norm2(x + self.dropout(self.ffn(x))) # Add & Norm 28. Linear Layer and Softmax in MLMAfter all the encoder layers (12), the final matrix (8, 768) is fed into the MLM head to predict the exact token for the Masked Language Model (MLM) task. The head has two parts: a transform, which is a 768 × 768 dense layer with GELU and LayerNorm, and then the output linear layer, whose weight is the word-embedding matrix itself, transposed.Equation 17: The MLM head.Figure 25: The output layer of the MLM head, tied to the word embeddings.Figure 25 shows the output layer as neurons. Each of the 30,522 outputs is connected to all 768 inputs, so its weight matrix is 768 × 30,522, the same size as the word-embedding table. BERT does not learn a second table. It reuses E_word (weight tying) and adds only a bias of 30,522 numbers, so the vector that represents a word at the input is also the one its output score is measured against.Figure 26: The MLM head, from the last hidden state to the predicted token and the loss. Example probabilitiesIn Figure 26, the (8, 768) matrix is first transformed, row by row, into H̃. H̃ is then multiplied by E_wordᵀ (768, 30,522), and the bias is added. This results in a new matrix with a size of (8, 30,522), where 30,522 is the total number of tokens in the vocabulary. This resulting matrix is called the logits matrix. All 8 rows pass through the head here, as in the Hugging Face implementation, and only row 4 is used in the loss.Next, the softmax function is applied to the logits matrix, which assigns a probability to every vocabulary token, row by row. The index with the highest probability score is selected as the output token.When the masked token’s vector (in this case, the 5th token, index 4) passes through the head, it produces a logit vector of size (1, 30,522). This vector is then fed into the softmax function, which generates probability scores across all 30,522 possible tokens.In our example, the correct output is the token “Encoder”, so the probability in its column should be high for the model to output “Encoder”: 0.62 in the example values of Figure 26. This means the model is confident that the correct output is “Encoder”. (In the real vocabulary, “encoder” is three WordPiece tokens, en, ##code and ##r, and each of those masked positions would get its own row and its own prediction.)The loss is computed on the same row. The target is a one-hot row, all zeros except a one at the target index. Cross-entropy against it picks out the log-probability of the correct token, as Equation 18 shows. It is computed only at the masked positions, here row 4, and its gradient is what trains every weight in the model for the task.Equation 18: Prediction and cross-entropy loss at the masked position.The following code implements the MLM head. The output layer’s weight is assigned the word-embedding table, so the input embeddings and the output layer share the same (30522, 768) parameters.class MaskedLanguageModel(nn.Module): # hidden --> model dimension (768), vocab_size --> 30522 def __init__(self, word_embeddings, hidden=768): super().__init__() self.transform = nn.Linear(hidden, hidden) # W_t, (768, 768) self.activation = nn.GELU() self.norm = nn.LayerNorm(hidden, eps=1e-12) vocab_size = word_embeddings.num_embeddings self.decoder = nn.Linear(hidden, vocab_size, bias=False) self.decoder.weight = word_embeddings.weight # tied: the same (30522, 768) table self.bias = nn.Parameter(torch.zeros(vocab_size)) # the only new output parameters self.softmax = nn.LogSoftmax(dim=-1)def forward(self, x): # (B, n, 768) x = self.norm(self.activation(self.transform(x))) return self.softmax(self.decoder(x) + self.bias) # log-probs, (B, n, 30522)The last block puts every piece from this article together and runs the eight-token example. With the weights of Hugging Face’s BertForMaskedLM copied in, its log-probabilities agree to within 3 × 10⁻⁶, and the parameter counts are identical.class BERT(nn.Module): def __init__(self, vocab_size=30522, d_model=768, n_layers=12, h=12, d_ff=3072): super().__init__() self.embeddings = BertEmbeddings(vocab_size, d_model) self.layers = nn.ModuleList([EncoderLayer(d_model, h, d_ff) for _ in range(n_layers)]) self.mlm = MaskedLanguageModel(self.embeddings.word, d_model)def forward(self, input_ids, mask=None): x = self.embeddings(input_ids) # (B, n, 768) for layer in self.layers: x = layer(x, mask) # (B, n, 768), 12 times return self.mlm(x) # (B, n, 30522)model = BERT().eval()ids = torch.randint(1000, 30522, (1, 8)) # any 8 token idsids[0, 4] = 103 # [MASK] at position 4, as in the figureslog_p = model(ids)print(log_p.shape) # torch.Size([1, 8, 30522])print(sum(p.numel() for p in model.parameters())) # 109514298Figure 27: Where BERT Base’s 109.48 million parameters live.Figure 27 counts the parameters by component. The 12 feed-forward networks hold just over half of BERT Base, the 12 attention layers about a quarter, and the word-embedding table a fifth. Positions, segments, and all the LayerNorms together come to under half a percent.Important note: The weight matrices, bias vectors, LayerNorm parameters, position embeddings, and word embeddings are all learnable. They get updated during the backpropagation process while the model is being trained.ConclusionSome topics were not covered in this article, such as segment embeddings, the next-sentence prediction task, and fine-tuning BERT for specific tasks. However, it covers the most essential topics for a solid understanding of the BERT architecture: word and position embeddings, the masked language model task, self-attention and multi-head attention, the feed-forward network, and the linear and softmax layers of the MLM head.By understanding the architecture, you can modify the loss function and the BERT architecture to suit your specific use case, and tailor BERT to your needs.Linkedin: jaiganesan-n 🌏❤️References[1] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin, Attention Is All You Need (2017). Research paper (arXiv:1706.03762).[2] Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova, BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (2018). Research paper (arXiv:1810.04805).[3] BERT PyTorch implementation, GitHub repo (2018).[4] BERT TensorFlow implementation, official GitHub repository given in the BERT research paper (2018).[5] Dan Hendrycks, Kevin Gimpel, Gaussian Error Linear Units (GELUs) (2016). Research paper (arXiv:1606.08415).[6] Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton, Layer Normalization (2016). Research paper (arXiv:1607.06450).[7] Kevin Clark, Urvashi Khandelwal, Omer Levy, Christopher D. Manning, What Does BERT Look At? An Analysis of BERT’s Attention (2019). Research paper (arXiv:1906.04341).[8] Hugging Face Transformers, BERT model documentation, used to check the parameter counts and the code in this article.BERT: In-Depth Exploration of Architecture, Workflow, Code, and Mathematical Foundations [Updated] was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.