◆ AI All-in-One

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
↗ Plan a path here

Read first

PyTorchThe Transformer

This leads to

Fine-Tuning an Open Model in Practice
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Matrices and Matrix Multiplication
  8. Partial Derivatives and Gradients
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Supervised, Unsupervised and Reinforcement Learning
  12. Tensors and Shapes
  13. Gradient Descent
  14. NumPy and Array Thinking
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Backpropagation
  21. Recurrent Neural Networks
  22. Activation Functions
  23. PyTorch
  24. Vanishing and Exploding Gradients
  25. Normalization Layers: BatchNorm and LayerNorm
  26. LSTMs and GRUs
  27. Residual Connections
  28. Sequence-to-Sequence Models
  29. Attention
  30. Self-Attention and Multi-Head Attention
  31. Positional Encodings
  32. The Transformer
  33. 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:

  1. 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.
  2. A set of open-source Python libraries that download and run those models with a few lines of code. The best known is transformers, alongside datasets, 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.

The Hub huggingface.co Models 1M+ repositories Datasets text, images, audio Spaces demo apps one model repository: config.json architecture model.safetensors weights tokenizer.json tokenizer README.md model card download once Local cache ~/.cache/ huggingface works offline after Python libraries transformers pipeline, AutoTokenizer, AutoModelFor... datasets load_dataset, .map peft / trl fine-tuning, LoRA huggingface_hub download, upload, login your code PyTorch model + tokenizer
Fig. 1 The Hugging Face ecosystem. The Hub stores model and dataset repositories. The Python libraries download what you name into a local cache and turn it into ready-to-use PyTorch objects. Your code only names the repository.

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:

  • AutoTokenizer loads the tokenizer that matches the model. Using any other tokenizer produces nonsense, because the model learned one particular mapping from text pieces to numbers.
  • AutoModelForCausalLM loads a model that predicts the next token: a GPT-style text generator. Siblings include AutoModelForSequenceClassification (classifiers), AutoModelForTokenClassification, AutoModelForSpeechSeq2Seq and the plain AutoModel, which returns hidden states without a task-specific head.
"what is a GPU?" messages tokenizer chat template + ids token ids [1, 9690, 198, …] model Transformer layers scores (logits) one per vocabulary token pick next token e.g. "A" append and repeat (max_new_tokens times) new ids → tokenizer.decode "A GPU (Graphics Processing Unit) is…" the reply as text model.generate() runs this loop for you
Fig. 2 What happens when you generate text. The tokenizer turns text into token ids. The model turns the ids into scores for every possible next token. generate() picks one, appends it and repeats. The tokenizer then turns the new ids back into text.

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 login in 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) and AutoModelFor...from_pretrained(name) turn that name into a ready-to-use tokenizer and PyTorch model, and pipeline(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 -Instruct or -Chat version, 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/huggingface by default and can take tens of gigabytes. Set the HF_HOME environment variable to move the cache, and run hf cache ls to 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=True executes 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

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

  1. Run the sentiment pipeline on ten sentences of your own, including sarcastic ones ("Great, another bug."). Where does it fail?
  2. In the generation script, set do_sample=True and temperature=1.2, and run it three times. How do the answers change? Then try temperature=0.2.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You load a model from one repository and a tokenizer from a different model's repository. What happens?

  2. You format a chat prompt for an Instruct model by hand as plain text, and the answers ramble. What should you use instead?

  3. A model's loading instructions ask for trust_remote_code=True. What does that do?

  4. Your company wants to ship a product built on an open-weight model from the Hub. What must you check first?

  5. You run pipeline("text-classification") without naming a model. Why is this discouraged?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face LLM Course

Hugging Face · Intermediate · Free

Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.

Docs

Hugging Face Documentation

Hugging Face · Intermediate · Free

Documentation for transformers, datasets, diffusers, PEFT, TRL and the rest of the ecosystem.

Docs

Transformers documentation

Hugging Face · Intermediate · Free

Official guide and API reference for pipelines, Auto classes, generation, chat templates, Trainer and every supported architecture.

Docs

Hugging Face Hub documentation

Hugging Face · Beginner · Free

How the Hub works: model and dataset repositories, gated models, access tokens, Spaces and uploading your own work.

Docs

Datasets documentation

Hugging Face · Intermediate · Free

Loading, processing, streaming and sharing datasets with the datasets library.

Docs

Model Cards

Hugging Face · Beginner · Free

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