Mindket

Transformers pipeline: run open models in Python, on CPU or GPU

A black banner titled "Hugging Face" over the line "Find, run and share open models".

A Transformers pipeline loads a model from the Hub and runs it in one call: you name a task, optionally a model, and pass your input. This lesson installs Transformers, classifies text, generates text with Gemma 2 and chats with SmolLM2. Then it picks the device and precision that let a model fit your machine.

In this lesson

  • Write the model id into every pipeline you keep, instead of trusting the task default.
  • Work out what a model weighs before you fetch it: parameters times bytes per number.
  • Hand a chat model a list of messages and let the pipeline wrap them in that model's own format.
  • Switch batching on only on a GPU with inputs of steady length, and keep it only if it measures faster.
All courses
On this page
  1. Before you start
  2. Install Transformers and run your first pipeline
  3. Chat with an instruction model
  4. Choose the device, precision and batch size
  5. Lysandre's chat CLI tip and Andrej Karpathy's warning on special tokens
  6. Common mistakes
  7. Try it yourself
  8. Next
  9. Check yourself
  10. Frequently asked questions
  11. Sources

Before you start

You need the setup from lesson 1: a Hugging Face account and a token saved with hf auth login. For the Gemma 2 example, you also need your access request approved. Transformers is tested on Python 3.11 or later with PyTorch 2.6 or later. PyTorch is the math library that does a model's number crunching, and Transformers is the Hugging Face library that loads Hub models on top of it.

A pipeline wraps the three jobs every model run needs. It turns your input into tokens, runs the model, then turns the output back into labels or text. That run is called inference: using a trained model on new input, as opposed to training it. Each task, such as text-classification or text-generation, gets its own pipeline with the right steps built in. For finer control, Transformers also has model classes such as AutoModelForCausalLM, which the chat templates page uses. The pipeline is the shorter road, and this lesson stays on it.

The same call covers audio and images. The pipeline tutorial transcribes a speech clip with openai/whisper-large-v3 under the automatic-speech-recognition task, and labels a photo with google/vit-base-patch16-224 under image-classification. This lesson sticks to text.

A GPU is optional. The classifier and GPT-2 in this lesson are small enough for a laptop CPU, and the device table further down shows what changes once a GPU is present.

Transformers reached version 5 in January 2026. Run pip show transformers before you copy an example from an older tutorial: later releases raised the oldest supported Python and changed what a retired pipeline task does.

Transformers v5 releases that touch this lesson
  1. Version 5 release candidate

    The first major version in five years opened for testing.

    Source: Transformers release v5.0.0rc0 (read November 5, 2026)

  2. Transformers v5.0.0

    Tokenizers stopped coming as separate slow and fast versions.

    Source: Transformers release v5.0.0 (read November 5, 2026)

  3. Version 5.19.0

    A deprecated pipeline task now redirects to its replacement, and a removed one raises an error.

    Source: Transformers release v5.19.0 (read November 5, 2026)

  4. Version 5.21

    Python 3.11 became the oldest supported version.

    Source: Transformers release v5.21 (read November 5, 2026)

  5. Version 5.22.0

    Added support for the Mistral Large 4 models.

    Source: Transformers release v5.22.0 (read November 5, 2026)

Install Transformers and run your first pipeline

The installation page uses uv, a fast Python package manager, and says to drop uv from each command if you prefer pip. Its install steps end with a check command, the final line below. It downloads the default sentiment model and labels one sentence.

The first call to any model downloads its files into the cache from lesson 1, under ~/.cache/huggingface/hub unless you moved it. Later calls load from that cache, so only the first run of each model waits on the network.

Every pipeline returns plain Python data. A classifier gives a list of dictionaries, each with a label and a score between 0 and 1. A score near 1 means the model is sure of its label. A text generator gives dictionaries with a generated_text key. Pass a list of inputs and you get a list back, one result per input.

uv venv .env
source .env/bin/activate
uv pip install "transformers[torch]"
python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))"
  1. Create a virtual environment with uv venv .env and activate it with source .env/bin/activate. On Windows, run the activate script inside .env\Scripts instead. Every later command assumes the environment is active.
  2. Install with uv pip install "transformers[torch]", which brings PyTorch along. On a machine without an NVIDIA GPU, the docs give a CPU-only route: uv pip install torch --index-url https://download.pytorch.org/whl/cpu, then uv pip install transformers.
  3. Run the check command. In the docs' example it prints one result: a POSITIVE label with a score just under 1.
  4. Name the model instead of taking the default: pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english"). Call it with one string, or with a list of strings when you have several.
  5. Switch to generation with pipeline(task="text-generation", model="google/gemma-2-2b") and call it with the start of a sentence. Gemma 2 is gated, so this step needs your approved access and saved token.
  6. Read the result. In the docs' example, the reply repeats the whole prompt about baking a cake, then adds "1. the right ingredients 2. the". The prompt is included by default. Add return_full_text=False to get only the new words.

