Run a Pretrained Model from the Hub

Training a language model from nothing takes huge amounts of text and days of computing on many accelerators, and most people never need to do it. Organisations that have done it publish the result, so anyone can download a network that already knows how language works and use it in a few lines of Python. Before you build on such a model, you want to know how it learned, what it is meant for and whether its terms allow your use; after that, running it on your own machine takes a single call.

Starting from what a network already learned

A neural network is its weights. Before training, they are random numbers, and the network's answers mean nothing. Training changes them, batch after batch, until the network does its job well. For a language model, that job needs a lot: the network has to learn which words go together, how sentences are built and what words usually mean in context, and it can only learn this from a very large amount of text.

A pretrained model is a network whose weights have already been through that expensive training and were then published. You download the trained weights and start from them, instead of from random numbers.

One example shows the cost you skip. The model distilbert/distilbert-base-uncased is a small English model with about 67 million weights. It was trained for 90 hours on 8 GPUs with 16 GB of memory each. Its training text was 11,038 unpublished books plus English Wikipedia. Using it starts with a download of a few hundred megabytes.

  • Very large text books, Wikipedia
  • Pretraining done once, costly
  • Published weights a pretrained model
  • Your use run it, or train further
  • Very large text to Pretraining
  • Pretraining to Published weights
  • Published weights to Your use

What you get is general knowledge of a language, not a finished product for your problem. A pretrained model on its own does the task it was trained on, and that task is usually a training exercise rather than something useful by itself. Its real value is as a starting point: from those weights, a short extra training on a small set of your own examples can teach it a specific job, far faster and with far less data than starting from random weights.

True or false?

A pretrained model has learned general knowledge of language, so starting from its weights saves most of the training a useful model would need.

True. The costly part, learning from a very large amount of text, is already done and stored in the published weights.

A pretrained model is already trained for the specific job you have in mind.

False. It learned a general training task. Making it do your job, such as sorting texts into your own categories, needs further training on your examples.

How a model learns from text nobody labelled

Training a network needs a right answer for every example, so the loss can measure how wrong the network is. Labelling millions of sentences by hand is impossible, so pretraining makes the right answers out of the text itself. The best-known way to do it for models that read a whole text at once is masked language modelling: hide some words of a real sentence and train the model to predict them from the words around.

One training example, made from a real sentence
  1. the
  2. cat
  3. sat
  4. on
  5. the
  6. [MASK] answer: mat
  7. and
  8. slept

The hidden word is the label, and the sentence provides it for free. To guess mat, the model has to use the words on both sides: sat on the before the gap says a surface is coming, and and slept after it makes a soft surface more likely. Repeated over billions of words, this forces the network to learn how words relate, how grammar works and which meanings fit which contexts. Because every sentence of any text can become examples like this, no human labelling is needed at all.

In practice a model does not see whole words but tokens: the pieces a text is cut into, roughly words. The recipe used for BERT, and described on the DistilBERT model card, chooses 15% of the tokens in each input for the model to predict. The chosen ones are not all hidden the same way:

What happens to the 15% of tokens chosen for prediction
  • replaced by [MASK] 80%
  • replaced by a random token 10%
  • left unchanged 10%

The model must predict the original token in all three cases. Since a chosen word sometimes stays as it is, or becomes a wrong word, the model cannot rely on seeing [MASK], and it learns to check every word against its context. Some models add other objectives at the same time: DistilBERT, for instance, was also trained to reproduce the outputs of a larger model, BERT, which acted as its teacher. Masked language modelling is the part that turns raw text into training examples.

This also tells you what such a model can and cannot do. It is good at understanding a text it is given, so it suits tasks like sorting sentences into categories. It never learned to write text word after word, so for generating text you need a different kind of model.

True or false?

Masked language modelling needs people to label which word belongs in each gap.

False. The hidden word comes from the original sentence, so the text labels itself. That is why pretraining can use enormous amounts of raw text.

To fill a gap, a masked language model uses the words after the gap as well as the words before it.

