Start hereQuick start · 6 you’ll reach for daily
Target versions · paceVersions
transformers ≥ 4.45
datasets ≥ 2.20
accelerate ≥ 0.34
torch ≥ 2.4
Hugging Face transformers moves fast — new model classes,
cache formats, and trainer args each minor release. This sheet pins to the May 2026 surface. Always check
the model’s README.md on the Hub for required
trust_remote_code, custom chat templates, and recommended dtype.
install · auth · smokeSetup
# Core + the bits you usually want
pip install -U "transformers[torch]" datasets accelerate evaluate
# Optional speedups
pip install -U flash-attn --no-build-isolation # Ada / Hopper GPUs
pip install -U bitsandbytes # 4 / 8-bit weights
# Hub auth (download gated / private models, push checkpoints)
huggingface-cli login
# Sanity test the install
python - <<'PY'
import torch
from transformers import pipeline
print(torch.cuda.is_available(), torch.cuda.device_count())
print(pipeline("sentiment-analysis")("Transformers is great"))
PY
where things liveCommon imports
Models, tokenizers, pipelines, training, generation utilities all sit at the top level of
transformers. Datasets + metrics in sibling packages.
| from transformers import pipeline | One-line task runner. |
| from transformers import AutoTokenizer, AutoModel | Tokenizer + base model heads. |
| from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM | Generation models. |
| from transformers import AutoModelForSequenceClassification, …ForTokenClassification, …ForQuestionAnswering | Classic NLP heads. |
| from transformers import AutoProcessor, AutoFeatureExtractor | Multimodal (vision / audio) wrappers. |
| from transformers import Trainer, TrainingArguments | High-level training loop. |
| from transformers import GenerationConfig, TextStreamer, TextIteratorStreamer | Generation knobs + streaming. |
| from transformers import BitsAndBytesConfig | 4 / 8-bit quantisation config. |
| from datasets import load_dataset, Dataset | Hub datasets + in-memory dataset class. |
| import evaluate | Metric library (accuracy, f1, bleu, rouge, …). |
zero-config inferencePipelines
| pipeline("sentiment-analysis") | Picks a default model. Good for sanity checks. |
| pipeline(task, model="org/name") | Pin a model. Loads tokenizer + model. |
| pipeline("text-generation", model=…) | Plain LLM completion. |
| pipeline("text-classification" / "zero-shot-classification") | Single-label / zero-shot. |
| pipeline("token-classification", aggregation_strategy="simple") | NER. Merges sub-tokens. |
| pipeline("summarization" / "translation_xx_to_yy") | Seq2seq tasks. |
| pipeline("automatic-speech-recognition", model="openai/whisper-large-v3") | Audio → text. |
| pipeline("image-to-text" / "visual-question-answering") | Vision-language. |
| pipe(inputs, batch_size=8, device=0) | Batched + pinned device. |
| pipe.tokenizer / pipe.model | Drop down to the wrapped objects when needed. |
AutoModel +
explicit batching — pipelines hide GPU memory choices and rebuild caches per call.
text ↔ idsTokenizers
| AutoTokenizer.from_pretrained(name) | Loads the fast tokenizer if available. |
| tok(text, return_tensors="pt") | Encode → dict of tensors. |
| tok(text, truncation=True, max_length=512) | Trim long inputs. |
| tok(text, padding="longest" / "max_length") | Pad for batching. |
| tok.batch_decode(ids, skip_special_tokens=True) | Decode back to strings. |
| tok.apply_chat_template(messages, add_generation_prompt=True) | Preferred Render messages into the model’s template. |
| tok.pad_token = tok.eos_token | Common fix for causal LMs missing pad. |
| tok.add_special_tokens({"additional_special_tokens":[…]}) | Extend vocab; remember model.resize_token_embeddings. |
| tok.is_fast | True → Rust-backed tokenizer (much faster). |
AutoModel familiesModels
| AutoModel | Raw encoder / decoder output. Use for embeddings. |
| AutoModelForCausalLM | Decoder-only (GPT-style). Generation. |
| AutoModelForSeq2SeqLM | Encoder-decoder (T5 / BART). Translation, summary. |
| AutoModelForMaskedLM | BERT-style mask filling. |
| AutoModelForSequenceClassification | Classification head on top of base. |
| AutoModelForTokenClassification | NER / POS / span tagging. |
| AutoModelForQuestionAnswering | SQuAD-style extractive QA. |
| from_pretrained(name, torch_dtype=torch.bfloat16) | Load in bf16; halves memory on Ampere+. |
| from_pretrained(…, device_map="auto") | Auto-shard across GPUs / CPU offload. |
| from_pretrained(…, quantization_config=BitsAndBytesConfig(load_in_4bit=True)) | 4-bit NF4 + LoRA-ready. |
| from_pretrained(…, attn_implementation="flash_attention_2") | Flash attention 2 on supported GPUs. |
| model.save_pretrained(path) / push_to_hub(…) | Persist weights + config. |
decode & sampleGeneration
| model.generate(input_ids, max_new_tokens=200) | Greedy default. |
| do_sample=True, temperature=0.7 | Stochastic sampling. |
| top_p=0.9, top_k=50 | Nucleus + top-k filter. |
| num_beams=4 | Beam search. Avoid for chat — too monotone. |
| repetition_penalty=1.1 | Suppress n-gram echo. |
| no_repeat_ngram_size=3 | Hard ban on repeating n-grams. |
| stop_strings=["\nUser:"] | Stop on a sub-string (3.42+). |
| eos_token_id / pad_token_id | Set both. Missing pad breaks batched generation. |
| streamer=TextStreamer(tok) | Stream tokens to stdout. |
| streamer=TextIteratorStreamer(tok) | Iterator form. Drive from another thread. |
| GenerationConfig(…) | Bundle defaults; save next to weights. |
| use_cache=True | KV cache. On by default; turn off only when debugging. |
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
name = "Qwen/Qwen2.5-7B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(
name, torch_dtype=torch.bfloat16, device_map="auto",
attn_implementation="flash_attention_2",
)
messages = [
{"role": "system", "content": "You are a careful assistant."},
{"role": "user", "content": "Summarise the Transformer paper in 2 lines."},
]
inputs = tok.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt",
).to(model.device)
# Sampling + repetition controls + streaming
streamer = TextStreamer(tok, skip_prompt=True, skip_special_tokens=True)
out = model.generate(
inputs,
max_new_tokens=256,
do_sample=True, temperature=0.7, top_p=0.9, top_k=50,
repetition_penalty=1.1,
eos_token_id=tok.eos_token_id,
pad_token_id=tok.eos_token_id,
streamer=streamer,
)
load & transformDatasets
| load_dataset("imdb") | Hub dataset. |
| load_dataset("json", data_files="train.jsonl", split="train") | Local JSONL / CSV / parquet. |
| ds.train_test_split(test_size=0.1, seed=42) | Reproducible split. |
| ds.map(fn, batched=True, num_proc=8) | Parallel map. Use for tokenisation. |
| ds.filter(fn, num_proc=8) | Parallel filter. |
| ds.shuffle(seed=42).select(range(2000)) | Sub-sample for fast iteration. |
| ds.set_format("torch") | Yields PyTorch tensors via __getitem__. |
| ds.with_format("numpy") / "pandas" | Per-call format switch. |
| ds.push_to_hub("org/name", private=True) | Upload to Hub. |
| load_dataset(…, streaming=True) | Iterable, no full download. Use for huge corpora. |
high-level training loopTrainer
| TrainingArguments(output_dir=…, …) | All hyperparams in one dataclass. |
| eval_strategy="epoch" / "steps" | When to run validation. |
| save_strategy="epoch", save_total_limit=3 | Rotate checkpoints. |
| load_best_model_at_end=True, metric_for_best_model=… | Auto-select best by held-out metric. |
| bf16=True / fp16=True | Mixed precision. bf16 on Ampere+. |
| gradient_checkpointing=True | Memory ↓, speed ↓~20%. Use when batch ↓ bottlenecked. |
| gradient_accumulation_steps=N | Effective batch = per-device × N × #GPUs. |
| deepspeed="ds_config.json" | DeepSpeed ZeRO for multi-GPU. |
| Trainer(model, args, train_dataset, eval_dataset, compute_metrics=…) | Wire everything. |
| trainer.train() / trainer.evaluate() | Run / re-run validation. |
| trainer.save_model(…) / push_to_hub(…) | Persist artefact. |
| trainer.add_callback(EarlyStoppingCallback(patience=3)) | Hooks for early stop, logging, … |
from datasets import load_dataset
from transformers import (
AutoModelForSequenceClassification, AutoTokenizer,
DataCollatorWithPadding, Trainer, TrainingArguments,
)
import evaluate, numpy as np
name = "bert-base-uncased"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
ds = load_dataset("imdb").shuffle(seed=42)
ds["train"] = ds["train"].select(range(2000)) # subsample for speed
def tokenize(b):
return tok(b["text"], truncation=True, max_length=256)
ds = ds.map(tokenize, batched=True)
accuracy = evaluate.load("accuracy")
def metrics(p):
return accuracy.compute(
predictions=np.argmax(p.predictions, axis=1), references=p.label_ids,
)
args = TrainingArguments(
output_dir="out", num_train_epochs=2,
per_device_train_batch_size=16, per_device_eval_batch_size=32,
learning_rate=2e-5, warmup_ratio=0.06, weight_decay=0.01,
eval_strategy="epoch", save_strategy="epoch",
load_best_model_at_end=True, metric_for_best_model="accuracy",
bf16=True, logging_steps=20, report_to="none",
)
Trainer(
model=model, args=args,
train_dataset=ds["train"], eval_dataset=ds["test"],
tokenizer=tok, data_collator=DataCollatorWithPadding(tok),
compute_metrics=metrics,
).train()
4-bit · chat template · streamEnd-to-end · Local Q&A
Load an 8B Llama-3 instruct in 4-bit, render the chat template, stream tokens from a background thread. Fits on a single 24 GB GPU.
# Local Q&A: load 4-bit -> chat-template prompt -> stream answer.
import torch
from transformers import (
AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextIteratorStreamer,
)
from threading import Thread
name = "meta-llama/Llama-3.1-8B-Instruct"
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16)
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(
name, quantization_config=bnb, device_map="auto",
attn_implementation="flash_attention_2",
)
def ask(question: str) -> str:
msgs = [
{"role": "system", "content": "Answer concisely."},
{"role": "user", "content": question},
]
ids = tok.apply_chat_template(msgs, add_generation_prompt=True,
return_tensors="pt").to(model.device)
streamer = TextIteratorStreamer(tok, skip_prompt=True, skip_special_tokens=True)
Thread(target=model.generate, kwargs=dict(
input_ids=ids, streamer=streamer, max_new_tokens=400,
do_sample=False, eos_token_id=tok.eos_token_id, pad_token_id=tok.eos_token_id,
)).start()
return "".join(streamer)
print(ask("Explain attention in one paragraph."))
Best practiceGood to know
apply_chat_template, not f-strings.
Every chat model has its own special tokens. Hand-rolling the prompt usually loses 5-15 points on
benchmarks because of one missing token.
torch_dtype + device_map at load.
Default fp32 on CPU is the most common “why is this so slow / OOM”. Set
bfloat16 + device_map="auto".
ds.map(…, batched=True).
Per-row Python loops are 50× slower than batched fast-tokenizer calls. The trainer expects
pre-tokenised columns anyway.
Common trapsWatch out for
tok.pad_token = tok.eos_token AND
pass pad_token_id=… to generate.
trust_remote_code=True runs arbitrary code from the Hub.
Required for many newer architectures. Treat it like installing an unaudited package: pin a revision,
review the modelling file, or mirror to your own org.
bitsandbytes + CUDA.
Older builds fall back silently to fp16, eating memory you thought you saved. Verify with
model.is_quantized and torch.cuda.memory_allocated().