Transformers Cheat Sheet: Hugging Face transformers, datasets, Hub, pipelines, PEFT and TRL Snippets (v5)
A practical, up-to-date cheat sheet for the Hugging Face ecosystem: the transformers library (pipelines, tokenizers, chat templates, generate, Trainer, quantization), the Hugging Face Hub and the hf command line, datasets, PEFT and LoRA/QLoRA, TRL (SFT, DPO, GRPO), Accelerate, sentence-transformers, diffusers, safetensors and Gradio. Every snippet uses current APIs (transformers v5, huggingface_hub 2.x, datasets 5.x) and verified model and dataset names. It is for ML engineers, data scientists and students who want the right code fast, and for anyone migrating older transformers v4 code.
Last reviewed: December 2026 (transformers 5.24, huggingface_hub 2.5, datasets 5.2, peft 0.22, trl 1.19, accelerate 1.16, sentence-transformers 6.3, diffusers 0.43, gradio 6.32). Independent cheat sheet, not affiliated with Hugging Face.
Table of Contents
- The ecosystem in one table
- Install
- hf command line
- Hub from Python
- Environment variables and cache
- Pipelines
- Tokenizers
- Chat templates and text generation
- Loading models: dtype, devices, attention
- Generation settings
- Streaming output
- Quantization
- Embeddings and hidden states
- datasets
- Fine-tuning with Trainer
- PEFT: LoRA and QLoRA
- TRL: SFT, DPO, GRPO
- Accelerate
- sentence-transformers
- diffusers
- safetensors
- Gradio and Spaces
- Serving: transformers serve and Inference Providers
- Migrating from transformers v4 to v5
- Common errors and fixes
- FAQ
- Where to go next
- Contributing
- More free resources
The ecosystem in one table
| Library | What it does | Reach for it when |
|---|---|---|
transformers |
Model architectures, pretrained weights, tokenizers, pipelines, generate, Trainer |
Running or fine-tuning almost any open model in PyTorch |
huggingface_hub (+ hf CLI) |
Download, upload, repos, cache, auth, inference clients | Moving files to and from the Hub, calling hosted models |
datasets |
Loading, processing and sharing datasets (Arrow-backed, streaming) | Data pipelines for training and evaluation |
tokenizers |
Fast Rust tokenizers (used inside transformers) | Training a custom tokenizer |
peft |
Parameter-efficient fine-tuning (LoRA, QLoRA and more) | Fine-tuning large models on small GPUs |
trl |
Post-training: SFT, DPO, GRPO, reward modeling | Instruction tuning and preference/RL training of LLMs |
accelerate |
Same training code on CPU, one GPU, many GPUs, mixed precision | Scaling a custom PyTorch loop |
sentence-transformers |
Embeddings, rerankers (cross-encoders), sparse encoders | Semantic search, RAG, clustering |
diffusers |
Diffusion pipelines for images, video, audio | Image generation and editing |
safetensors |
Safe, fast tensor file format | Saving and loading weights without pickle |
gradio |
Web UIs for ML demos | Sharing a demo, Spaces |
evaluate |
Metric implementations | Still works; for LLM evaluation Hugging Face points to LightEval |
Install
pip install -U transformers torch # transformers v5 requires Python 3.11+ and PyTorch
pip install -U huggingface_hub datasets accelerate peft trl
pip install -U sentence-transformers diffusers safetensors gradio
pip install -U bitsandbytes # 4-bit/8-bit quantization (CUDA, plus other backends)
pip install "transformers[serving]" # for `transformers serve` / `transformers chat`
Check versions:
python -c "import transformers, huggingface_hub, datasets; print(transformers.__version__, huggingface_hub.__version__, datasets.__version__)"
hf env
hf command line
The hf CLI (installed with huggingface_hub) replaced the old huggingface-cli command.
# auth
hf auth login # paste a token from https://huggingface.co/settings/tokens
hf auth login --token $HF_TOKEN # non-interactive
hf auth whoami
hf auth logout
# download (prints the local path)
hf download gpt2 config.json
hf download Qwen/Qwen3-0.6B # whole repo into the cache
hf download Qwen/Qwen3-0.6B --local-dir ./qwen3-0.6b # into a folder
hf download stabilityai/stable-diffusion-xl-base-1.0 --include "*.safetensors" --exclude "*.fp16.*"
hf download stanfordnlp/imdb --repo-type dataset
hf download openai-community/gpt2 --dry-run # show what would be downloaded
# upload
hf upload my-cool-model . . # current folder to repo root (creates repo)
hf upload my-cool-model ./model.safetensors # single file
hf upload my-user/my-dataset ./data /train --repo-type dataset
# repos
hf repos create my-cool-model --private
hf repos create my-space --repo-type space --sdk gradio
hf repos ls --namespace my-org
hf repos delete my-user/old-model
# cache
hf cache ls # what is cached and how big
hf cache rm model/gpt2 # delete one repo from the cache
hf cache prune # remove unreferenced revisions
hf cache verify gpt2 # check files against the Hub
hf env # versions and paths, useful for bug reports
Every command has --help. Full reference: hf CLI guide.
Hub from Python
from huggingface_hub import HfApi, create_repo, hf_hub_download, login, snapshot_download
login() # or set HF_TOKEN
path = hf_hub_download(repo_id="Qwen/Qwen3-0.6B", filename="config.json")
folder = snapshot_download(repo_id="Qwen/Qwen3-0.6B", allow_patterns=["*.json", "*.safetensors"])
ds_file = hf_hub_download(repo_id="stanfordnlp/imdb", filename="README.md", repo_type="dataset")
create_repo("my-user/my-model", private=True, exist_ok=True)
api = HfApi()
api.upload_folder(folder_path="./outputs", repo_id="my-user/my-model", ignore_patterns=["*.pt"])
api.upload_file(path_or_fileobj="README.md", path_in_repo="README.md", repo_id="my-user/my-model")
info = api.model_info("Qwen/Qwen3-0.6B")
print(info.downloads, info.pipeline_tag)
for m in api.list_models(search="whisper", sort="downloads", limit=5):
print(m.id)
Large uploads: upload_folder is resumable and splits big folders into several commits automatically. Transfers use the Xet storage backend through the hf-xet package, installed with huggingface_hub.
Environment variables and cache
| Variable | Default | Purpose |
|---|---|---|
HF_HOME |
~/.cache/huggingface |
Root for token, caches and config |
HF_HUB_CACHE |
$HF_HOME/hub |
Model and dataset file cache |
HF_TOKEN |
(unset) | Access token; overrides the saved login |
HF_HUB_OFFLINE |
0 |
1 = never call the network, use the cache only |
HF_HUB_DISABLE_PROGRESS_BARS |
(unset) | Quieter logs in CI |
HF_XET_HIGH_PERFORMANCE |
(unset) | 1 for maximum transfer throughput |
HF_ENDPOINT |
https://huggingface.co |
Point to a mirror or private Hub |
Removed or renamed: TRANSFORMERS_CACHE and similar transformers-specific cache variables were removed in v5 (use HF_HOME); HUGGING_FACE_HUB_TOKEN is replaced by HF_TOKEN; HF_HUB_ENABLE_HF_TRANSFER no longer does anything now that transfers go through Xet.
Run fully offline after a first download:
HF_HUB_OFFLINE=1 python app.py
Pipelines
The fastest way to use a model. Pass model= explicitly in real code so results do not change when defaults change.
from transformers import pipeline
clf = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
print(clf(["I love this!", "This is terrible."]))
# [{'label': 'POSITIVE', 'score': 0.99...}, {'label': 'NEGATIVE', 'score': 0.99...}]
ner = pipeline("token-classification", model="dslim/bert-base-NER", aggregation_strategy="simple")
print(ner("Ada Lovelace worked with Charles Babbage in London."))
zero = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
print(zero("The new GPU doubles training speed", candidate_labels=["hardware", "cooking", "sports"]))
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small")
print(asr("meeting.wav")["text"])
img = pipeline("image-classification", model="google/vit-base-patch16-224")
print(img("cat.jpg")[0])
det = pipeline("object-detection", model="facebook/detr-resnet-50")
print(det("street.jpg"))
fill = pipeline("fill-mask", model="google-bert/bert-base-uncased")
print(fill("Paris is the [MASK] of France.")[0]["token_str"])
Task names available in v5 (aliases in parentheses):
| Text | Vision | Audio | Multimodal |
|---|---|---|---|
text-generation |
image-classification |
automatic-speech-recognition |
image-text-to-text |
text-classification (sentiment-analysis) |
object-detection |
audio-classification |
document-question-answering |
token-classification (ner) |
image-segmentation |
text-to-audio (text-to-speech) |
zero-shot-image-classification |
zero-shot-classification |
depth-estimation |
zero-shot-audio-classification |
zero-shot-object-detection |
fill-mask |
image-feature-extraction |
table-question-answering |
|
feature-extraction |
mask-generation, keypoint-matching, video-classification |
Removed in v5: summarization, translation and text2text-generation pipelines (and question-answering, image-to-text, visual-question-answering). Use a chat model with text-generation (or image-text-to-text for images) and ask for a summary, translation or answer in the prompt.
Pipeline options worth knowing: device_map="auto" (or device=0), dtype="auto", batch_size=8, and for long audio chunk_length_s=30.
Tokenizers
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
enc = tok("Hello world!", "A second sentence.") # pairs are supported
print(enc["input_ids"], enc["attention_mask"])
print(tok.convert_ids_to_tokens(enc["input_ids"]))
batch = tok(
["short", "a much longer sentence that needs padding"],
padding=True, # pad to longest in batch ("max_length" pads to max_length)
truncation=True,
max_length=32,
return_tensors="pt",
)
print(batch["input_ids"].shape)
print(tok.decode(batch["input_ids"][1], skip_special_tokens=True))
print(len(tok), tok.pad_token, tok.model_max_length)
# count tokens
print(len(tok("How many tokens is this?")["input_ids"]))
# offsets for highlighting spans
enc = tok("New York City", return_offsets_mapping=True)
print(enc["offset_mapping"])
Notes for v5: tokenizers are backed by the fast (Rust) implementation; encode_plus is deprecated in favor of calling the tokenizer directly, and decode also handles batches. Decoder-only LLM tokenizers often have no pad token; set tok.pad_token = tok.eos_token for batched generation and use left padding (tok.padding_side = "left").
Chat templates and text generation
With a pipeline (handles the chat template for you):
from transformers import pipeline
chat = [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain gradient descent in two sentences."},
]
pipe = pipeline("text-generation", model="HuggingFaceTB/SmolLM2-1.7B-Instruct", dtype="auto", device_map="auto")
out = pipe(chat, max_new_tokens=200)
print(out[0]["generated_text"][-1]["content"]) # the assistant's reply
With a model and tokenizer (full control):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen3-0.6B"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto", device_map="auto")
messages = [{"role": "user", "content": "Write a haiku about version control."}]
inputs = tok.apply_chat_template(
messages,
add_generation_prompt=True, # append the assistant turn header
return_tensors="pt", # in v5 this returns a dict (BatchEncoding) with input_ids and attention_mask
).to(model.device)
output = model.generate(**inputs, max_new_tokens=128)
new_tokens = output[0][inputs["input_ids"].shape[-1]:]
print(tok.decode(new_tokens, skip_special_tokens=True))
See what the template produces:
print(tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True))
Template tips:
- Always use the model’s own template; never hand-write
<|im_start|>style strings. - Pass extra template variables as keyword arguments, for example
enable_thinking=Falsefor models whose templates support switching reasoning on or off. - Tools:
apply_chat_template(messages, tools=[my_function], ...)renders function schemas for models whose templates support tool calling. - Do not combine
add_generation_prompt=Truewithcontinue_final_message=True.
Loading models: dtype, devices, attention
import torch
from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen3-0.6B",
dtype="auto", # v5 default: use the dtype stored with the checkpoint
device_map="auto", # spread across GPUs/CPU automatically (needs accelerate)
attn_implementation="sdpa", # or "flash_attention_2" (needs flash-attn), "eager"
)
model.eval()
clf = AutoModelForSequenceClassification.from_pretrained(
"distilbert/distilbert-base-uncased",
num_labels=3,
id2label={0: "neg", 1: "neu", 2: "pos"},
label2id={"neg": 0, "neu": 1, "pos": 2},
)
| Argument | Values | Notes |
|---|---|---|
dtype |
"auto", torch.bfloat16, torch.float16, torch.float32 |
Renamed from torch_dtype in v5 (old name still accepted with a warning) |
device_map |
"auto", "cuda", "cpu", "mps", or a dict |
"auto" offloads to CPU/disk if GPUs are full |
revision |
branch, tag or commit hash | Pin for reproducibility |
token |
your token | Gated or private models (replaces use_auth_token) |
trust_remote_code |
False by default |
Only enable for repos you trust; it runs code from the repo |
quantization_config |
BitsAndBytesConfig(...) etc. |
See Quantization |
Common Auto classes: AutoModel (base, hidden states), AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelForMaskedLM, AutoModelForImageClassification, AutoModelForSpeechSeq2Seq, AutoModelForImageTextToText, plus AutoProcessor / AutoImageProcessor for non-text inputs.
Save and reload:
model.save_pretrained("./my-model") # always safetensors in v5
tok.save_pretrained("./my-model")
model.push_to_hub("my-user/my-model")
tok.push_to_hub("my-user/my-model")
Generation settings
out = model.generate(
**inputs,
max_new_tokens=256,
do_sample=True, # False = greedy (deterministic)
temperature=0.7,
top_p=0.9,
top_k=50,
repetition_penalty=1.1,
num_return_sequences=1,
)
| Goal | Settings |
|---|---|
| Deterministic, factual | do_sample=False |
| Creative | do_sample=True, temperature=0.8 to 1.0, top_p=0.9 to 0.95 |
| Stop at a string | stop_strings=["\n\n"], tokenizer=tok |
| Beam search | num_beams=4, do_sample=False |
| Change defaults for every call | edit model.generation_config (for example model.generation_config.max_new_tokens = 256) |
In v5 generation defaults come from model.generation_config (from the checkpoint’s generation_config.json), not from the model config. Many instruct models ship recommended sampling settings there.
Streaming output
Print tokens as they are generated:
from transformers import TextStreamer
streamer = TextStreamer(tok, skip_prompt=True, skip_special_tokens=True)
model.generate(**inputs, max_new_tokens=200, streamer=streamer)
Iterate over text in your own code (for web servers):
from threading import Thread
from transformers import TextIteratorStreamer
streamer = TextIteratorStreamer(tok, skip_prompt=True, skip_special_tokens=True)
thread = Thread(target=model.generate, kwargs=dict(**inputs, max_new_tokens=200, streamer=streamer))
thread.start()
for piece in streamer:
print(piece, end="", flush=True)
thread.join()
Quantization
4-bit (NF4) loading with bitsandbytes, the usual base for QLoRA:
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
bnb = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", quantization_config=bnb, device_map="auto")
print(f"{model.get_memory_footprint() / 1e9:.2f} GB")
8-bit: BitsAndBytesConfig(load_in_8bit=True). In v5 the shortcut arguments load_in_4bit=True / load_in_8bit=True on from_pretrained were removed; always pass a quantization_config.
Pre-quantized checkpoints (GPTQ, AWQ, FP8, compressed-tensors and others) load with a plain from_pretrained when the right backend package is installed; the quantization settings are read from the checkpoint. See the quantization overview for which methods support which hardware. For local CPU/Mac inference, converting to GGUF for llama.cpp or Ollama is usually a better path.
Embeddings and hidden states
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoTokenizer
name = "sentence-transformers/all-MiniLM-L6-v2"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
texts = ["How do I reset my password?", "Steps to change account password"]
batch = tok(texts, padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
hidden = model(**batch).last_hidden_state # (batch, seq, dim)
mask = batch["attention_mask"].unsqueeze(-1).float()
emb = (hidden * mask).sum(1) / mask.sum(1) # mean pooling over real tokens
emb = F.normalize(emb, dim=-1)
print((emb[0] @ emb[1]).item()) # cosine similarity
For production embeddings, use sentence-transformers, which applies each model’s correct pooling and normalization.
datasets
from datasets import load_dataset, Dataset, DatasetDict
ds = load_dataset("stanfordnlp/imdb") # DatasetDict with train/test/unsupervised
train = load_dataset("stanfordnlp/imdb", split="train[:10%]") # slicing
csv = load_dataset("csv", data_files="data.csv")
jsn = load_dataset("json", data_files={"train": "train.jsonl", "test": "test.jsonl"})
pq = load_dataset("parquet", data_files="data/*.parquet")
stream = load_dataset("stanfordnlp/imdb", split="train", streaming=True) # IterableDataset, no full download
print(next(iter(stream)))
small = Dataset.from_dict({"text": ["a", "b"], "label": [0, 1]})
from_pandas = Dataset.from_pandas(df) # df is a pandas DataFrame
Processing:
ds = load_dataset("stanfordnlp/imdb", split="train")
ds = ds.filter(lambda ex: len(ex["text"]) < 2000)
ds = ds.map(lambda ex: {"n_words": len(ex["text"].split())})
ds = ds.map(lambda batch: tok(batch["text"], truncation=True), batched=True, num_proc=4)
ds = ds.rename_column("label", "labels").remove_columns(["n_words"])
splits = ds.train_test_split(test_size=0.1, seed=42) # shuffled by default
ds = ds.shuffle(seed=42).select(range(1000))
ds.set_format("torch", columns=["input_ids", "attention_mask", "labels"]) # or ds.with_format("torch")
print(ds.features, ds.num_rows, ds[0].keys())
df = ds.to_pandas()
ds.to_parquet("out.parquet")
ds.push_to_hub("my-user/my-dataset")
Version notes: since datasets 4.0, dataset loading scripts (Python files in dataset repos) are no longer supported; datasets on the Hub are stored as data files (Parquet, CSV, JSON and so on). Audio and video decoding uses torchcodec.
Fine-tuning with Trainer
Text classification end to end:
import numpy as np
from datasets import load_dataset
from transformers import (AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding,
Trainer, TrainingArguments)
model_id = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(model_id)
ds = load_dataset("stanfordnlp/imdb")
ds = ds.map(lambda b: tok(b["text"], truncation=True), batched=True)
model = AutoModelForSequenceClassification.from_pretrained(
model_id, num_labels=2, id2label={0: "NEGATIVE", 1: "POSITIVE"}, label2id={"NEGATIVE": 0, "POSITIVE": 1}
)
def compute_metrics(eval_pred):
logits, labels = eval_pred
return {"accuracy": float((np.argmax(logits, axis=-1) == labels).mean())}
args = TrainingArguments(
output_dir="imdb-distilbert",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=2,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
bf16=True, # if your GPU supports it
report_to="none", # the v5 default; set "wandb", "tensorboard", "trackio"... to log
)
trainer = Trainer(
model=model,
args=args,
train_dataset=ds["train"],
eval_dataset=ds["test"],
processing_class=tok, # v5: replaces tokenizer=
data_collator=DataCollatorWithPadding(tokenizer=tok),
compute_metrics=compute_metrics,
)
trainer.train()
print(trainer.evaluate())
trainer.save_model("imdb-distilbert/final")
Useful TrainingArguments: gradient_accumulation_steps, gradient_checkpointing=True, lr_scheduler_type="cosine", warmup_ratio=0.05, logging_steps=50, save_total_limit=2, push_to_hub=True, use_cpu=True (replaces no_cuda).
PEFT: LoRA and QLoRA
from peft import LoraConfig, PeftModel, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype="auto", device_map="auto")
config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=16, # rank: 8 to 64 is typical
lora_alpha=32, # scaling; often 2 × r
lora_dropout=0.05,
target_modules="all-linear", # or a list like ["q_proj", "k_proj", "v_proj", "o_proj"]
)
model = get_peft_model(base, config)
model.print_trainable_parameters() # e.g. "trainable params: ... || all params: ... || trainable%: ..."
# ... train (Trainer or TRL) ...
model.save_pretrained("my-lora") # saves only the small adapter
# later: load and merge
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype="auto")
model = PeftModel.from_pretrained(base, "my-lora")
merged = model.merge_and_unload() # returns a plain model with LoRA folded in
merged.save_pretrained("my-merged-model")
QLoRA = load the base in 4-bit with BitsAndBytesConfig (see Quantization), then add LoRA as above. TRL’s SFTTrainer can do both for you via peft_config=.
| LoRA knob | Effect |
|---|---|
r |
Adapter capacity; higher = more parameters and more memory |
lora_alpha |
Scale of the update (effective scale alpha / r) |
target_modules |
Which layers get adapters; "all-linear" is a strong default |
lora_dropout |
Regularization for small datasets |
| learning rate | Usually higher than full fine-tuning, for example 1e-4 to 2e-4 |
TRL: SFT, DPO, GRPO
Supervised fine-tuning (SFT) on chat data in the messages format:
import torch
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
dataset = load_dataset("trl-lib/Capybara", split="train") # rows: {"messages": [{"role": ..., "content": ...}, ...]}
trainer = SFTTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=dataset,
args=SFTConfig(
output_dir="qwen3-sft",
max_length=1024,
assistant_only_loss=True, # learn only from assistant turns
model_init_kwargs={"dtype": torch.bfloat16}, # otherwise a model given by name loads in float32
),
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear"),
)
trainer.train()
Preference tuning (DPO) with prompt / chosen / rejected data:
from datasets import load_dataset
from trl import DPOConfig, DPOTrainer
trainer = DPOTrainer(
model="Qwen/Qwen3-0.6B",
train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"),
args=DPOConfig(output_dir="qwen3-dpo"),
)
trainer.train()
Reinforcement learning with verifiable rewards (GRPO): write reward functions that score completions, then train:
from trl import GRPOConfig, GRPOTrainer
def reward_short(completions, **kwargs):
# one score per completion; here: prefer answers under 50 words
return [1.0 if len(c[0]["content"].split()) < 50 else 0.0 for c in completions]
trainer = GRPOTrainer(
model="Qwen/Qwen3-0.6B",
reward_funcs=reward_short,
train_dataset=my_prompt_dataset, # rows with a "prompt" (conversational: list of messages)
args=GRPOConfig(output_dir="qwen3-grpo", num_generations=4, max_completion_length=256),
)
trainer.train()
The reward function above assumes a conversational dataset (each completion is a list of messages); for plain-text prompts, completions are strings. TRL also ships ready-made rewards in trl.rewards.
CLI (no Python needed):
trl sft --model_name_or_path Qwen/Qwen3-0.6B --dataset_name trl-lib/Capybara --output_dir qwen3-sft
trl dpo --model_name_or_path Qwen/Qwen3-0.6B --dataset_name trl-lib/ultrafeedback_binarized --output_dir qwen3-dpo
Accelerate
Run the same PyTorch loop on CPU, one GPU or many GPUs:
from accelerate import Accelerator
accelerator = Accelerator(mixed_precision="bf16") # or configure via `accelerate config`
model, optimizer, train_dl, scheduler = accelerator.prepare(model, optimizer, train_dl, scheduler)
for batch in train_dl:
optimizer.zero_grad()
loss = model(**batch).loss
accelerator.backward(loss) # instead of loss.backward()
optimizer.step()
scheduler.step()
# evaluation across processes
preds, refs = accelerator.gather_for_metrics((preds, refs))
accelerator.save_model(model, "out")
accelerate config # answer a few questions once
accelerate launch train.py --lr 3e-4 # runs on all configured devices
accelerate launch --num_processes 4 train.py
sentence-transformers
from sentence_transformers import CrossEncoder, SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
docs = ["The cat sits on the mat.", "Stock markets fell sharply today.", "A kitten is resting on a rug."]
doc_emb = model.encode(docs, normalize_embeddings=True)
query_emb = model.encode(["Where is the cat?"], normalize_embeddings=True)
scores = model.similarity(query_emb, doc_emb) # cosine by default
print(scores)
# retrieval models with separate query/document handling
qwen = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B")
q = qwen.encode_query(["Where is the cat?"])
d = qwen.encode_document(docs)
print(qwen.similarity(q, d))
# rerank candidates with a cross-encoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
print(reranker.predict([("Where is the cat?", doc) for doc in docs]))
Pick models from the MTEB leaderboard for your language and task; check their license and maximum input length.
diffusers
import torch
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5",
dtype=torch.float16,
)
pipe = pipe.to("cuda") # or "mps" on Apple Silicon
image = pipe("a watercolor lighthouse at sunrise", num_inference_steps=30).images[0]
image.save("lighthouse.png")
Memory savers: pipe.enable_model_cpu_offload(), pipe.enable_attention_slicing(), smaller height/width, and quantized pipelines (see the diffusers quantization docs). Newer diffusers releases use dtype= like transformers v5.
safetensors
import torch
from safetensors import safe_open
from safetensors.torch import load_file, save_file
tensors = {"weight": torch.randn(4, 4), "bias": torch.zeros(4)}
save_file(tensors, "model.safetensors", metadata={"format": "pt"})
loaded = load_file("model.safetensors") # dict of tensors
with safe_open("model.safetensors", framework="pt", device="cpu") as f: # lazy, per-tensor
print(f.keys(), f.get_tensor("bias"))
Why safetensors: loading never executes code (unlike pickle-based .bin/.pt), it is memory-mappable, and it is the only format save_pretrained writes in v5.
Gradio and Spaces
import gradio as gr
from transformers import pipeline
clf = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
def predict(text):
return {r["label"]: r["score"] for r in clf(text, top_k=None)}
gr.Interface(fn=predict, inputs="text", outputs="label", title="Sentiment").launch()
A chatbot UI around any function:
import gradio as gr
def respond(message, history): # history: list of {"role": ..., "content": ...}
return f"You said: {message}"
gr.ChatInterface(fn=respond).launch()
Deploy to a Space: create one with hf repos create my-demo --repo-type space --sdk gradio, add app.py and requirements.txt, then hf upload my-user/my-demo . . --repo-type space. Check the Spaces documentation for current hardware options and plans.
Serving: transformers serve and Inference Providers
Local OpenAI-compatible server from transformers:
pip install "transformers[serving]"
transformers serve # http://localhost:8000, /v1/chat/completions and more
transformers chat Qwen/Qwen3-0.6B # terminal chat client (talks to `transformers serve`)
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
r = client.chat.completions.create(model="Qwen/Qwen3-0.6B", messages=[{"role": "user", "content": "Hi!"}])
print(r.choices[0].message.content)
For production throughput, dedicated servers such as vLLM, SGLang or Text Generation Inference style deployments are faster; transformers serve is great for development and new architectures.
Hosted inference through the Hub (Inference Providers):
from huggingface_hub import InferenceClient
client = InferenceClient() # uses HF_TOKEN; provider="auto" picks an available provider
resp = client.chat_completion(
messages=[{"role": "user", "content": "Summarize the plot of Hamlet in one sentence."}],
model="Qwen/Qwen3-0.6B", # use a model that is served by a provider
max_tokens=100,
)
print(resp.choices[0].message.content)
Which models are available, which providers serve them and pricing change often; check the model page’s “Inference Providers” widget and the docs.
Migrating from transformers v4 to v5
| v4 code | v5 replacement |
|---|---|
from_pretrained(..., torch_dtype=torch.bfloat16) |
dtype=torch.bfloat16 (default is now "auto") |
from_pretrained(..., load_in_4bit=True) |
quantization_config=BitsAndBytesConfig(load_in_4bit=True) |
use_auth_token=... |
token=... |
Trainer(tokenizer=tok) |
Trainer(processing_class=tok) |
TrainingArguments(no_cuda=True) |
use_cpu=True |
per_gpu_train_batch_size |
per_device_train_batch_size |
report_to defaulted to all installed loggers |
defaults to "none"; set it explicitly |
apply_chat_template(..., return_tensors="pt") returned a tensor |
returns a dict; call model.generate(**inputs) |
tok.encode_plus(...) |
tok(...) |
tok.batch_decode(ids) |
tok.decode(ids) also handles batches (batch_decode deprecated) |
save_pretrained(..., safe_serialization=False) |
removed; always safetensors |
pipeline("summarization"), "translation", "text2text-generation" |
text-generation with an instruct model and a prompt |
TensorFlow / Flax / JAX model classes (TFAutoModel…) |
removed; use PyTorch (or keep transformers v4 for legacy TF code) |
TRANSFORMERS_CACHE |
HF_HOME |
transformers-cli ... |
transformers ... |
huggingface-cli login / download |
hf auth login / hf download |
Read the official v5 migration guide for the complete list.
Common errors and fixes
| Error (abbreviated) | Cause | Fix |
|---|---|---|
401 Client Error / GatedRepoError |
Gated or private model | Accept the terms on the model page, then hf auth login or pass token= |
OSError: ... does not appear to have a file named config.json |
Wrong repo id, missing files, or offline with an empty cache | Check the id; download once online; check HF_HUB_OFFLINE |
CUDA out of memory |
Model or batch too big | dtype=torch.bfloat16, 4-bit loading, smaller batch, gradient_checkpointing=True, LoRA |
ValueError: Asking to pad but the tokenizer does not have a padding token |
LLM tokenizers often lack one | tok.pad_token = tok.eos_token |
| Output repeats the prompt | Decoding the full sequence | Slice off the prompt tokens before decode (see the chat example) |
got an unexpected keyword argument 'tokenizer' in Trainer |
v5 rename | processing_class=tok |
evaluation_strategy not recognized |
Old argument name | eval_strategy |
| Garbled chat output from an instruct model | No chat template applied | Use apply_chat_template or a text-generation pipeline with messages |
trust_remote_code prompt or error |
Repo contains custom model code | Read the code; enable only for trusted repos, or wait for native support |
| Slow downloads | Network or older client | Update huggingface_hub (Xet transfers); set HF_XET_HIGH_PERFORMANCE=1 |
KeyError: 'qwen3' (unknown architecture) |
transformers too old for the model | pip install -U transformers |
| Dataset script error | Loading scripts are no longer supported (datasets 4+) | Use a dataset stored as data files, or load the files directly |
FAQ
What is the difference between transformers and the Hugging Face Hub? transformers is a Python library that runs models; the Hub is the website and storage where models, datasets and Spaces live. huggingface_hub is the client library that talks to the Hub.
Does transformers v5 still support TensorFlow? No. v5 is PyTorch-only. Keep a v4 release for legacy TensorFlow or Flax code, or migrate to PyTorch or Keras-native models.
How do I download a model for offline use? hf download <repo> --local-dir ./model (or let from_pretrained cache it), then load from the folder or set HF_HUB_OFFLINE=1.
Where are models stored? In ~/.cache/huggingface/hub by default. Change it with HF_HOME or HF_HUB_CACHE. Inspect and clean with hf cache ls and hf cache rm.
How do I fine-tune an LLM on one consumer GPU? QLoRA: 4-bit base model plus LoRA adapters with TRL’s SFTTrainer, gradient checkpointing and a small batch with gradient accumulation. 7B-class models fit on 16 to 24 GB GPUs this way.
pipeline vs AutoModel: which should I use? Pipelines for quick inference with sensible pre- and post-processing; Auto classes when you need control over batching, generation, outputs or training.
How do I count tokens for a model? len(tok(text)["input_ids"]) with that model’s tokenizer. For a chat, render the template first: len(tok(tok.apply_chat_template(messages, tokenize=False), add_special_tokens=False)["input_ids"]).
Is evaluate deprecated? Not officially, but it has seen few releases; it still works for classic metrics, and Hugging Face recommends LightEval for evaluating LLMs. Simple metrics are easy to compute with NumPy or scikit-learn.
Can I run Hugging Face models on a Mac? Yes: device_map="mps" works for many models in transformers, and for LLMs MLX or llama.cpp (GGUF) are usually faster.
How do I share a model? model.push_to_hub("user/name") and tok.push_to_hub("user/name"), then write a model card (README.md) with intended use, training data, evaluation and license.
Where to go next
- transformers documentation and the v5 migration guide
- huggingface_hub documentation and hf CLI guide
- datasets documentation
- PEFT documentation and TRL documentation
- Accelerate documentation
- sentence-transformers documentation
- diffusers documentation
- Hugging Face LLM Course (free)
- In this collection: the PyTorch snippets repository, the deep learning cheat sheet, and the GGUF quantization guide for running models locally
Contributing
PRs are welcome. Every snippet should run against the library versions in the “Last reviewed” line, use real model and dataset ids, and prefer the current API over deprecated ones. When an API changes, update the snippet and add a row to the migration table rather than keeping both versions side by side.
If this cheat sheet saved you a docs search, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.