TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Inside a Pretrained BERT

Inside a Pretrained BERT

BERT (Devlin et al., 2018) is the encoder-only transformer that made "pretrain once, fine-tune for every task" the default in NLP. Before you fine-tune one for classification, NER or retrieval in the next section, it pays to open one up: what is in the config, where the parameters are, what comes out of each layer, what the [CLS] vector and the "pooler" are, and what the pretrained masked-language-model head actually predicts. This lesson does that with the small BERT cached in the course image, google/bert_uncased_L-2_H-128_A-2: one of the 24 compact BERTs Google released with the paper by Turc et al. (2019), with 2 layers, hidden size 128 and 2 heads. It has the same code, the same tokenizer and the same pretraining recipe as BERT-base, at 4% of the size, which also means it is much weaker. The numbers below are reported as they are.

The architecture in numbers

A BERT model is three parts: an embedding layer (word, position and token-type tables, summed and normalised), a stack of LL encoder layers (post-norm blocks: self-attention, MLP, residuals, LayerNorm after each addition, as in the 2017 transformer), and a small pooler on top of the [CLS] position. With vocabulary VV, PP positions, hidden size HH and MLP width II (usually 4H4H), the parameter counts are:

Nemb=(V+P+2) H+2Hthree tables, LayerNormNlayer=4(H2+H)+2H⏟attention+2HI+I+H+2H⏟MLP=12H2+13H(I=4H)Npool=H2+HN=Nemb+L⋅Nlayer+Npool\begin{aligned} N_{\text{emb}} &= (V + P + 2)\,H + 2H && \text{three tables, LayerNorm} \\ N_{\text{layer}} &= \underbrace{4(H^2 + H) + 2H}_{\text{attention}} + \underbrace{2HI + I + H + 2H}_{\text{MLP}} = 12H^2 + 13H \quad (I = 4H) \\ N_{\text{pool}} &= H^2 + H \\ N &= N_{\text{emb}} + L \cdot N_{\text{layer}} + N_{\text{pool}} \end{aligned}

The "2" in the first line is the two token types (sentence A and sentence B). The formula in plain Python for four BERT sizes:

python · try it yourself
def bert_params(V, P, H, L, I, types=2):
    emb = (V + P + types) * H + 2 * H                  # word, position, token-type tables + LayerNorm
    attn = 4 * (H * H + H) + 2 * H                     # Q, K, V, output projection + LayerNorm
    ffn = (H * I + I) + (I * H + H) + 2 * H            # two linear layers + LayerNorm
    pooler = H * H + H
    return {"embeddings": emb, "layers": L * (attn + ffn), "pooler": pooler,
            "total": emb + L * (attn + ffn) + pooler}

for name, cfg in [("tiny  L=2  H=128", (30522, 512, 128, 2, 512)),
                  ("mini  L=4  H=256", (30522, 512, 256, 4, 1024)),
                  ("base  L=12 H=768", (30522, 512, 768, 12, 3072)),
                  ("large L=24 H=1024", (30522, 512, 1024, 24, 4096))]:
    p = bert_params(*cfg)
    share = p["embeddings"] / p["total"]
    print(f"{name}: total {p['total']:>11,}  embeddings {p['embeddings']:>10,} ({share:.0%})  "
          f"layers {p['layers']:>11,}  pooler {p['pooler']:>9,}")
tiny  L=2  H=128: total   4,385,920  embeddings  3,972,864 (91%)  layers     396,544  pooler    16,512
mini  L=4  H=256: total  11,170,560  embeddings  7,945,728 (71%)  layers   3,159,040  pooler    65,792
base  L=12 H=768: total 109,482,240  embeddings 23,837,184 (22%)  layers  85,054,464  pooler   590,592
large L=24 H=1024: total 335,141,888  embeddings 31,782,912 (9%)  layers 302,309,376  pooler 1,049,600

For the tiny model, 91% of the 4,385,920 parameters are the embedding tables: 30,522 WordPiece vectors of width 128 dominate two thin layers. In BERT-base (109,482,240 parameters, the "110M" of the paper) the embeddings are 22%, and in BERT-large 9%. Small models are mostly vocabulary, which is why shrinking the vocabulary or factorising the embedding (as ALBERT did) matters at small scale and hardly at all at large scale.

Loading it and checking the count

The recorded example loads the model with AutoModel (no task head), prints the config, groups the parameters by component and compares with the formula. Then it runs a batch of two sentences with output_hidden_states=True and checks the pooler.

python · try it yourself
import torch
from transformers import AutoTokenizer, AutoModel
from transformers.utils import logging
logging.set_verbosity_error()

