Using an AI model downloaded locally from Hugging Face is a common and efficient way to leverage powerful models without needing an internet connection for every inference or dealing with API rate limits.
Here's a comprehensive guide on how to do it, covering various model types and considerations:
How to Use a Locally Downloaded Hugging Face Model
The core idea is to point the transformers library to the local directory where you saved the model files.
I. Prerequisites
- Python: Ensure you have Python installed (3.8+ recommended).
- Virtual Environment (Highly Recommended): This isolates your project's dependencies.
python -m venv my_ai_env
source my_ai_env/bin/activate # On Windows: my_ai_env\Scripts\activate
- Install Libraries:
pip install transformers torch # Or tensorflow if the model uses TF
pip install accelerate # For better GPU utilization, especially for large models
pip install sentencepiece # Required by some tokenizers (e.g., Llama, T5)
pip install bitsandbytes # For 8-bit/4-bit quantization (if using it)
If you downloaded an image/audio model, you might need:
pip install Pillow # For image processing
pip install librosa soundfile # For audio processing
II. Download the Model Locally (if you haven't already)
You can download a model in a few ways:
-
Using from_pretrained (recommended):
The first time you load a model with from_pretrained, it's cached locally. You can specify a local directory directly.
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "mistralai/Mistral-7B-Instruct-v0.2" # Or any other model
# This will download the model to your Hugging Face cache directory (~/.cache/huggingface/hub)
# You can also specify a local_dir to save it explicitly:
# model = AutoModelForCausalLM.from_pretrained(model_name, local_dir="./my_local_model_path")
# tokenizer = AutoTokenizer.from_pretrained(model_name, local_dir="./my_local_model_path")
# To explicitly download and save to a specific path:
local_model_path = "./my_downloaded_mistral_model"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Save the model and tokenizer to your desired local path
model.save_pretrained(local_model_path)
tokenizer.save_pretrained(local_model_path)
print(f"Model and tokenizer saved to: {local_model_path}")
-
Manually from Hugging Face Hub:
Go to the model page on Hugging Face Hub (e.g., https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2/tree/main).
You can click the "Files and versions" tab and download individual files (pytorch_model.bin, config.json, tokenizer.json, vocab.txt, etc.) into a new local directory. This is less common but possible.
III. Load and Use the Local Model
Once you have the model files in a local directory (e.g., ./my_downloaded_mistral_model), loading is straightforward:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# --- 1. Define the local path where your model is stored ---
local_model_directory = "./my_downloaded_mistral_model" # Make sure this path exists and contains the model files
# --- 2. Load the Tokenizer ---
# The tokenizer is crucial for converting text into numbers (tokens) the model understands.
tokenizer = AutoTokenizer.from_pretrained(local_model_directory)
# --- 3. Load the Model ---
# Use AutoModelFor... appropriate for your task (e.g., AutoModelForCausalLM for text generation).
# Specify the device for inference (GPU if available, otherwise CPU)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
model = AutoModelForCausalLM.from_pretrained(
local_model_directory,
torch_dtype=torch.float16, # Use float16 for reduced memory usage and faster inference on GPUs
device_map="auto" # Automatically maps model layers to available devices (GPUs/CPU)
# trust_remote_code=True # Uncomment if the model requires custom code (e.g., some Llama models)
)
# If device_map="auto" is used, you don't need to do model.to(device) manually
# Otherwise: model.to(device)
model.eval() # Set model to evaluation mode (disables dropout, etc.)
# --- 4. Perform Inference (Example: Text Generation) ---
prompt = "Tell me a short story about a cat who learned to fly."
input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
print(f"Generating text for prompt: '{prompt}'...")
with torch.no_grad(): # Disable gradient calculations for inference to save memory and speed up
output_ids = model.generate(
input_ids,
max_new_tokens=100, # Max number of tokens to generate
num_return_sequences=1,
do_sample=True, # Whether to use sampling (true) or greedy decoding (false)
top_k=50, # Sample from top 50 tokens
top_p=0.95, # Sample from top P probability mass
temperature=0.7, # Controls randomness
eos_token_id=tokenizer.eos_token_id, # Stop generation when EOS token is generated
)
generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
print("\n--- Generated Story ---")
print(generated_text)
IV. Examples for Different Model Types/Tasks
The transformers library provides AutoModelFor... classes for various tasks. You just swap the AutoModelForCausalLM with the appropriate class.
1. Text Classification (e.g., Sentiment Analysis)
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
local_path = "./my_downloaded_sentiment_model" # e.g., "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(local_path)
model = AutoModelForSequenceClassification.from_pretrained(local_path)
model.eval()
text = "This movie was absolutely fantastic! I loved every minute of it."
inputs = tokenizer(text, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
# Get the predicted label
predicted_class_id = predictions.argmax().item()
predicted_label = model.config.id2label[predicted_class_id]
print(f"Text: '{text}'")
print(f"Predicted Sentiment: {predicted_label} (Confidence: {predictions[0][predicted_class_id]:.2f})")
2. Image Classification
from transformers import AutoModelForImageClassification, AutoImageProcessor
from PIL import Image
import requests
import torch
local_path = "./my_downloaded_image_model" # e.g., "google/vit-base-patch16-224"
# Example: Download an image
url = "http://images.cocofinder.com/wp-content/uploads/2021/04/13092244/cute-cat-pictures-cvr9i-a7.jpg"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
processor = AutoImageProcessor.from_pretrained(local_path)
model = AutoModelForImageClassification.from_pretrained(local_path)
model.eval()
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
# model predicts one of the 1000 ImageNet classes
predicted_label_id = logits.argmax(-1).item()
predicted_label = model.config.id2label[predicted_label_id]
print(f"Image classified as: {predicted_label}")
3. Audio Transcription (e.g., Whisper)
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
import torch
import librosa # pip install librosa soundfile
local_path = "./my_downloaded_whisper_model" # e.g., "openai/whisper-small"
# Example: Load an audio file (replace with your local audio file)
# If you don't have one, you can download a sample:
# !wget https://www.signalogic.com/melabs/test_audio/audio.wav -O sample.wav
audio_file = "sample.wav"
speech, sr = librosa.load(audio_file, sr=16000) # Whisper expects 16kHz audio
processor = AutoProcessor.from_pretrained(local_path)
model = AutoModelForSpeechSeq2Seq.from_pretrained(local_path)
model.eval()
input_features = processor(speech, sampling_rate=sr, return_tensors="pt").input_features
with torch.no_grad():
predicted_ids = model.generate(input_features)
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
print(f"Audio Transcription: {transcription}")
V. Important Considerations
-
Hardware (CPU vs. GPU):
- GPU (
"cuda"): Essential for large models and fast inference. Models should be moved to the GPU (model.to("cuda")).
- CPU (
"cpu"): Slower, but works if no GPU is available or for smaller models.
device_map="auto": For very large models that don't fit on a single GPU, device_map="auto" intelligently splits the model across available GPUs and CPU. Requires accelerate library.
-
Memory Usage:
-
Performance Optimization:
- Batching: Process multiple inputs at once. Create a list of prompts/inputs and tokenize them together.
torch.compile() (PyTorch 2.0+): Can compile your model to run faster.
# model = torch.compile(model) # After loading, before inference
BetterTransformer: Hugging Face's integration for optimized attention mechanisms.
# model = model.to_bettertransformer() # After loading, before inference
-
pipeline for Simplicity:
For many common tasks, transformers.pipeline offers a higher-level abstraction that handles tokenization, model loading, and output decoding for you. You can point it to your local path.
from transformers import pipeline
local_model_path = "./my_downloaded_sentiment_model" # or "./my_downloaded_mistral_model" for text-gen
# For text generation:
# generator = pipeline("text-generation", model=local_model_path, tokenizer=local_model_path, torch_dtype=torch.float16, device_map="auto")
# print(generator("Once upon a time, in a land far away...", max_new_tokens=50))
# For sentiment analysis:
classifier = pipeline("sentiment-analysis", model=local_model_path, tokenizer=local_model_path)
print(classifier("I hate this movie, it was terrible."))
By following these steps, you can effectively load and utilize your locally downloaded Hugging Face models for various AI tasks.