Chat with an instruction model

An instruction model, often marked Instruct in its name, is one trained further to follow requests and hold a conversation. Chat models take a list of messages, each a dictionary with a role and content. Start with one user message. A system message is optional and tells the model how to behave.

The code is the chat page's own example. It uses SmolLM2-1.7B-Instruct, an Apache 2.0 model with no access request. dtype="auto" loads the weights in the precision the model's config names, and device_map="auto" places them on the fastest device found. That second setting needs the Accelerate library: pip install -U accelerate.

The reply is not a plain string. response[0]["generated_text"] holds the whole chat, your messages plus the new one, so [-1]["content"] reads the answer. max_new_tokens=512 caps how many tokens the model adds to it. To keep talking, take that list, append the next user message and call the pipeline again. A chat can grow until it fills the model's context window, the most tokens it reads at once, or until memory runs out.

Behind each call, the pipeline applies a chat template: the model's own way of marking who said what, using control tokens the model learned in training. Two models from the same Mistral-7B base mark turns differently, as the table shows. With the wrong tokens, these models perform drastically worse.

The pipeline also appends the start of an assistant turn for you, a setting called add_generation_prompt. Leave it out and a model may simply continue your message. When your last message has the assistant role, the pipeline treats it as the opening of the reply and carries on from there. This is a prefill, and it helps when you know how the answer should begin.

With no code at all, transformers chat Qwen/Qwen2.5-0.5B-Instruct opens a chat in the terminal. It uses transformers serve under the hood, so the chat page asks you to start transformers serve first.

chat = [
    {"role": "system", "content": "You are a helpful science assistant."},
    {"role": "user", "content": "Hey, can you explain gravity to me?"}
]

import torch
from transformers import pipeline

pipeline = pipeline(task="text-generation", model="HuggingFaceTB/SmolLM2-1.7B-Instruct", dtype="auto", device_map="auto")
response = pipeline(chat, max_new_tokens=512)
print(response[0]["generated_text"][-1]["content"])
Control tokens from the chat templates page, read on 5 November 2026.
ModelHow a user turn is markedHow the reply is marked
Mistral-7B-Instruct[INST] before the message and [/INST] after itPlain text right after [/INST]
Zephyr-7B<|user|> on the line above the message<|assistant|> on the line above the reply
The docs' add_generation_prompt example<|im_start|>user before the message, <|im_end|> after it<|im_start|>assistant, which add_generation_prompt appends

Choose the device, precision and batch size

Leave device unset and the pipeline takes the first accelerator it finds: an NVIDIA GPU through CUDA, an Apple Silicon GPU through MPS, or an Intel GPU through XPU. Each is the vendor's route for running math on its GPU. With none of them present, the pipeline falls back to the CPU. Set the device yourself when a script must behave the same on every machine.

Memory decides whether a model runs at all. Every parameter is a number, and the dtype, the number format, sets its size: 4 bytes in float32, 2 in float16 or bfloat16. An 8B model, one with 8 billion parameters, needs about 32GB in float32, by the chat page's count. Half precision halves that. On hardware that supports it, bfloat16 keeps more range than float16. For most models, the pipeline tutorial says, the quality lost to half precision is negligible, and larger models lose least.

By default, Transformers loads the dtype written in the model's config.json. Pass dtype="auto" or a type such as torch.bfloat16 to choose. To go lower, the pipeline accepts a model quantized to 8 or 4 bits with the bitsandbytes library, passed through model_kwargs. The tutorial's own example loads google/gemma-7b that way, in bfloat16 with 8-bit weights and device_map="auto", in a single call. Before you fetch anything big, the local LLM hardware lesson sets out memory needs by model size.

Speed follows memory too. A model reads every active parameter from memory for each token it writes. That is why the chat page names quantizing and faster memory as the levers, and says extra compute power does not meaningfully help.

A mixture-of-experts model bends that rule. It splits its layers into many expert blocks and sends each token through only a few, so Mixtral, Qwen2MoE and GPT-OSS read a small share of their parameters per token. They need less memory bandwidth and can beat a regular model of the same size on speed, though every parameter still has to fit in memory.

The chat page names one more lever, speculative decoding: a smaller model drafts tokens and the large one checks them, so it can accept several per step. It helps little with mixture-of-experts models, because each drafted token wakes more of their parameters.

