DS DevShelfHub Projects · AI tools
Cheatsheets / Transformers
Cheatsheet · AI frameworks

Transformers Cheatsheet: Pipelines, AutoModels and Trainer Reference

By DevShelfHub

Hugging Face transformers — pipelines, tokenizers, AutoModels, generation, Trainer, datasets, and the everyday API.

81 items 7 min Pipelines AutoModel Trainer

Start hereQuick start · 6 you’ll reach for daily

One-linerpipeline("text-generation")
TokenizeAutoTokenizer.from_pretrained(…)
Load modelAutoModelForCausalLM.from_pretrained(…)
Generatemodel.generate(input_ids, …)
Chat templatetok.apply_chat_template(msgs)
TrainTrainer(model, args, …).train()

Target versions · paceVersions

Targets: 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

bash
# 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 pipelineOne-line task runner.
from transformers import AutoTokenizer, AutoModelTokenizer + base model heads.
from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLMGeneration models.
from transformers import AutoModelForSequenceClassification, …ForTokenClassification, …ForQuestionAnsweringClassic NLP heads.
from transformers import AutoProcessor, AutoFeatureExtractorMultimodal (vision / audio) wrappers.
from transformers import Trainer, TrainingArgumentsHigh-level training loop.
from transformers import GenerationConfig, TextStreamer, TextIteratorStreamerGeneration knobs + streaming.
from transformers import BitsAndBytesConfig4 / 8-bit quantisation config.
from datasets import load_dataset, DatasetHub datasets + in-memory dataset class.
import evaluateMetric 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.modelDrop down to the wrapped objects when needed.
Pipelines are great for prototypes and notebooks. For production, drop to 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_tokenCommon fix for causal LMs missing pad.
tok.add_special_tokens({"additional_special_tokens":[…]})Extend vocab; remember model.resize_token_embeddings.
tok.is_fastTrue → Rust-backed tokenizer (much faster).

AutoModel familiesModels

AutoModelRaw encoder / decoder output. Use for embeddings.
AutoModelForCausalLMDecoder-only (GPT-style). Generation.
AutoModelForSeq2SeqLMEncoder-decoder (T5 / BART). Translation, summary.
AutoModelForMaskedLMBERT-style mask filling.
AutoModelForSequenceClassificationClassification head on top of base.
AutoModelForTokenClassificationNER / POS / span tagging.
AutoModelForQuestionAnsweringSQuAD-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.7Stochastic sampling.
top_p=0.9, top_k=50Nucleus + top-k filter.
num_beams=4Beam search. Avoid for chat — too monotone.
repetition_penalty=1.1Suppress n-gram echo.
no_repeat_ngram_size=3Hard ban on repeating n-grams.
stop_strings=["\nUser:"]Stop on a sub-string (3.42+).
eos_token_id / pad_token_idSet 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=TrueKV cache. On by default; turn off only when debugging.
python
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=3Rotate checkpoints.
load_best_model_at_end=True, metric_for_best_model=…Auto-select best by held-out metric.
bf16=True / fp16=TrueMixed precision. bf16 on Ampere+.
gradient_checkpointing=TrueMemory ↓, speed ↓~20%. Use when batch ↓ bottlenecked.
gradient_accumulation_steps=NEffective 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, …
python
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.

python
# 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

Use 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.
Pin 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".
Tokenise inside 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

Missing pad token breaks batched generation. Causal LMs often ship without one. Set 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.
4-bit quantisation needs a recent 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().

Go deeperSee also

Transformers FAQ

What is the Hugging Face Transformers library?

Hugging Face Transformers is the de-facto Python library for working with pre-trained transformer models — BERT, GPT-2, T5, Llama, Mistral, and thousands more. It provides a unified API for text, vision, audio, and multimodal models through pipelines (high-level) and AutoModel/AutoTokenizer (low-level). Models are downloaded from the Hugging Face Hub.

What is a Transformers pipeline and when should I use it?

pipeline('task', model='model-id') is the highest-level API — it handles tokenization, model inference, and postprocessing in one call. Use it for quick inference, prototyping, and standard tasks (text-generation, sentiment-analysis, ner, translation, etc.). Switch to AutoModel + manual tokenization when you need logits, custom batching, or non-standard output.

What is the difference between AutoModel and AutoModelForCausalLM?

AutoModel loads the base model (encoder/decoder trunk, no task head). Task-specific variants add heads: AutoModelForCausalLM adds a language model head for text generation, AutoModelForSequenceClassification adds a classification head, and so on. Always use the task-specific class if you want to fine-tune or run generation — the base AutoModel is mainly for feature extraction.

How does the Transformers Trainer work?

Trainer wraps the training loop for fine-tuning. Provide a model, TrainingArguments (output dir, epochs, batch size, learning rate, etc.), train and eval datasets, and an optional compute_metrics function. Call trainer.train() to start. It handles gradient accumulation, mixed precision, multi-GPU, and Weights & Biases logging automatically.

How do I run inference on GPU with Transformers?

Pass device_map='auto' to from_pretrained() and the library places layers across available GPUs automatically (requires accelerate). For single-GPU, use model.to('cuda'). For quantized inference, add load_in_4bit=True or load_in_8bit=True (requires bitsandbytes) to load large models on consumer GPUs.

Is the Transformers library free and open source?

Yes. The Transformers library is Apache-2.0 licensed and free. The Hugging Face Hub for downloading models is free for public models; private model hosting has paid plans. Model weights vary in licence — always check the model card before commercial use.