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.
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.
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).
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:
Or an intermediate layer:
If you want the representation of the first token in the sequence, often the [CLS] token:
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.
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.
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=Trueto 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.
Related reading
- How to get labels ids in Keras when training on multiple classes?
- How to get output of hidden layer given an input, weights and biases of the hidden layer in keras?
- How to get reproducible result when running Keras with Tensorflow backend
- How to Get Reproducible Results Keras, Tensorflow
- How to get summary information on tensorflow `RNN`
- How to get the best model when using EarlyStopping callback in Keras?
- How to get the CUDA version?
- How to get the dimensions of a tensor in TensorFlow at graph construction time?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.