Batching sends several inputs through the model at once with batch_size. It is off by default because it is not always faster. Skip it on a CPU and when each answer has to come back quickly, and plan for out-of-memory errors when you use it. Measure on your own model, data and hardware before you keep it.

For a large dataset, give the pipeline an iterator instead of one big list: a generator function, or a dataset column wrapped in KeyDataset. The pipeline then works through the data without first holding all of it in memory.

Device settings from the pipeline tutorial, read on 5 November 2026.
SettingWhere the model runsUse it when
device left unsetThe first accelerator found (CUDA, MPS, XPU), else the CPUYou want sensible defaults on any machine
device="cpu"The CPU, even with a GPU presentEvery run should use the CPU, GPU or not
device=0The first NVIDIA GPUOne GPU holds the whole model
device="mps"The GPU of an Apple Silicon MacYou work on an M-series Mac
device_map="auto"Accelerate fills the fastest device first, then the CPU, then the diskThe model is bigger than one GPU, with Accelerate installed

Lysandre's chat CLI tip and Andrej Karpathy's warning on special tokens

Lysandre, Chief Open-Source Officer at Hugging Face, posted on X in May 2025 that version 4.52 made transformers chat plus a model id the whole command, with generation settings typed straight after it. Today's chat page writes them as key=value pairs, as in transformers chat Qwen/Qwen2.5-0.5B-Instruct do_sample=False max_new_tokens=10, and transformers chat -h lists the rest. Get a prompt right there before you write pipeline code around it.

Andrej Karpathy, an AI researcher and educator who was a founding member of OpenAI, warned on X in August 2024 that tokenizers parse special tokens out of plain text. A user who types <|endoftext|> into your app can slip a control token into the model's input, much like SQL injection. His fix was add_special_tokens=False plus split_special_tokens=True, with the special tokens added by your own code. For chat models, he thought a chat template would also do.

The warning still holds. In Transformers 5.22.1, the tokenizer reference still defaults split_special_tokens to False. If your app tokenizes text that users type, pass split_special_tokens=True and print the tokens it produces, as he advised.

User input strings are untrusted data

Andrej Karpathy, AI researcher and educator, a founding member of OpenAI · X (read November 5, 2026)
Lysandre (@LysandreJik) on X, 21 May 2025: From v4.52, "transformers chat [model id]" is all you need. We upgrade the chat CLI so that it is simpler and more configurable. Customize it from the command line: pass any generation argument (temperature, sampling, num beams, repetition penalty, early_stopping) straight away.
Lysandre on X, 21 May 2025
Andrej Karpathy (@karpathy) on X, 13 August 2024: SQL injection-like attack on LLMs with special tokens. Parsing special tokens in the input string leads to footguns at best and LLM security vulnerabilities at worst. User input strings are untrusted data.
Andrej Karpathy on X, 13 August 2024
Hugging Face on YouTube: a video on the pipeline function this lesson uses.

Screenshots of X's own embeds of the posts, taken on 5 November 2026, with the time in UTC. X cuts Andrej Karpathy's post short with Show more. Select one to open the post on X.

Common mistakes

  • Leaving out the model id. Each task falls back to a default model, which may not suit your text, your memory or your license check.
  • Calling Gemma 2 before the authors approve your request, or with no token saved. The download stops until both are in place.
  • Asking a base model to chat. google/gemma-2-2b continues text, while its chat-trained sibling is google/gemma-2-2b-it, and the message list only gets sensible replies from the second.
  • Typing control tokens into a prompt by hand. A single wrong token sends the model off its training format, so pass the message list instead.
  • Turning on batch_size on a CPU, where the pipeline docs advise against batching at all.
  • Setting trust_remote_code=True with no revision. That flag runs Python code from the model repo, and pinning a commit hash with revision= keeps that code from changing under you.
  • Using device_map="auto" before Accelerate is installed. One pip install -U accelerate in the same environment fixes it.

Try it yourself

Start python inside your virtual environment and type these lines from the pipeline tutorial. GPT-2 is public and small, so you need no token or GPU. The Python prompt prints the four continuations the call returns.

from transformers import pipeline

pipeline = pipeline(task="text-generation", model="openai-community/gpt2")
pipeline("the secret to baking a good cake is", num_return_sequences=4, return_full_text=False)
  • Run the call twice. Do the four continuations change between runs?
  • Drop return_full_text=False and compare what comes back.
  • Load the DistilBERT classifier from the steps and pass it a list of three short reviews. Which one scores lowest?
  • Run the SmolLM2 chat once with device="cpu" and once with the device unset, and time one reply each way.
  • Add an assistant message that starts with "Answer:" to the end of the chat. How does the reply pick up from it?
  • Continue the SmolLM2 chat the way the chat page does: append a user message to the returned list and call the pipeline again. Does the second reply build on the first?
  • Run hf cache ls from lesson 1. Which models did this lesson add, and how much disk does each one take?