True. It reads the whole sentence at once, so both sides of the gap count as evidence.

In this recipe, every token chosen for prediction is replaced by [MASK].

False. Only 80% of them are. 10% become a random token and 10% stay unchanged, and the model must predict the original in every case.

The Hugging Face Hub: where models are published

The Hugging Face Hub (huggingface.co) is a public host for models and datasets. Each model lives in a repository, a folder of files with a version history, much like a code repository. A repository is named by its owner and its name, joined by a slash: in distilbert/distilbert-base-uncased, the owner is distilbert and the model is distilbert-base-uncased. That full id is what you give your code to say which model you want.

A model repository holds the trained weights and the small files needed to use them. Many repositories keep the same weights in several formats for different frameworks, so a repository can be much larger than what you download.

Some files of distilbert/distilbert-base-uncased
FileSizeWhat it holds
model.safetensors268 MBthe trained weights, read by PyTorch
config.json483 bytesthe architecture: layers, sizes, model type
tokenizer.json, vocab.txt466 kB, 232 kBhow text is cut into tokens and numbered
README.md8.58 kBthe model card
LICENSE11.4 kBthe full licence text
pytorch_model.bin, tf_model.h5, flax_model.msgpack, rust_model.otabout 1.3 GBthe same weights in older or other formats

You never download these by hand to use a model. The first time your code asks for a model by its id, the library fetches only the files it needs (here the 268 MB weights file, the configuration and the tokenizer files, not the whole 1.53 GB repository) and stores them in a local cache, by default in ~/.cache/huggingface/hub. Every later run finds them there and loads them from disk, with no download and no need for a network connection.

  • Hugging Face Hub
  • local cache
  • your script
  • first run: download
  • every run: load
  • ~/.cache/huggingface/hub

Inside the cache, each repository gets its own folder named after its type, owner and name, such as models--distilbert--distilbert-base-uncased. A file is downloaded again only when the repository has a newer version of it.

Cached files are never deleted on their own, so models you tried once keep their disk space until you remove them. The hf cache ls command lists what the cache holds, and hf cache rm removes entries. The environment variables HF_HOME or HF_HUB_CACHE move the cache to another place.

True or false?

Loading the same model a second time downloads its weights again.

False. The first run stores the files in the local cache, and later runs load them from there. A file is fetched again only if the repository has a newer version.

A model id such as distilbert/distilbert-base-uncased names the owner of the repository and the model.

True. The part before the slash is the owner, the part after it is the name of the model repository.

Reading the model card before you use a model

Anyone can publish a model on the Hub, so a model's id tells you little about whether it suits your problem. Every repository's page shows its model card: the repository's README.md file, written by the people who published the model. A good card says what the model is, what it was trained on, what it is meant for, its known limits and biases, and how it was evaluated. Reading it first is how you avoid building on a model that does the wrong task, was trained on the wrong kind of text, or may not be used the way you plan.

What to look for on a card, with the answers from the DistilBERT card
QuestionWhat this card says
What is it?A smaller, faster version of BERT, trained with BERT as its teacher
What was it trained on?BookCorpus (11,038 unpublished books) and English Wikipedia, raw text with no human labels
What is it for?Mostly meant to be fine-tuned on tasks that read a whole sentence, such as sequence classification; for text generation, use another kind of model
How does it treat text?Uncased: it lowercases everything, so english and English are the same to it
What are its limits?It can make biased predictions, and that bias carries into every model fine-tuned from it
May I use it?Licence apache-2.0

The card's limits section deserves the same attention as its intended uses. A model learns patterns from its training text, including unfair ones, and further training on your own data does not remove them. The DistilBERT card shows this with gap-filling examples whose predicted jobs change with the gender and skin colour named in the sentence.

The licence

The licence says what you are allowed to do with the weights. On the Hub it is not on a separate legal page: it sits in a short block of metadata at the top of the card, and the Hub shows it as a tag on the model page.

Metadata at the top of a model card (excerpt)
---
license: apache-2.0
datasets:
- bookcorpus
- wikipedia
---

