Using Hugging Face Models in Python

Find, download and run Hugging Face models for embeddings and text generation.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 0 · Lesson 7 of 9 · Beginner

Using Hugging Face Models in Python

Find, download and run Hugging Face models for embeddings and text generation.

The Hugging Face Hub hosts hundreds of thousands of open models: embedding models, rerankers, text generators, speech and vision models. Many components of a RAG system can come from it and run on your own hardware. This lesson shows how to find a suitable model, download it, and run it with the sentence-transformers and transformers libraries.

What you will learn

  • How to find and evaluate models on the Hugging Face Hub
  • How to run embedding and reranking models with sentence-transformers
  • How to run a small text-generation model with the transformers pipeline
  • How to handle access tokens, gated models, caching and licences

Prerequisites

Installation

pip install sentence-transformers transformers torch accelerate

For an NVIDIA GPU, install the PyTorch build that matches your CUDA version, as described on the PyTorch website.

Finding a model

On huggingface.co/models, filter by task (for RAG: "Sentence Similarity" for embeddings, "Text Ranking" for rerankers, "Text Generation" for LLMs), then check each model card for:

  • Licence: some models do not allow commercial use.
  • Size: the number of parameters decides memory and speed.
  • Languages and maximum input length.
  • Usage instructions: prefixes or prompt formats the model expects.

Embeddings with sentence-transformers

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("BAAI/bge-small-en-v1.5")     # downloaded on first use
vectors = model.encode(["RAG retrieves documents.", "Vector databases store embeddings."],
                       normalize_embeddings=True)
print(vectors.shape, model.max_seq_length)
(2, 384) 512

Reranking with a cross-encoder

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("BAAI/bge-reranker-base")
scores = reranker.predict([
    ("How many leave days?", "Employees get 18 days of paid leave."),
    ("How many leave days?", "Laptops must be encrypted."),
])
print(scores)            # the first pair scores much higher

Text generation with the transformers pipeline

The pipeline API loads a model and its tokenizer in one line. Chat-tuned models accept a list of messages and apply their own chat template:

hf_generate.py
from transformers import pipeline

generator = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct", device_map="auto")

messages = [
    {"role": "system", "content": "Answer using only the context. Be brief."},
    {"role": "user", "content": "Context: Employees get 18 days of paid leave.\n\n"
                                "Question: How many leave days do employees get?"},
]
result = generator(messages, max_new_tokens=60)
print(result[0]["generated_text"][-1]["content"])     # the assistant's reply
Employees get 18 days of paid leave.

A 0.5-billion-parameter model runs on a CPU and is fine for learning; real applications need larger models, which need a GPU or a serving tool such as Ollama or vLLM. The output field structure can differ between library versions; check the transformers documentation for your version.

Access tokens and gated models

Some models (for example several Llama versions) are gated: you must accept the licence on the model page and authenticate. Create an access token in your Hugging Face account settings, then log in once:

huggingface-cli login

Newer versions of the huggingface_hub package also provide the shorter hf auth login command. Alternatively, set the HF_TOKEN environment variable (for example in .env). Never put tokens in notebooks you share.

Where models are stored

Downloaded files are cached (by default in a huggingface folder in your user cache directory) and reused. Set the HF_HOME environment variable to move the cache to a larger disk. For servers, download models once at build time so containers do not download them on every start.

Common errors and troubleshooting

  • 401 or "gated repo" errors: accept the licence on the model page and log in with a token.
  • Out of memory: choose a smaller model, use a GPU, or load a quantised version.
  • Very slow first run: the model is downloading; later runs use the cache.
  • trust_remote_code warnings: some models need custom code from the Hub; only enable it for models from sources you trust.

Key takeaways

  • Use sentence-transformers for embedding and reranking models, and transformers pipelines for generation.
  • Check licence, size, languages and usage instructions on every model card.
  • Authenticate with an access token for gated models; manage the cache with HF_HOME.

Frequently asked questions

Hugging Face pipeline or Ollama for local LLMs?

Ollama is easier for serving chat models to applications. The transformers library gives more control for experimentation, fine-tuning and custom pipelines.

Can I use Hugging Face models through an API instead?

Yes. Hugging Face offers hosted inference options; see its documentation for current services and pricing.

Practice exercises

  1. Find a multilingual embedding model on the Hub and test it with a Hindi query against English sentences.
  2. Compare the speed of bge-small and bge-base on 1,000 sentences.

Related tutorials