BERT
HuggingFace Transformers
intermediate layers
pre-trained model
deep learning

How to get intermediate layers' output of pre-trained BERT model in HuggingFace Transformers library?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Intermediate BERT representations are useful for probing, feature extraction, attribution experiments, and comparing how meaning evolves across transformer layers. In Hugging Face Transformers, the normal way to retrieve them is not by manually editing the model internals. You simply ask the model to return hidden states during the forward pass.

Enable Hidden States in the Forward Output

For a pretrained BERT model, load the tokenizer and model with output_hidden_states=True.

python
1import torch
2from transformers import AutoModel, AutoTokenizer
3
4tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
5model = AutoModel.from_pretrained(
6    "bert-base-uncased",
7    output_hidden_states=True,
8)
9
10inputs = tokenizer("Intermediate layers can be useful.", return_tensors="pt")
11
12with torch.no_grad():
13    outputs = model(**inputs)
14
15hidden_states = outputs.hidden_states
16print(len(hidden_states))
17print(hidden_states[0].shape)

For bert-base-uncased, hidden_states typically contains 13 tensors:

  • one embedding output
  • twelve encoder layer outputs

That first tensor surprises people. Index 0 is the embedding output, not the first transformer block.

Understand the Tensor Shapes

Each hidden-state tensor normally has shape (batch_size, sequence_length, hidden_size).

python
for index, layer_tensor in enumerate(hidden_states):
    print(index, tuple(layer_tensor.shape))

For BERT base, hidden_size is 768. If you tokenize one sentence, sequence_length includes special tokens such as [CLS] and [SEP], so the shape reflects the exact tokenized sequence rather than the number of words in the original string.

Extract a Specific Layer or Token

Once you have the hidden states, you can select any layer you want. For example, the last layer:

python
last_layer = hidden_states[-1]
print(last_layer.shape)

Or an intermediate layer:

python
layer_8 = hidden_states[8]
print(layer_8.shape)

If you want the representation of the first token in the sequence, often the [CLS] token:

python
cls_vector = hidden_states[-1][:, 0, :]
print(cls_vector.shape)

This is common when building sentence-level features, although the best layer is task-dependent and not always the final one.

Use Task-Specific Models Too

You are not limited to AutoModel. Task-specific models can also return hidden states if you enable them.

python
1import torch
2from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
4tokenizer = AutoTokenizer.from_pretrained("textattack/bert-base-uncased-imdb")
5model = AutoModelForSequenceClassification.from_pretrained(
6    "textattack/bert-base-uncased-imdb",
7    output_hidden_states=True,
8)
9
10inputs = tokenizer("The film was better than expected.", return_tensors="pt")
11
12with torch.no_grad():
13    outputs = model(**inputs)
14
15print(outputs.logits.shape)
16print(len(outputs.hidden_states))

That is useful when you want both the task output and the internal layer activations from the same forward pass.

Pool Intermediate Features Carefully

A common pattern is to take a full layer and pool it into one vector per input. Mean pooling over the attention-masked tokens is often more informative than blindly taking the final-layer [CLS] token.

python
1layer = hidden_states[-2]
2mask = inputs["attention_mask"].unsqueeze(-1)
3
4masked = layer * mask
5pooled = masked.sum(dim=1) / mask.sum(dim=1)
6print(pooled.shape)

This is a practical way to turn token-level representations into sentence-level features for clustering, retrieval, or downstream classifiers.

Common Pitfalls

The most common mistake is forgetting to enable hidden states, then trying to access outputs.hidden_states and finding it empty or missing.

Another issue is misreading the layer numbering. Because the embedding output comes first, hidden_states[1] is the first encoder layer, not hidden_states[0].

Memory usage is also easy to underestimate. Returning every layer for long sequences and large batches can consume a lot of GPU memory. Use torch.no_grad(), reduce batch size, or shorten sequences when running analysis jobs.

Finally, do not assume the last layer is always the best feature representation. For some tasks, intermediate layers carry more transferable information than the final task-adapted layer.

Summary

  • Enable output_hidden_states=True to retrieve intermediate BERT representations.
  • Hidden states include the embedding output plus one tensor per transformer layer.
  • Each layer tensor has shape (batch_size, sequence_length, hidden_size).
  • You can extract specific layers or token positions directly from outputs.hidden_states.
  • Intermediate layers are often useful for analysis and feature extraction, not just the final hidden state.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design