A great question about leveraging the awesome models from Hugging Face 🤗!
Using a pre-trained model downloaded locally from Hugging Face is relatively straightforward. Here's a step-by-step guide to help you get started:
Prerequisites
Python: Make sure you have Python (3.6+) installed on your system.
Transformers library: Install the Hugging Face transformers library using pip:
code
pip install transformers
This library provides a unified API for many transformer-based models.
Model download: Download your desired model from the Hugging Face Model Hub. You can do this in two ways:
Using the website: Go to the model page (e.g., bert-base-uncased), click on the Files and versions tab, and download the model files (e.g., config.json, pytorch_model.bin, vocab.txt, etc.) manually.
Using the transformers library: Run the following Python code to download the model programmatically:
python
from transformers import AutoModel, AutoTokenizer
model_name = "bert-base-uncased" # replace with your model name
model = AutoModel.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
This will download the model and tokenizer files to your local cache directory (usually ~/.cache/huggingface/transformers/ on Linux/Mac or C:\Users\<username>\.cache\huggingface\transformers\ on Windows).
Loading the model locally
Assuming you've downloaded the model files, let's load them locally. We'll cover two scenarios:
Scenario 1: Model files downloaded manually
If you downloaded the model files manually, you'll need to specify the local path to the model directory containing the files (e.g., config.json, pytorch_model.bin, etc.).
Here's an example:
python
from transformers import BertTokenizer, BertModel
# Specify the local path to the model directory
model_path = "/path/to/downloaded/model/bert-base-uncased"
# Load the tokenizer and model from the local path
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertModel.from_pretrained(model_path)
Scenario 2: Model files downloaded using transformers library
If you downloaded the model using the transformers library (as shown in the Prerequisites section), the model files are cached locally. You can load the model by specifying the cache_dir argument:
python
from transformers import AutoModel, AutoTokenizer
model_name = "bert-base-uncased"
cache_dir = "~/.cache/huggingface/transformers/" # default cache directory
# Load the model and tokenizer from the local cache
model = AutoModel.from_pretrained(model_name, cache_dir=cache_dir)
tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=cache_dir)
Alternatively, you can also specify the local_files_only=True argument to force the library to look for the model files only in the local cache:
python
model = AutoModel.from_pretrained(model_name, local_files_only=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, local_files_only=True)
Using the loaded model
Now that you've loaded the model and tokenizer, you can use them for inference, fine-tuning, or other tasks. Here's a simple example using the loaded bert-base-uncased model for text classification:
python
import torch
# Prepare input text
text = "Hello, how are you?"
inputs = tokenizer(text, return_tensors="pt")
# Forward pass
outputs = model(**inputs)
# Get the last hidden state
last_hidden_state = outputs.last_hidden_state
# Use the pooled output for classification (e.g., sentiment analysis)
pooled_output = outputs.pooler_output
print(pooled_output.shape) # Should be torch.Size([1, 768])
# Add a classification head (e.g., a simple linear layer)
classification_head = torch.nn.Linear(768, 8) # 8 classes for example
logits = classification_head(pooled_output)
print(logits.shape) # Should be torch.Size([1, 8])
That's it! You've successfully loaded and used a pre-trained model downloaded locally from Hugging Face.
Tips and Variations
For TensorFlow models, use TFAutoModel and TFAutoTokenizer from transformers instead.
To fine-tune the model on your custom dataset, create a custom dataset class, data loader, and train the model using your preferred optimizer and loss function.
Consult the Hugging Face transformersdocumentation and examples for more use cases, such as language translation, question answering, and text generation.