Level 3 In-Depth AI · Programming and Tools
The Hugging Face Ecosystem
Hugging Face is where the AI community shares open models and datasets, and its Python libraries load any of them in a few lines. The Hub, model cards, pipelines, tokenizers, AutoModel classes, the datasets library, and running an open language model yourself.
- Level
- ●●●●● Easy
- Reading
- 10 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 32 concepts →
- Quiz
- 5 questions ↓
This leads to
Fine-Tuning an Open Model in PracticeThe full path from zero — 32 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Matrices and Matrix Multiplication
- Partial Derivatives and Gradients
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Tensors and Shapes
- Gradient Descent
- NumPy and Array Thinking
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Recurrent Neural Networks
- Activation Functions
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- The Hugging Face Ecosystem
Read them roughly in this order. See it on the concept map →
Why it matters
Training a modern language or vision model from scratch costs far more than most people can spend. Fortunately you rarely need to. Thousands of organisations and individuals publish pretrained models with their weights, ready to use or to fine-tune on your own data. Most of them are published on Hugging Face.
Hugging Face is two things:
- The Hub (huggingface.co), a website that hosts models, datasets and small demo apps, a kind of GitHub for AI. As of late 2026 it hosts around three million public models, from tiny sentiment classifiers to open-weight large language models such as Meta's Llama, Mistral, Qwen and DeepSeek families, plus image generators, speech recognisers and embedding models.
- A set of open-source Python libraries that download and run those models with a few lines of code. The best known is
transformers, alongsidedatasets,tokenizers,huggingface_hub,peft(for LoRA),diffusers(for Diffusion Models) and others.
If you want to try a sentence-embedding model for Embeddings and Semantic Search, fine-tune BERT on your own labels, or run an open LLM on your own machine, this is almost always where you start.
The intuition
Think of the Hub as a vast library of pre-built engines, and transformers as a universal adapter that bolts any of them onto your code.
Every model on the Hub lives in a repository with a name such as distilbert/distilbert-base-uncased-finetuned-sst-2-english (organisation, then model). The repository holds:
- the weights, the billions of learned numbers, usually in the safetensors format;
- a config file describing the architecture (how many layers, how wide);
- the tokenizer files that turn text into tokens;
- a model card, a README explaining what the model is for, how it was trained, its limitations and its licence.
When your code says from_pretrained("some/model"), the library reads the config, builds the right PyTorch architecture, downloads the weights into a local cache and loads them. The next time it uses the cache, so it works offline.
How it works
Install the libraries into your environment:
pip install transformers datasets accelerate
The code below was run with transformers 5.x and PyTorch on a laptop CPU. The first run of each example downloads the model, a few hundred megabytes, so it needs internet access.
Level 1: pipelines
A pipeline bundles everything needed for one task (tokenizer, model and post-processing) into one callable object. You name the task and, ideally, the exact model:
from transformers import pipeline
classifier = pipeline("text-classification",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
classifier(["I finally understand backpropagation!",
"The training run crashed again after six hours."])
# [{'label': 'POSITIVE', 'score': 0.9868948459625244},
# {'label': 'NEGATIVE', 'score': 0.9994056224822998}]
This model is DistilBERT, a smaller version of BERT, fine-tuned on movie-review sentences labelled positive or negative. Other pipeline tasks include "text-generation", "zero-shot-classification", "automatic-speech-recognition", "image-classification", "object-detection" and "feature-extraction" (embeddings). Always pass model= explicitly. If you leave it out, the library picks a default that may change between versions, and it warns you.
Level 2: AutoTokenizer and AutoModel
Pipelines hide the steps. To control them, load the two parts yourself. The Auto classes look at a repository's config and pick the right class for you:
AutoTokenizerloads the tokenizer that matches the model. Using any other tokenizer produces nonsense, because the model learned one particular mapping from text pieces to numbers.AutoModelForCausalLMloads a model that predicts the next token: a GPT-style text generator. Siblings includeAutoModelForSequenceClassification(classifiers),AutoModelForTokenClassification,AutoModelForSpeechSeq2Seqand the plainAutoModel, which returns hidden states without a task-specific head.
Tokenisation in action, with the tokenizer of a small open chat model, SmolLM2:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-360M-Instruct")
ids = tokenizer("Hugging Face hosts models.")["input_ids"]
print(ids) # [56, 19712, 8182, 13018, 2859, 30]
print(tokenizer.convert_ids_to_tokens(ids)) # ['H', 'ugging', 'ĠFace', 'Ġhosts', 'Ġmodels', '.']
Six tokens for five words. The Ġ marks a token that begins with a space. "Hugging" is split in two because it is rarer than "Face" in the text the tokenizer was built from. Tokenization explains why.
Chat templates
Chat models are trained on conversations formatted with special marker tokens, and each model family uses its own format. A chat template, stored with the tokenizer, converts a list of messages into exactly that format. Always use tokenizer.apply_chat_template rather than formatting the text by hand: a wrong format silently makes the model worse. Messages use the same role and content structure as LLM APIs.
Choosing and checking a model
Before using a model, read its model card. Check:
- Licence. Many models allow commercial use (Apache 2.0, MIT). Others have custom licences with conditions, or forbid commercial use.
- Gated access. Some models, including Meta's Llama models, are gated: you must accept the licence on the model's web page and log in with an access token (
hf auth loginin the terminal) before downloading. - Size. Use the parameter count to estimate memory, as in GPUs and Why AI Needs Them: roughly 2 bytes per parameter in 16-bit precision. An 8-billion-parameter model needs about 16 GB just for its weights.
- Intended use, training data and limitations. Good model cards describe biases and failure cases. See Bias and Fairness.
The dtype="auto" option loads weights in the precision they were saved in, often bfloat16, which halves memory compared with float32. (Versions of transformers before 4.56 call this argument torch_dtype.) For models larger than one GPU, device_map="auto" (which needs the accelerate package) spreads layers across the available GPUs and CPU memory. To fit bigger models on small GPUs, load them quantised to 8 or 4 bits.
The datasets library
datasets loads datasets from the Hub in one line, caches them on disk in a fast columnar format, and processes them in parallel batches:
from datasets import load_dataset
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
print(ds["train"].num_rows, ds["train"][0]["label"]) # 8530 1
tokenized = ds.map(lambda batch: tokenizer(batch["text"], truncation=True), batched=True)
ds is a dictionary of splits (train, validation, test). .map applies a function to every example and caches the result. Datasets of hundreds of gigabytes can be streamed with streaming=True instead of downloaded in full. Converting to Pandas and Working with Data with ds["train"].to_pandas() is one call.
Beyond inference
The same objects are used for training. A loaded model is an ordinary nn.Module, so you can fine-tune it with your own PyTorch loop, or with the library's Trainer class. The peft library adds LoRA adapters (LoRA and Parameter-Efficient Fine-Tuning), and trl adds instruction tuning and preference tuning. Fine-Tuning an Open Model in Practice walks through a project. model.push_to_hub("my-model") uploads your result as a new repository.
Key idea On Hugging Face, every model is a repository name.
AutoTokenizer.from_pretrained(name)andAutoModelFor...from_pretrained(name)turn that name into a ready-to-use tokenizer and PyTorch model, andpipeline(task, model=name)wraps both for quick use. Read the model card before you rely on it.
In code
A complete script that loads an open chat model, inspects it, and generates an answer. SmolLM2-360M-Instruct is a 362-million-parameter model, small enough to run on a laptop CPU in seconds. Swap in a larger model name, such as an 8-billion-parameter Llama or Qwen model, when you have a GPU with enough memory. Nothing else needs to change.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto").to(device)
print(f"{model.num_parameters() / 1e6:.0f}M parameters, dtype {model.dtype}")
# Chat: format the conversation the way this model was trained to see it
messages = [{"role": "user", "content": "In one sentence, what is a GPU?"}]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True,
return_tensors="pt", return_dict=True).to(device)
with torch.no_grad():
out = model.generate(**inputs, max_new_tokens=60, do_sample=False)
new_tokens = out[0, inputs["input_ids"].shape[1]:] # drop the prompt
print(tokenizer.decode(new_tokens, skip_special_tokens=True))
# 362M parameters, dtype torch.bfloat16
# A GPU (Graphics Processing Unit) is a powerful computing component that processes
# complex graphics and visual data, such as images and videos, in real-time.
add_generation_prompt=True ends the formatted prompt with the marker that means "now the assistant speaks". do_sample=False picks the single most likely token at each step (greedy decoding), so the output is repeatable. Set do_sample=True, temperature=0.7 for more varied text. See Decoding: Temperature, Top-k and Top-p. The answer is fluent but generic, about what you should expect from a model this small. The output of generate contains the prompt tokens followed by the new ones, which is why the script slices off the prompt before decoding.
The same thing with a pipeline is three lines:
chat = pipeline("text-generation", model="HuggingFaceTB/SmolLM2-360M-Instruct")
reply = chat([{"role": "user", "content": "Name three uses of a GPU."}],
max_new_tokens=50, do_sample=False)
print(reply[0]["generated_text"][-1]["content"])
Common pitfalls
- Mismatched tokenizer and model. Always load both from the same repository name.
- Ignoring the chat template. Formatting chat prompts by hand, or using a base model instead of an
-Instructor-Chatversion, gives rambling or odd answers. - Running out of memory. Check the parameter count first. Use
dtype="auto", a smaller model or quantisation. - Filling your disk. Downloaded models are cached under
~/.cache/huggingfaceby default and can take tens of gigabytes. Set theHF_HOMEenvironment variable to move the cache, and runhf cache lsto see what is stored there. - Version drift. The libraries move fast and some arguments get renamed between versions. Pin versions in your project (Setting Up Your Environment) and check the documentation for the version you have installed.
- Licence surprises. "Open weights" does not always mean free for any use. Read the licence before building a product.
Watch out Loading a model can run code.
trust_remote_code=Trueexecutes Python files from the model's repository on your machine. Only use it for repositories you trust. Older checkpoints in pickle format (.bin,.pt) can also run code when loaded. Prefer models that ship safetensors files, a format that holds only numbers and cannot execute anything.
Where it leads
- Fine-Tuning an Open Model in Practice and LoRA and Parameter-Efficient Fine-Tuning adapt Hub models to your own data.
- Sentence Embeddings and Embeddings and Semantic Search use
feature-extractionmodels from the Hub. - Running Models Locally covers tools such as Ollama and llama.cpp, which run quantised Hub models efficiently. Serving LLMs at Scale covers serving models to many users.
- Evaluating LLMs and Benchmarks explains leaderboards and benchmarks. Hugging Face hosts many of them.
- Diffusion Models and Text-to-Image in Practice use the
diffuserslibrary in the same style.
A bit of history
Hugging Face was founded in New York in 2016 by Clément Delangue, Julien Chaumond and Thomas Wolf, originally to make a chatbot app for teenagers, named after the "hugging face" emoji. In late 2018, soon after Google released BERT in TensorFlow, the team published a PyTorch port, pytorch-pretrained-bert. It became popular so quickly that the company changed direction. The library grew to cover GPT-2 and many other architectures and was renamed pytorch-transformers and then transformers in 2019. A paper describing it won a best demo paper award at EMNLP 2020. The datasets library followed in 2020, Spaces for demo apps in 2021, and the safetensors format in 2022. Since then the Hub has become the default place to publish open models.
Try it
- Run the sentiment pipeline on ten sentences of your own, including sarcastic ones ("Great, another bug."). Where does it fail?
- In the generation script, set
do_sample=Trueandtemperature=1.2, and run it three times. How do the answers change? Then trytemperature=0.2.- Browse huggingface.co/models, filter by the task "text-classification", and open a model card. Find its licence, its training data and one stated limitation.
Hint for 1: the model was trained on movie-review sentences, so text from very different domains or with sarcasm is where it struggles.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
Hugging Face Documentation
Documentation for transformers, datasets, diffusers, PEFT, TRL and the rest of the ecosystem.
Transformers documentation
Official guide and API reference for pipelines, Auto classes, generation, chat templates, Trainer and every supported architecture.
Hugging Face Hub documentation
How the Hub works: model and dataset repositories, gated models, access tokens, Spaces and uploading your own work.
Datasets documentation
Loading, processing, streaming and sharing datasets with the datasets library.
Model Cards
What a model card should contain (intended use, training data, limitations, licence) and how to read and write one.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/hugging-face.md