name = "google/bert_uncased_L-2_H-128_A-2"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name).eval()
c = model.config
print(f"layers {c.num_hidden_layers}, hidden {c.hidden_size}, heads {c.num_attention_heads}, "
      f"intermediate {c.intermediate_size}, vocab {c.vocab_size}, positions {c.max_position_embeddings}")

groups = {}
for n, p in model.named_parameters():
    key = n.split(".")[0] if not n.startswith("encoder.layer.") else "encoder.layer." + n.split(".")[2]
    groups[key] = groups.get(key, 0) + p.numel()
for k, v in groups.items():
    print(f"  {k:16s} {v:>9,}")
print(f"  total            {sum(groups.values()):>9,}")

enc = tok(["The ferry leaves at noon.", "Bring a warm coat."], padding=True, return_tensors="pt")
print("input_ids:", enc["input_ids"][1].tolist())
print("tokens   :", tok.convert_ids_to_tokens(enc["input_ids"][1]))
with torch.no_grad():
    out = model(**enc, output_hidden_states=True)
print("hidden_states:", len(out.hidden_states), "tensors of", tuple(out.hidden_states[0].shape))
for i, h in enumerate(out.hidden_states):
    print(f"  layer {i}: mean vector norm {h[0].norm(dim=-1).mean().item():.2f}")
print("last_hidden_state == hidden_states[-1]:", torch.equal(out.last_hidden_state, out.hidden_states[-1]))

# The pooler: tanh(W h_[CLS] + b), trained on next-sentence prediction.
cls = out.last_hidden_state[:, 0]
manual = torch.tanh(model.pooler.dense(cls))
print("pooler_output == tanh(dense([CLS])):", torch.allclose(manual, out.pooler_output, atol=1e-6))
print("pooler_output:", tuple(out.pooler_output.shape), " first values:", [round(v, 3) for v in out.pooler_output[0, :4].tolist()])
layers 2, hidden 128, heads 2, intermediate 512, vocab 30522, positions 512
  embeddings       3,972,864
  encoder.layer.0    198,272
  encoder.layer.1    198,272
  pooler              16,512
  total            4,385,920
input_ids: [101, 3288, 1037, 4010, 5435, 1012, 102, 0]
tokens   : ['[CLS]', 'bring', 'a', 'warm', 'coat', '.', '[SEP]', '[PAD]']
hidden_states: 3 tensors of (2, 8, 128)
  layer 0: mean vector norm 13.59
  layer 1: mean vector norm 13.28
  layer 2: mean vector norm 12.40
last_hidden_state == hidden_states[-1]: True
pooler_output == tanh(dense([CLS])): True
pooler_output: (2, 128)  first values: [-1.0, -0.089, -1.0, 0.894]
  • The count matches the formula exactly: 3,972,864 for the embeddings, 12⋅1282+13⋅128=198,27212 \cdot 128^2 + 13 \cdot 128 = 198{,}272 per layer, 16,512 for the pooler, 4,385,920 in total.
  • Tokenisation and padding. The second sentence becomes [CLS] bring a warm coat . [SEP] plus one [PAD] (id 0) to match the first sentence's length. [CLS] is 101, [SEP] 102. The attention mask (not printed) is 0 at the padding, so no real token attends to it (tokenizers in practice).
  • Hidden states. output_hidden_states=True returns L+1=3L + 1 = 3 tensors of shape (2, 8, 128): the embedding output (layer 0) and the output of each encoder layer. last_hidden_state is the last of them. Because BERT is post-norm, every layer's output has passed through a LayerNorm, so the vector norms stay similar (13.59, 13.28, 12.40) instead of growing with depth as in a pre-norm stack.
  • The pooler is tanh(dense(h_[CLS])), confirmed exactly. It was trained on next-sentence prediction during pretraining; its outputs are saturated (several values are −1.0-1.0), a sign of a layer trained for a binary task. BertForSequenceClassification puts its classifier on top of this pooler output; many fine-tuning recipes instead use the raw [CLS] hidden state or mean pooling.

Which layer to use is a real choice. Probing studies on BERT-base found that lower layers carry more surface and syntactic information and upper layers more task-specific semantics; for feature extraction without fine-tuning, a middle-to-upper layer or an average of the last few is often better than the very last.

What the masked-LM head predicts

BERT was pretrained to fill in masked tokens. AutoModelForMaskedLM adds the pretraining head: a dense layer with GELU and LayerNorm, then a projection to the 30,522 vocabulary logits whose weight matrix is tied to the input word embeddings (the same tensor, which is why the head adds few parameters).

python · try it yourself
import torch
from transformers import AutoTokenizer, AutoModelForMaskedLM
from transformers.utils import logging
logging.set_verbosity_error()

name = "google/bert_uncased_L-2_H-128_A-2"
tok = AutoTokenizer.from_pretrained(name)
mlm = AutoModelForMaskedLM.from_pretrained(name).eval()
print("MLM head tied to the input embeddings:",
      mlm.cls.predictions.decoder.weight.data_ptr() == mlm.bert.embeddings.word_embeddings.weight.data_ptr())