Licences differ, and the identifier tells you which one applies. apache-2.0 and mit are permissive open-source licences. The Apache License 2.0 lets you use, change and redistribute the work, also commercially, at no charge. Its conditions include adding a copy of the licence and keeping the original notices when you redistribute the work. It also gives the work "as is", without any warranty.

Other models come under licences written for them, such as llama3.1 or gemma, which set their own conditions. The identifier other means the terms are in a LICENSE file in the repository that you have to read. When the licence is unknown or missing, you have no clear permission at all. Whether a particular use complies is a legal question; the card tells you which terms to check.

True or false?

A model that can be downloaded freely from the Hub may be used for any purpose.

False. Being public is not a permission. What you may do is set by the licence named in the card, and some licences restrict commercial or other uses.

On the Hub, the licence of a model is written in the metadata of its model card.

True. The license field at the top of README.md holds it, and the Hub shows it as a tag on the model page.

Fine-tuning a model on your own data removes the biases it learned in pretraining.

False. The DistilBERT card states that its bias also affects all fine-tuned versions of the model.

Running a model with a pipeline

A model does not read text. It takes numbers in and gives numbers out. Using it therefore takes three steps: turn the text into numbers with the model's tokenizer, run the model on them, and turn its output numbers back into an answer a person can read. The Transformers library wraps all three in a pipeline: one object, created for a named task, that you call with text and that returns the answer.

  • Your text
  • Tokenizer text to numbers
  • Model numbers to scores
  • Post-processing scores to an answer
  • Answer
  • Your text to Tokenizer
  • Tokenizer to Model
  • Model to Post-processing
  • Post-processing to Answer

A model trained with masked language modelling can be run on its own training task, which the library calls fill-mask: give it a sentence with one [MASK] token and it returns the most likely words for the gap. This is the simplest way to see what a pretrained model learned.

Fill a gap with a pretrained model
from transformers import pipeline

unmasker = pipeline(
    "fill-mask",
    model="distilbert/distilbert-base-uncased",
    device="cpu",
)

predictions = unmasker("I left my umbrella on the [MASK].")
for p in predictions:
    print(p["token_str"], round(p["score"], 3))

Creating the pipeline loads the tokenizer and the model from the Hub, or from the cache after the first run. Calling it with a sentence runs the three steps and returns a list of five predictions, the most likely first (the top_k argument changes how many). Each prediction is a dictionary:

  • token_str: the predicted word for the gap;
  • score: the probability the model gives that word in that position, out of every token in its vocabulary;
  • token: the number of that token in the vocabulary;
  • sequence: the whole sentence with the gap filled in.

Because this model is uncased, the words and the sentence come back in lowercase. The pipeline expects exactly one [MASK] in the text, and the mask token must be the one this model was trained with: other models use a different mask token.

Two arguments in the example are worth naming every time.

model chooses the model. Without it, the pipeline loads a default model for the task. For fill-mask that default is distilbert/distilroberta-base, a different model with a different mask token, and the default may change between library versions.

device chooses where the model runs. Left unset, the pipeline uses the first accelerator it finds, such as a GPU, and falls back to the CPU only when there is none. Passing device="cpu" makes every machine run the model the same way. A model of this size runs comfortably on a CPU; a GPU only makes it faster.

The same pipeline() call covers many other tasks, such as text-classification, each with its own preprocessing and postprocessing. The model you pass must have been trained for the task you name, which is one more thing the model card tells you.

True or false?

pipeline("fill-mask") without a model argument loads distilbert/distilbert-base-uncased.

False. It loads the task default, distilbert/distilroberta-base, which uses a different mask token. Naming the model keeps the result under your control.

The score of a fill-mask prediction is the probability of that word in the gap, not a rating of the whole sentence.

True. It is the probability the model gives that token at the masked position, compared with every other token of its vocabulary.

A pipeline left without a device argument always runs on the CPU.

False. It takes the first available accelerator, such as a GPU, and uses the CPU only when there is none. Pass device="cpu" to force the CPU.