Next

You can now run any model your machine holds. Many it can't: a 70B model needs about 140GB at 2 bytes per number, far beyond a laptop. Lesson 3 sends those to hosted providers by the same Hub ids, billed to your Hugging Face account. The message lists from this lesson carry over unchanged, and the token you saved in lesson 1 is the only key the calls need.

Check yourself

  1. Where does a pipeline run when you leave device unset?

    Show answer

    B. On the first accelerator it finds, else the CPU It looks for CUDA, MPS or XPU first and falls back to the CPU only when none is there.

  2. About how much memory do the weights of an 8B model need in float32?

    Show answer

    D. 32GB Eight billion parameters at 4 bytes each come to about 32GB, and half precision halves that.

  3. What do you pass to a text generation pipeline to chat with an instruction model?

    Show answer

    A. A list of messages, each with a role and content The pipeline applies the model's chat template to the message list, so you never type control tokens.

  4. When is batch_size worth turning on?

    Show answer

    C. On a GPU with inputs of steady length, after you measure Batching can speed up GPU work but is not guaranteed. Skip it on a CPU, as the docs advise, and when answers must come back quickly.

Frequently asked questions

Does the Transformers pipeline need a GPU?

No. Without an accelerator it runs on the CPU, and the installation page has a CPU-only install. Small models suit a CPU, and larger ones slow down as memory reads pile up. Past a few billion parameters, a GPU or a hosted provider starts to pay off.

How do I find the task name a model needs?

Read the task tag on the model's page. That tag is the pipeline_tag in its model card, and it matches the name pipeline() takes, such as text-generation. Each pipeline's API reference lists its task identifier as well.

Why does my chat model ignore instructions or ramble?

Usually because its chat template was skipped or applied twice. Pass the message list to the pipeline so it formats the chat once. If you format text yourself with apply_chat_template(tokenize=False), tokenize it later with add_special_tokens=False.

Can I run a pipeline offline?

Yes. Set HF_HUB_OFFLINE=1 and the libraries stop calling the Hub and read only what is stored on disk. When you load a model class directly, pass local_files_only=True to from_pretrained instead. Run each model once while online, so its files are there before you disconnect.

Sources

  1. Transformers: Pipeline (read November 5, 2026)https://huggingface.co/docs/transformers/pipeline_tutorial
  2. Transformers: Installation (read November 5, 2026)https://huggingface.co/docs/transformers/installation
  3. Transformers: Chat basics (read November 5, 2026)https://huggingface.co/docs/transformers/conversations
  4. Transformers: Chat templates (read November 5, 2026)https://huggingface.co/docs/transformers/chat_templating
  5. Transformers: Loading models (read November 5, 2026)https://huggingface.co/docs/transformers/models
  6. Hugging Face: google/gemma-2-2b model page (read November 5, 2026)https://huggingface.co/google/gemma-2-2b
  7. Hugging Face: HuggingFaceTB/SmolLM2-1.7B-Instruct model page (read November 5, 2026)https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct
  8. Hugging Face: distilbert-base-uncased-finetuned-sst-2-english model page (read November 5, 2026)https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english
  9. Transformers: Tokenizer reference (read November 5, 2026)https://huggingface.co/docs/transformers/main_classes/tokenizer
  10. Transformers release v5.0.0rc0 (read November 5, 2026)https://github.com/huggingface/transformers/releases/tag/v5.0.0rc0
  11. Transformers release v5.0.0 (read November 5, 2026)https://github.com/huggingface/transformers/releases/tag/v5.0.0
  12. Transformers release v5.19.0 (read November 5, 2026)https://github.com/huggingface/transformers/releases/tag/v5.19.0
  13. Transformers release v5.21 (read November 5, 2026)https://github.com/huggingface/transformers/releases/tag/v5.21
  14. Transformers release v5.22.0 (read November 5, 2026)https://github.com/huggingface/transformers/releases/tag/v5.22.0
  15. Lysandre on X: transformers chat from v4.52 (read November 5, 2026)https://x.com/LysandreJik/status/1925124636498645407
  16. Andrej Karpathy on X: special tokens and untrusted user input (read November 5, 2026)https://x.com/karpathy/status/1823418177197646104
  17. Hugging Face on YouTube: The pipeline function (read November 5, 2026)https://www.youtube.com/watch?v=tiZFewofSLM

Share this lesson

Find ready-made kits for your AI tools

Kits on Mindket bundle AI agent skills, rules and prompts as plain text files you can read before you use them.

Browse kits

This lesson as Markdown · Hugging Face course: find, run and share open models · All courses