sentences = [
    "the capital of france is [MASK] .",
    "she poured the [MASK] into a cup .",
    "he opened the door with a [MASK] .",
    "two plus two equals [MASK] .",
    "the children played in the [MASK] after school .",
]
for s in sentences:
    enc = tok(s, return_tensors="pt")
    pos = (enc["input_ids"][0] == tok.mask_token_id).nonzero().item()
    with torch.no_grad():
        logits = mlm(**enc).logits[0, pos]
    p = logits.softmax(-1)
    top = p.topk(5)
    words = ", ".join(f"{tok.convert_ids_to_tokens(i)} {v:.2f}" for v, i in zip(top.values.tolist(), top.indices.tolist()))
    print(f"{s:48s} -> {words}")
MLM head tied to the input embeddings: True
the capital of france is [MASK] .                -> france 0.30, spain 0.13, germany 0.03, algeria 0.03, canada 0.02
she poured the [MASK] into a cup .               -> water 0.07, bottle 0.07, cup 0.06, pool 0.04, table 0.04
he opened the door with a [MASK] .               -> door 0.52, window 0.03, seat 0.03, room 0.02, doorway 0.02
two plus two equals [MASK] .                     -> 2 0.07, 1 0.07, 3 0.04, two 0.03, . 0.03
the children played in the [MASK] after school . -> school 0.12, year 0.10, college 0.04, season 0.03, play 0.03

Read the predictions honestly. This 4M-parameter model has learned what kind of word fits, not facts:

  • "the capital of france is [MASK]" gives "france" (0.30), "spain", "germany": country names, the right category, but not "paris". BERT-base gets this one right, which is the gap between 4M and 110M parameters.
  • "she poured the [MASK] into a cup" puts "water" first, but only at 0.07, nearly tied with "bottle" and "cup".
  • "he opened the door with a [MASK]" predicts "door" at 0.52: repeating a word from the context is a cheap strategy small models over-use.
  • "two plus two equals [MASK]" spreads its weight over "2", "1", "3" (0.07 at most): no arithmetic.
  • "the children played in the [MASK] after school" gives "school", "year", "college": topical, not right ("park", "yard").

So this model is a shape demonstrator, good for learning the APIs and fine for fine-tuning experiments on small tasks, not a source of knowledge. Use it to learn the plumbing; expect BERT-base or larger for meaningful fill-in-the-blank behaviour.

Sentence vectors: [CLS] or mean pooling?

To turn BERT into a sentence encoder you need one vector per sentence. The two standard choices are the final hidden state at [CLS] and the mean of all token vectors, computed with the attention mask so that padding does not count:

hˉ=∑tmt ht∑tmt,mt∈{0,1} the attention mask\bar h = \frac{\sum_t m_t\, h_t}{\sum_t m_t}, \qquad m_t \in \{0, 1\} \text{ the attention mask}

The recorded example compares the cosine similarity of four sentence pairs, from paraphrase to unrelated, under both choices.

python · try it yourself
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
from transformers.utils import logging
logging.set_verbosity_error()

name = "google/bert_uncased_L-2_H-128_A-2"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name).eval()
pairs = [
    ("how do i reset my password", "i forgot my login password"),        # paraphrase
    ("the train to paris is late", "our train was delayed again"),       # related
    ("how do i reset my password", "the soup needs more salt"),          # unrelated
    ("the cat slept on the sofa", "stock prices fell sharply today"),    # unrelated
]
texts = [t for p in pairs for t in p]
enc = tok(texts, padding=True, return_tensors="pt")
with torch.no_grad():
    h = model(**enc).last_hidden_state                       # (8, T, 128)
cls = h[:, 0]
m = enc["attention_mask"].unsqueeze(-1).float()               # ignore padding in the mean
mean = (h * m).sum(1) / m.sum(1)
print("pair                                 [CLS] cos   mean-pool cos")
for k, (a, b) in enumerate(pairs):
    c1 = F.cosine_similarity(cls[2 * k], cls[2 * k + 1], dim=0).item()
    c2 = F.cosine_similarity(mean[2 * k], mean[2 * k + 1], dim=0).item()
    print(f"{a[:17]:17s} / {b[:17]:17s}  {c1:8.3f}   {c2:10.3f}")
# Padding must not change a sentence's mean-pooled vector:
alone = tok(texts[2], return_tensors="pt")
with torch.no_grad():
    single = model(**alone).last_hidden_state.mean(1)[0]
