Hello! Welcome to the next lesson in our journey through Transformer Architectures.
In our last session, we explored the theoretical blueprints of modern language models, contrasting the three main architectures: encoder-only (like BERT), decoder-only (like GPT), and encoder-decoder (like T5). We discussed how their designs make them suitable for different kinds of tasks—understanding, generating, or transforming text.
Today, we transition from theory to practice. As a software engineer, you know that understanding a concept is one thing, but using it effectively via an API or library is another. This lesson is all about that practical step. Our goal is to learn how to use the Hugging Face transformers library to load a pre-trained model and tokenizer. This is your entry point into applying the powerful models we've been discussing.
The Hugging Face Ecosystem
Before we dive into the code, it's helpful to understand what "Hugging Face" is. It's not just a single library, but a whole ecosystem for machine learning. Think of it as the "GitHub for AI."

The main components you'll interact with are:
- The Hugging Face Hub: A massive, open-source repository where researchers and companies share pre-trained models, datasets, and demos. This is where we'll find the models to download.
- The
transformerslibrary: A Python library that provides a standardized, easy-to-use interface for downloading and using the models from the Hub. - Other libraries: Like
datasetsfor loading data andevaluatefor measuring performance, which we'll encounter later.
For a software engineer, a good analogy is this: The Hub is like a package registry (e.g., PyPI, npm), and the transformers library is like your package manager (pip, npm) and framework combined, giving you the tools to download and work with those packages (models).
Setting Up Your Environment
First, you'll need to install the necessary libraries. The transformers library depends on a deep learning framework like PyTorch or TensorFlow. We will be using PyTorch throughout this course.
You can install them using pip:
# Install PyTorch first
pip install torch
# Then install the core Hugging Face libraries
pip install transformers
(Note: If you have a CUDA-enabled GPU, you should follow the specific installation instructions on the PyTorch website to enable GPU acceleration.)
Core Components: Tokenizers and Models
To use a pre-trained model, you always need two things:
-
The Tokenizer: A transformer model doesn't understand raw text. It works with numbers. The tokenizer is a utility that converts your text into a numerical representation that the model can process. This involves several steps:
- Splitting the text into tokens (words, sub-words, or characters).
- Mapping each token to a unique integer ID from a vocabulary.
- Adding special tokens required by the model (like
[CLS]or[SEP]). - Creating an "attention mask" to tell the model which tokens are real and which are padding.
-
The Model: This is the pre-trained neural network itself. It contains the architecture (the stack of encoder/decoder blocks) and the learned weights (the "knowledge" it gained from its training).
The AutoClass Abstraction
Hugging Face provides a wonderfully simple abstraction for loading these components: the AutoClass. You'll primarily use AutoTokenizer and various AutoModel classes.
The beauty of this approach is that you don't need to know the exact Python class for the model you want to use. You simply tell the AutoClass which model checkpoint (a specific pre-trained model saved from training) you want to load from the Hub, and it automatically figures out the correct architecture and tokenizer to download.
This is a powerful design pattern that you'll appreciate as a developer. It decouples your code from specific model implementations, allowing you to switch from, say, BERT to another model like RoBERTa by changing just one line of code.
Let's start by learning more about the tokenizer.
Guide to Hugging Face AutoModelFor** Classes and ...
The following article gives a concise and practical overview of the AutoTokenizer. Focus on understanding its role and the common arguments used when calling it.
From the article, please read the sections titled 'The Role of Tokenizers' and 'AutoTokenizer'. Pay close attention to the bulleted list under 'What AutoTokenizer Handles' and the 'Usage Pattern' code block.
Loading Your First Model and Tokenizer
Let's put this into practice. We'll load bert-base-uncased, a classic encoder-only model, perfect for understanding-based tasks.
Step 1: Load the tokenizer
We use AutoTokenizer.from_pretrained() and pass it the model checkpoint name from the Hub.
from transformers import AutoTokenizer
checkpoint = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
print(f"Tokenizer loaded: {type(tokenizer)}")
Output: Tokenizer loaded: <class 'transformers.models.bert.tokenization_bert_fast.BertTokenizerFast'>
Notice how AutoTokenizer correctly instantiated a BertTokenizerFast object for us.
Step 2: Use the tokenizer
Now, let's see what the tokenizer does to a sentence.
raw_text = "Hello, this is our first transformer model!"
# The tokenizer returns a dictionary of tensors
tokenized_inputs = tokenizer(raw_text, padding=True, truncation=True, return_tensors="pt")
print(tokenized_inputs)
Output:
{
'input_ids': tensor([[ 101, 7592, 1010, 2023, 2003, 2256, 2034, 19081, 3325, 999, 102]]),
'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]),
'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
}
Here's what this output means:
input_ids: These are the numerical IDs for each token. Notice the101at the start and102at the end—these are the special[CLS]and[SEP]tokens for BERT.token_type_ids: This is used to distinguish between different sentences in sentence-pair tasks. Since we only have one sentence, it's all zeros.attention_mask: This tells the model which tokens to pay attention to. It's all ones because every token is real. If we had added padding, we would see zeros for the padding tokens.
Step 3: Load the model
Next, we load the model itself using AutoModel. We use the same from_pretrained() method.
The official Hugging Face Quickstart guide provides a great example of the from_pretrained() method in action. It's the central function you'll use constantly to load models.
Please read the section 'Pretrained models'. Focus on how AutoClass and from_pretrained() are used together to load a model and its preprocessor (tokenizer).
Now, let's write the code. We'll use AutoModel, which loads the base transformer architecture without any specific task-related head on top. This is great for feature extraction.
from transformers import AutoModel
import torch
model = AutoModel.from_pretrained(checkpoint)
print(f"Model loaded: {type(model)}")
Output: Model loaded: <class 'transformers.models.bert.modeling_bert.BertModel'>
Again, AutoModel correctly identified that bert-base-uncased corresponds to the BertModel class.
Step 4: Get model outputs
Finally, we pass our tokenized inputs to the model to get its output. We use the ** operator to unpack the dictionary from the tokenizer as keyword arguments.
# Ensure the model is in evaluation mode
model.eval()
with torch.no_grad(): # Disable gradient calculation for inference
outputs = model(**tokenized_inputs)
# The primary output is the last_hidden_state
last_hidden_state = outputs.last_hidden_state
print(f"Shape of last_hidden_state: {last_hidden_state.shape}")
Output: Shape of last_hidden_state: torch.Size([1, 11, 768])
This shape [1, 11, 768] corresponds to:
- 1: The batch size (we processed one sentence).
- 11: The sequence length (our sentence was tokenized into 11 tokens).
- 768: The hidden size of the
bert-base-uncasedmodel. Each of our 11 tokens has been converted into a dense vector of 768 numbers that represents its meaning in the context of the sentence.
This last_hidden_state is the rich, contextual embedding that makes encoder models so powerful for understanding tasks.
Test your understanding!
Write the Python code to load the tokenizer and model for the distilbert-base-uncased checkpoint. This is a smaller, faster version of BERT. What do you expect to be different about the last_hidden_state shape compared to bert-base-uncased?
Show answer
The code is nearly identical, you just change the checkpoint name. This highlights the power of the AutoClass abstraction.
from transformers import AutoTokenizer, AutoModel
checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModel.from_pretrained(checkpoint)
print(f"Tokenizer type: {type(tokenizer)}")
print(f"Model type: {type(model)}")
# Let's check the hidden size
print(f"Hidden size: {model.config.hidden_size}")
Output:
Tokenizer type: <class 'transformers.models.distilbert.tokenization_distilbert_fast.DistilBertTokenizerFast'>
Model type: <class 'transformers.models.distilbert.modeling_distilbert.DistilBertModel'>
Hidden size: 768
The hidden size for distilbert-base-uncased is also 768, so the shape of the last_hidden_state tensor will be [batch_size, sequence_length, 768], just like bert-base-uncased. The main difference is that the DistilBERT model has fewer layers, making it faster but slightly less accurate.
Preview: Models for Specific Tasks
So far, we've used AutoModel, which gives us the raw hidden states. But what if we want to perform a specific task, like text classification or question answering?
This is where the AutoModelFor... classes come in. These classes load the base model and add a task-specific "head" on top. For example:
AutoModelForSequenceClassification: Adds a classification layer to classify the entire sequence.AutoModelForCausalLM: The standard class for decoder-only models used for text generation (like GPT-2).AutoModelForSeq2SeqLM: For encoder-decoder models used in tasks like translation or summarization.
The loading process is exactly the same, you just change the class name.
from transformers import AutoModelForSequenceClassification
# This loads BERT with a classification head on top
# Note the warning: some weights were not initialized (the head)
# This is expected, as the head needs to be fine-tuned on a specific task
model_for_classification = AutoModelForSequenceClassification.from_pretrained(checkpoint)
print(f"Model for classification: {type(model_for_classification)}")
This concept is key to applying transformers to real-world problems.
Guide to Hugging Face AutoModelFor** Classes and ...
To see how this pattern extends to the architectures we learned about in the last lesson, quickly scan through the following sections of the guide. The goal isn't to memorize every class, but to appreciate the consistent design pattern.
Quickly scan the sections for AutoModel, AutoModelForSequenceClassification, AutoModelForQuestionAnswering, AutoModelForCausalLM, and AutoModelForSeq2SeqLM. Notice how the class name directly maps to a task and that the loading pattern from_pretrained(model_name) remains the same.
Conclusion
Congratulations! You've successfully bridged the gap from theory to practice. You now have the fundamental skill required to work with nearly any model in the Hugging Face Hub.
Key Takeaways:
- The Hugging Face ecosystem, centered around the Hub and the
transformerslibrary, provides the tools to download and use thousands of pre-trained models. - Every model is paired with a tokenizer that converts text into a numerical format the model can understand.
- The
AutoClasspattern (AutoTokenizer,AutoModel, etc.) offers a powerful and flexible abstraction for loading any model architecture with the simplefrom_pretrained("model-name")method. AutoModelloads the base transformer for feature extraction, while classes likeAutoModelForSequenceClassificationadd a task-specific head, preparing the model for fine-tuning.
Next Up:
We've loaded a model and seen its raw output. In the next lesson, we'll put it to work. We will apply a pre-trained encoder model for a downstream task: text classification. You'll learn how to take the AutoModelForSequenceClassification we just previewed, run an input through it, and get a concrete prediction.