Session #11: Transformer Architecture: BERT
Free University Berlin
2026-04-26
Game plan
This lecture provides an introduction to the transformer architecture with a focus on the encoder.
** Bidirectional Encoder Representations from Transformers(BERT)**: - Developed in 2018 by researchers at Google AI Language - A swiss army knife solution to many common language tasks, such as sentiment analysis and named entity recognition.
| Transformer | Layers | Hidden Size | Attention Heads | Parameters | Processing | Length of Training |
|---|---|---|---|---|---|---|
| BERTbase | 12 | 768 | 12 | 110M | 4 TPUs | 4 days |
| BERTlarge | 24 | 1024 | 16 | 340M | 16 TPUs | 4 days |
The dimension of the FFN is 3072
There are 12 attention heads in the multihead attention block (BERTbase – 16 for BERTlarge).
The transformer block is repeated Nx times (12 for BERTbase and 24 for BERTlarge), that is, the output of one block is used as input for the next
The output of the final block is used as input for the linear layer
Differences to the original transformer:
Major differences:
Core Objective
MLM: Predict the correct word given both the left and right bidirectional context.
Left Context Task
“An elephant’s trunk can be used to grasp yellow [?].”
Full Context MLM Task
“An elephant’s [?] can be used to grasp yellow bananas.”
Recall the definition of the attention output
\[ \underbrace{\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})}_{N\times N} = \mathrm{softmax}\left( \frac{ \underbrace{\mathbf{Q}}_{N\times d_{hidden}} \times \underbrace{\mathbf{K}^T}_{d_{hidden}\times N}} {\sqrt{d_{k}}} \right) \]
[MASK]: Berlin is the [MASK] of GermanyThe motivation for not always replacing the token with [MASK] is that this would created a mismatch between pre-training and fine-tuning, since the [MASK] token does not appear during fine-tuning. Using the random/unchanged tokens mitigates this mismatch.
\[ \begin{align} \mathbf{u}_i &= \mathbf{h}_i^L \mathbf{E}^T \\ \mathbf{y}_i &= \mathrm{softmax}(\mathbf{u}_i) \end{align} \]
\[ -\frac{1}{M}\sum_{m=1}^M \log P(x_i\mid \mathbf{h}_i^L) \]
NSP:
Why did the chicken cross the road? To get to the other side
Why did the chicken cross the road? The climate crisis is driven by burning fossil fuels.
NSP:
IsNext) or does not (NotNext) follow another sentence?dog is from the first and play is from the second sentence[CLS]) to linear layer – with only two output features, next and notNext, and pass through softmax.[SEP] Token and Sentence Pairs[SEP] token separating the two sentences, plus a learned segment embedding added to each token indicating which sentence it belongs to:\[ \text{[CLS]} \ \text{Sentence A} \ \text{[SEP]} \ \text{Sentence B} \ \text{[SEP]} \]
For every training example, BERT builds one input (a sentence pair with some tokens replaced by [MASK]) and runs it through a single forward pass.
That one pass produces both:
The two losses are then just added together \[ \mathcal{L} = \mathcal{L}_{MLM} + \mathcal{L}_{NSP} \]
The combined loss is backpropagated through the shared BERT weights in one update step.
\[ \underbrace{1 \times 768}_{\text{Input}} \xrightarrow{W_1, b_1} \underbrace{1 \times 3072}_{\text{Linear Expansion}} \xrightarrow{\text{GELU}} \underbrace{1 \times 3072}_{\text{Non-linear Activation}} \xrightarrow{W_2, b_2} \underbrace{1 \times 768}_{\text{Output}} \]
| Causal LM (GPT-style) | Masked LM (BERT-style) | |
|---|---|---|
| Direction | Left-to-right only | Bidirectional |
| Attention | Causal mask (Section 2) | No mask — full self-attention |
| Predicts | Next token, given all past tokens | Randomly masked tokens, given surrounding context (past and future) |
| Natural use | Text generation | Understanding/representation tasks (classification, extraction) |
| Reference | Radford et al. (2018)1 | Devlin et al. (2019)2 |
Import libraries (datasets, evaluate, and transformers are from huggingface)
adapted from Shaw Talebi Fine-Tuning BERT for Text Classification YouTube
model_path = "google-bert/bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_path)
id2label = { 0: "Safe", 1: "Phishing"}
label2id = { "Safe": 0, "Phishing": 1}
model = AutoModelForSequenceClassification.from_pretrained(model_path,
num_labels=2,
id2label=id2label,
label2id=label2id,
attn_implementation="eager")AutoModelForSequenceClassification class adds a binary classification head to the BERT base model.attn_implementation="eager" is needed to avoid the fused SDPA kernel, which is not available from PyTorch’s MPS (Apple GPU) backend1.[CLS] token, still part of base_model, which we explicitly unfreeze, andAutoModelForSequenceClassification — untouched by the loop below since it lives outside base_model, and trainable simply because it’s newly initialized.We set up a tokenizer and tokenize the input texts.
accuracy = evaluate.load("accuracy")
auc_score = evaluate.load("roc_auc")
def compute_metrics(eval_pred):
# logits and ground truth labels
predictions, labels = eval_pred
# softmax
probabilities = np.exp(predictions)/np.exp(predictions).sum(-1, keepdims=True)
positive_class_probs = probabilities[:,1]
auc = np.round(auc_score.compute(prediction_scores=positive_class_probs, references=labels)['roc_auc'], 3)
predicted_classes = np.argmax(predictions, axis=1)
acc = np.round(accuracy.compute(predictions=predicted_classes, references=labels)['accuracy'], 3)
return {"Accuracy": acc, "AUC": auc}lr = 2e-4
batch_size = 8
num_epochs = 10
training_args = TrainingArguments(
output_dir="bert_phishing-classifier_teacher",
learning_rate=lr,
per_device_eval_batch_size=batch_size,
per_device_train_batch_size=batch_size,
num_train_epochs=num_epochs,
logging_strategy="epoch",
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True
)from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
import evaluate
import numpy as np
dataset_name = "ag_news"
dataset = load_dataset(dataset_name)
# Similar code
# To get multiple classes
n_classes = dataset["train].features["label"].num_classes
model = AutoModelForSequenceClassification.from_pretrained(model_path,
num_labels=n_classes,
attn_implementation="eager")See: https://www.kaggle.com/datasets/amananandrai/ag-news-classification-dataset
\[ P(\text{label}_i) = \text{softmax}(\mathbf{h}_i W_{\text{tok}} + b_{\text{tok}}), \qquad \text{for each token } i \]
[CLS] and [SEP] are typically excluded from the loss — they’re structural tokens, not real words with entity labels.We need to tell BERT about the following classification
| ID | Tag | Description |
|-----:|:-------|:---------------------------|
| 0 | O | Outside of a named entity |
| 1 | B-PER | Beginning of a PER entity |
| 2 | I-PER | Inside of a PER entity |
| 3 | B-ORG | Beginning of a ORG entity |
| 4 | I-ORG | Inside of a ORG entity |
| 5 | B-LOC | Beginning of a LOC entity |
| 6 | I-LOC | Inside of a LOC entity |
| 7 | B-MISC | Beginning of a MISC entity |
| 8 | I-MISC | Inside of a MISC entity || Token | Entity | Probability |
|---|---|---|
| konrad | B-PER | 0.9857714 |
| aden | I-PER | 0.9818236 |
| ##auer | I-PER | 0.979223 |
| germany | B-LOC | 0.9961558 |
\[ \mathrm{sim}(\mathbf{x},\mathbf{y}) = \frac{\mathbf{x}\cdot \mathbf{y}}{\Vert \mathbf{x} \Vert \Vert \mathbf{y} \Vert} = \frac{\sum_i A_i\cdot B_i}{\sqrt{\sum_i A_i^2}\cdot \sqrt{\sum_i B_i^2}} \]
entailment, contradiction, or neutral| Premise | Hypothesis | Label |
|---|---|---|
| The sun is shining | It is not raining | entailment |
| The girl is playing with a ball | The girl is sleeping | contradiction |
| An older and younger man smiling | Two men are smiling and laughing at cats playing on the floor | neutral |
\[ (u, v, |u-v|) \]
\[ o = \mathrm{softmax}\big(W_t\,(u, v, |u-v|)\big) \]
| Score | Meaning | Example 1 | Example 2 |
|---|---|---|---|
| 5 | The two sentences are completely equivalent, as they mean the same thing. | The bird is bathing in the sink. | Birdie is washing itself in the water basin. |
| 4 | The two sentences are mostly equivalent, but some unimportant details differ. | Two boys on a couch are playing video games. | Two boys are playing a video game. |
| 3 | The two sentences are roughly equivalent, but some important information differs/missing. | John said he is considered a witness but not a suspect. | “He is not a suspect anymore.” John said. |
| 2 | The two sentences are not equivalent, but share some details. | They flew out of the nest in groups. | They flew into the nest together. |
| 1 | The two sentences are not equivalent, but are on the same topic. | The woman is playing the violin. | The young lady enjoys listening to the guitar. |
| 0 | The two sentences are completely dissimilar. | The black dog is running through the snow. | A race car driver is driving his car through the mud. |
Mean squared-error (MSE) loss for the cosine similarity is used as the objective function.
The STS Benchmark labels are on a \(y\in 0–5\) scale, so before computing the loss, the gold score \(y\) is rescaled as \(y^{\prime} = \frac{y}{2.5} - 1\). For instance
| Model | STS12 | STS13 | STS14 | STS15 | STS16 | STSb | SICK-R | Avg. |
|---|---|---|---|---|---|---|---|---|
| Avg. GloVe embeddings | 55.14 | 70.66 | 59.73 | 68.25 | 63.66 | 58.02 | 53.76 | 61.32 |
| Avg. BERT embeddings | 38.78 | 57.98 | 57.98 | 63.15 | 61.06 | 46.35 | 58.40 | 54.81 |
| BERT CLS-vector | 20.16 | 30.01 | 20.09 | 36.88 | 38.08 | 16.50 | 42.63 | 29.19 |
| InferSent - Glove | 52.86 | 66.75 | 62.15 | 72.77 | 66.87 | 68.03 | 65.65 | 65.01 |
| Universal Sentence Encoder | 64.49 | 67.80 | 64.61 | 76.83 | 73.18 | 74.92 | 76.69 | 71.22 |
| SBERT-NLI-base | 70.97 | 76.53 | 73.19 | 79.09 | 74.30 | 77.03 | 72.91 | 74.89 |
| SBERT-NLI-large | 72.27 | 78.46 | 74.90 | 80.99 | 76.25 | 79.23 | 73.75 | 76.55 |
| SRoBERTa-NLI-base | 71.54 | 72.49 | 70.80 | 78.74 | 73.69 | 77.77 | 74.46 | 74.21 |
| SRoBERTa-NLI-large | 74.53 | 77.00 | 73.18 | 81.85 | 76.82 | 79.10 | 74.29 | 76.68 |
Given an anchor sentence \(a\), a positive sentence \(p\), and a negative sentence \(n\):
We assume that a sentence is thematically closer to sentences within its section than to sentences from other sections
\(a\): McDonnell resigned from Martin in 1938 and founded McDonnell Aircraft Corporation in 1939
\(p\): In 1967, McDonnell Aircraft merged with the Douglas Aircraft Company to create McDonnell Douglas
\(n\): Born in Denver, Colorado, McDonnell was raised in Little Rock, Arkansas, and graduated from Little Rock High School in 1917
The authors assumed that sentences from the same Wikipedia section are more similar than those from different sections - Dor, YM, et al. (2018) Learning Thematic Similarity Metric from Article Sections Using Triplet Networks
Compute two Euclidean distances: \[ d_{ap} = \|s_a - s_p\|, \qquad d_{an} = \|s_a - s_n\| \]
Loss (with margin \(\epsilon\)): \[ \mathcal{L} = \max\big(d_{ap} - d_{an} + \epsilon,\ 0\big) \]
The margin \(\epsilon\) ensures that \(s_p\) is at least \(\epsilon\) closer to \(s_a\) than \(s_n\).
As metric Euclidean distance was used.
\(\epsilon=1\)
| \(d_{ap}\) | \(d_{an}\) | \(d_{ap}-d_{an}+1\) | Loss | Interpretation |
|---|---|---|---|---|
| 0.3 | 2.0 | \(-0.7\) | 0 | well-separated — no update |
| 0.3 | 0.9 | \(0.4\) | 0.4 | \(p\) closer, but less than \(\epsilon\) |
| 1.2 | 0.8 | \(1.4\) | 1.4 | \(n\) is closer — larger loss |
| Classification (NLI) | Regression (STS) | Triplet | |
|---|---|---|---|
| Data needed | labeled pairs (entailment/contradiction/neutral) | labeled pairs (0–5 similarity score) | (anchor, positive, negative) triplets — no score |
| Extra trainable layer? | yes — \(W_t\), size \(3n \times k\) | no | no |
| Similarity metric | — (cross-entropy on softmax) | cosine similarity | Euclidean distance |
| Loss | cross-entropy | MSE | hinge (\(\max(\cdot,0)\)) with margin |