print("mean pooling with mask == unpadded mean:", torch.allclose(single, mean[2], atol=1e-5))
pair                                 [CLS] cos   mean-pool cos
how do i reset my / i forgot my login     0.939        0.912
the train to pari / our train was del     0.819        0.785
how do i reset my / the soup needs mo     0.725        0.682
the cat slept on  / stock prices fell     0.620        0.594
mean pooling with mask == unpadded mean: True

Both orderings are right (paraphrase above related above unrelated), but look at the scale: even "the cat slept on the sofa" and "stock prices fell sharply today" have cosine 0.620 under [CLS] and 0.594 under mean pooling. Raw BERT vectors are anisotropic: they occupy a narrow cone, so every pair looks similar, and a fixed threshold such as "cosine above 0.7 means same topic" is meaningless. The [CLS] vector of a model that was never fine-tuned for similarity is particularly unreliable. The fix is training: sentence-transformers fine-tune the encoder with a contrastive objective so that cosine similarity becomes meaningful (Sentence Embeddings, and Dense Retrieval in this course). The last line checks the masked mean: the padded sentence's pooled vector equals the vector computed without padding.

Pitfalls

  • Mean pooling without the mask. h.mean(1) averages [PAD] vectors into every short sentence, so the same sentence gets different vectors in different batches.
  • Cosine thresholds on raw BERT vectors. Anisotropy makes all cosines high; compare rankings, or use a model trained for similarity.
  • Uncased versus cased. This model lower-cases and strips accents in its tokenizer. Feeding text to a cased model's tokenizer that was meant for an uncased one (or the reverse) silently changes the token ids.
  • More than 512 tokens. The position table has 512 rows; truncate or window (positional encoding).
  • Reading facts from a small MLM. Fill-mask predictions of small models reflect word categories and co-occurrence, not knowledge. Even large models' fill-mask outputs are not a knowledge base.
  • Missing token_type_ids for sentence pairs. Pair tasks (question + passage) need segment ids 0 and 1; the tokenizer creates them when called with two texts, tok(a, b).

Practice

  1. Using bert_params, how many parameters would the tiny model have with a 50,000-token vocabulary? What share would the embeddings be?
Answer

Embeddings (50000+512+2)⋅128+256=6,466,048(50000 + 512 + 2) \cdot 128 + 256 = 6{,}466{,}048; layers and pooler unchanged (396,544+16,512396{,}544 + 16{,}512), so the total is 6,879,1046{,}879{,}104, and the embeddings are 94% of it.

  1. Derive the per-layer count 12H2+13H12H^2 + 13H from the components: which terms give the 13H13H?
Answer

Attention: 4 weight matrices (4H24H^2) and 4 biases (4H4H), LayerNorm 2H2H. MLP with I=4HI = 4H: weights 2⋅4H2=8H22 \cdot 4H^2 = 8H^2, biases 4H+H=5H4H + H = 5H, LayerNorm 2H2H. Total 12H2+(4+2+5+2)H=12H2+13H12H^2 + (4 + 2 + 5 + 2)H = 12H^2 + 13H.

  1. In ib2.py, why does hidden_states have 3 entries for a 2-layer model, and which entry would you use for a token tagger?
Answer

Entry 0 is the embedding output (before any layer), entries 1 and 2 are the outputs of the two encoder layers. A tagger normally fine-tunes and uses the last one (last_hidden_state); for frozen features, trying an average of the last layers is worth it.

  1. Change the mean pooling in ib4.py to h.mean(1) without the mask. Which sentence vectors change, and why?
Answer

Every sentence shorter than the longest one in the batch: their [PAD] positions now enter the average. The longest sentences (no padding) are unchanged; the final check prints False whenever the third sentence is shorter than the longest one in the batch.

Test yourself

Which part holds most of the parameters of the tiny BERT (2 layers, hidden 128)?

  1. The two encoder layers
  2. The embedding tables, about 91%
  3. The pooler
  4. The attention heads

What is BERT's pooler output?

  1. The mean of all token vectors
  2. tanh⁡(Wh[CLS]+b)\tanh(W h_{[\text{CLS}]} + b), a layer trained on next-sentence prediction
  3. The logits of the masked-LM head
  4. The embedding of the [CLS] token before the first layer

With output_hidden_states=True, a BERT with LL layers returns how many hidden-state tensors?

  1. LL
  2. L+1L + 1, including the embedding output
  3. 2L2L
  4. 1

Why is mean pooling done with the attention mask?

  1. To make it faster
  2. So that padding positions do not enter the average and a sentence gets the same vector in any batch
  3. Because BERT has no [CLS] token
  4. To normalise the vector

The tiny BERT predicts 'france' for 'the capital of france is [MASK] .' What does that suggest?

  1. The tokenizer is broken
  2. A 4M-parameter MLM learns word categories and co-occurrence rather than facts
  3. The [MASK] token was not found
  4. BERT cannot predict city names