Okay, here is a complete, runnable Python code example demonstrating how to load and use a pre-trained model downloaded locally from Hugging Face.
This example will:
- Simulate downloading a model (
distilbert-base-uncased for speed) to a specific local directory. You can skip this simulation part if you already have your model files ready.
- Load the tokenizer and model from that specified local directory.
- Perform inference to get embeddings for a sample text.
- Add a simple classification head and demonstrate its usage.
import torch
import os
from transformers import AutoTokenizer, AutoModel, DistilBertModel, DistilBertTokenizer
# --- Configuration ---
# 1. Define the Hugging Face model name you want to use.
# We'll use 'distilbert-base-uncased' as it's relatively small and fast.
MODEL_NAME = "distilbert-base-uncased"
# 2. Define the LOCAL directory where your model files are saved or will be saved.
# *** IMPORTANT: You MUST change this path to where YOUR model files are located! ***
# Example paths:
# - Windows: r"C:\Users\YourUsername\Models\distilbert-base-uncased"
# - Linux/macOS: "/home/yourusername/models/distilbert-base-uncased"
#
# For this example, we'll create a subdirectory './my_local_model' relative to this script.
LOCAL_MODEL_DIR = "./my_local_model"
print(f"Using MODEL_NAME: '{MODEL_NAME}'")
print(f"Looking for/Saving model files to: '{os.path.abspath(LOCAL_MODEL_DIR)}'")
print("-" * 60)
# --- Step 1: Ensure Model Files Exist Locally (Simulation) ---
# This block helps make the example runnable even if you haven't manually downloaded yet.
# It downloads the model to the Hugging Face cache and then saves it to LOCAL_MODEL_DIR.
# If you ALREADY have your model files in LOCAL_MODEL_DIR, you can comment out or skip this block.
print("--- Step 1: Ensuring Model Files Exist Locally ---")
try:
# Check if the target directory already exists and has files
if not os.path.exists(LOCAL_MODEL_DIR) or not os.listdir(LOCAL_MODEL_DIR):
print(f"'{LOCAL_MODEL_DIR}' is empty or does not exist. Attempting to download '{MODEL_NAME}'...")
# Download the model and tokenizer from Hugging Face Hub to the cache
# This step downloads files like config.json, pytorch_model.bin, etc.
print("Downloading model and tokenizer to Hugging Face cache...")
temp_tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
temp_model = AutoModel.from_pretrained(MODEL_NAME)
# Create the local directory if it doesn't exist
if not os.path.exists(LOCAL_MODEL_DIR):
os.makedirs(LOCAL_MODEL_DIR)
print(f"Created directory: {LOCAL_MODEL_DIR}")
# Save the downloaded tokenizer and model files to our specified local directory
print(f"Saving tokenizer and model files to '{LOCAL_MODEL_DIR}'...")
temp_tokenizer.save_pretrained(LOCAL_MODEL_DIR)
temp_model.save_pretrained(LOCAL_MODEL_DIR)
print("Model and tokenizer saved successfully to local directory.")
# Clean up temporary objects to free memory
del temp_tokenizer
del temp_model
else:
print(f"Model files already found in '{LOCAL_MODEL_DIR}'. Skipping download.")
except Exception as e:
print(f"\nError during model download/save simulation: {e}")
print("Please ensure you have an internet connection or that the model files are correctly placed in the specified LOCAL_MODEL_DIR.")
# If this step fails critically, you might want to exit or handle the error.
# For this script, we'll continue assuming the user might manually provide files.
print("-" * 60)
# --- Step 2: Load Tokenizer and Model from Local Directory ---
print("--- Step 2: Loading Tokenizer and Model Locally ---")
# Verify the directory exists before attempting to load
if not os.path.exists(LOCAL_MODEL_DIR) or not os.listdir(LOCAL_MODEL_DIR):
print(f"Error: The specified local directory '{LOCAL_MODEL_DIR}' does not exist or is empty.")
print("Please ensure the directory contains the model files (e.g., config.json, pytorch_model.bin, vocab.txt).")
exit() # Exit if the directory isn't ready
try:
# Load the tokenizer from the specified local directory
# AutoTokenizer automatically detects the tokenizer type based on config files
tokenizer = AutoTokenizer.from_pretrained(LOCAL_MODEL_DIR)
print("Tokenizer loaded successfully from:", LOCAL_MODEL_DIR)
# Load the model from the specified local directory
# AutoModel automatically detects the model architecture
model = AutoModel.from_pretrained(LOCAL_MODEL_DIR)
print("Model loaded successfully from:", LOCAL_MODEL_DIR)
# --- Optional: Using specific classes ---
# If you know the exact model type (e.g., DistilBERT), you can use specific classes:
# tokenizer = DistilBertTokenizer.from_pretrained(LOCAL_MODEL_DIR)
# model = DistilBertModel.from_pretrained(LOCAL_MODEL_DIR)
# Set the model to evaluation mode (important for inference)
model.eval()
# Check if GPU is available and move the model to the GPU if possible
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
print(f"Model moved to device: {device}")
except Exception as e:
print(f"\nError loading model or tokenizer from '{LOCAL_MODEL_DIR}': {e}")
print("Please double-check the contents of the directory and ensure they are compatible model files.")
exit()
print("-" * 60)
# --- Step 3: Prepare Input Text and Tokenize ---
print("--- Step 3: Preparing Input and Tokenizing ---")
text_input = "Using AI models locally is a great way to control your data and compute."
print(f"Input text: '{text_input}'")
# Tokenize the input text.
# - return_tensors='pt': Returns PyTorch tensors. Use 'tf' for TensorFlow.
# - padding=True: Pads shorter sequences to the length of the longest sequence in the batch.
# - truncation=True: Truncates sequences longer than the model's maximum input length.
inputs = tokenizer(text_input, return_tensors="pt", padding=True, truncation=True)
# Move the tokenized inputs to the same device as the model (CPU or GPU)
inputs = {key: val.to(device) for key, val in inputs.items()}
print("Input tokenized and moved to device.")
# print(f"Tokenized Inputs: {inputs}") # Uncomment to see token IDs, attention mask, etc.
print(f"Input IDs shape: {inputs['input_ids'].shape}")
print(f"Attention Mask shape: {inputs['attention_mask'].shape}")
print("-" * 60)
# --- Step 4: Perform Inference (Get Embeddings) ---
print("--- Step 4: Performing Inference (Getting Embeddings) ---")
# Disable gradient calculations for inference to save memory and computation
with torch.no_grad():
# Pass the tokenized inputs through the model
# The output object contains various model outputs depending on the architecture
outputs = model(**inputs)
# Common outputs for AutoModel include:
# - last_hidden_state: The hidden states output by the last layer of the model.
# Shape: (batch_size, sequence_length, hidden_size)
# - pooler_output: The hidden state of the first token ([CLS]) after a pooling operation.
# Often used as input for classification tasks. Shape: (batch_size, hidden_size)
last_hidden_states = outputs.last_hidden_state
pooler_output = outputs.pooler_output
print(f"Shape of last_hidden_states: {last_hidden_states.shape}")
print(f"Shape of pooler_output: {pooler_output.shape}")
print("-" * 60)
# --- Step 5: Example Downstream Task - Simple Classification ---
# We'll add a simple linear layer on top of the pooler_output to perform a dummy classification task.
# This is just to show how you might use the model's output.
print("--- Step 5: Example Downstream Task (Simple Classification) ---")
# Get the dimensionality of the hidden states (e.g., 768 for BERT-base, 768 for DistilBERT-base)
hidden_size = model.config.hidden_size
# Define the number of output classes for our dummy task (e.g., 2 classes: positive/negative sentiment)
num_classes = 2
# Create a simple classification head (a linear layer)
# This layer takes the pooler_output and maps it to the number of classes.
classification_head = torch.nn.Linear(hidden_size, num_classes).to(device)
# --- IMPORTANT NOTE ---
# In a real scenario, if you downloaded a model *already fine-tuned* for classification
# (e.g., bert-base-uncased-finetuned-sst2), you would load it using `AutoModelForSequenceClassification`
# and it would already have this head included.
# Here, we are demonstrating adding a head to a base model.
# Pass the pooler_output through the classification head to get logits
logits = classification_head(pooler_output)
print(f"Classification head input shape (pooler_output): {pooler_output.shape}")
print(f"Classification logits output shape: {logits.shape}")
# To get the predicted class ID:
predicted_class_id = torch.argmax(logits, dim=1).item()
print(f"Predicted class ID: {predicted_class_id}")
# You would typically map this ID to a meaningful label (e.g., 0 -> 'Negative', 1 -> 'Positive')
print("\n--- Code Example Finished ---")
print("You have successfully loaded and used a local Hugging Face model!")
How to Run This Code:
- Save the code: Save the code above as a Python file (e.g.,
use_local_model.py).
- Install Libraries: Make sure you have the necessary libraries installed:
pip install torch transformers
- Create Local Directory (Optional but Recommended):
- If you haven't already, create a folder named
my_local_model in the same directory where you saved the Python script.
- Alternatively, modify the
LOCAL_MODEL_DIR variable in the script to point to any existing folder where you have downloaded model files (e.g., config.json, pytorch_model.bin or model.safetensors, vocab.txt, etc.).
- Run the script:
python use_local_model.py
The script will first attempt to download distilbert-base-uncased if the my_local_model directory is empty, and then proceed to load and use it. If you already have the files in my_local_model, it will skip the download step.