Hub: hosts models, datasets and Spaces (git-based repos)
transformers: model architectures, tokenizers, pipelines, Trainer
datasets: load, process and stream datasets (Apache Arrow)
tokenizers: fast Rust tokenizers
peft: parameter-efficient fine-tuning (LoRA, QLoRA)
trl: SFT, DPO, GRPO and other post-training trainers
accelerate: device placement and distributed training
evaluate / safetensors: metrics and safe weight format
pip install transformers datasets accelerate peft trl
pip install huggingface_hub
hf auth login # paste an access token (older CLI: huggingface-cli login)
hf auth whoami
# Non-interactive (CI)
export HF_TOKEN=hf_xxx
# Cache location (models can be many GBs)
export HF_HOME=/data/hf-cache
Gated models (e.g. Llama) need you to accept the license on the Hub first
The pipeline API wraps tokenizer, model and post-processing in one call.
from transformers import pipeline
clf = pipeline("sentiment-analysis")
clf("I love this cheatsheet")
gen = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct",
device_map="auto", torch_dtype="auto")
gen("Explain LoRA in one sentence.", max_new_tokens=60)
# Other tasks: summarization, translation, question-answering,
# zero-shot-classification, automatic-speech-recognition,
# image-classification, feature-extraction (embeddings)
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
name = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(
name, torch_dtype=torch.bfloat16, device_map="auto")
inputs = tok("Hello", return_tensors="pt").to(model.device)
out = model.generate(**inputs, max_new_tokens=50)
print(tok.decode(out[0], skip_special_tokens=True))
AutoModelForSequenceClassification: classification heads
AutoModelForCausalLM: decoder-only LLMs
AutoModelForSeq2SeqLM: encoder-decoder (T5, BART)
AutoModel: bare backbone, hidden states
enc = tok("Hello world", padding=True, truncation=True,
max_length=512, return_tensors="pt")
enc.input_ids, enc.attention_mask
tok.tokenize("unbelievable") # subword pieces
tok.vocab_size, tok.pad_token
# Chat models: always use the model's own template
messages = [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "What is RAG?"},
]
prompt = tok.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True)
Wrong chat template = silently worse output
out = model.generate(
**inputs,
max_new_tokens=256,
do_sample=True, # False = greedy
temperature=0.7, # lower = more deterministic
top_p=0.9, # nucleus sampling
top_k=50,
repetition_penalty=1.1,
num_beams=1, # >1 = beam search (no sampling)
)
max_new_tokens: limits generated tokens (prefer over max_length)
temperature: only applies when do_sample=True
streaming: use TextStreamer or TextIteratorStreamer
from datasets import load_dataset
ds = load_dataset("imdb") # DatasetDict: train / test
ds = load_dataset("csv", data_files="data.csv")
ds = load_dataset("json", data_files={"train": "tr.jsonl", "test": "te.jsonl"})
ds["train"][0] # one row (dict)
ds["train"].features # schema
ds["train"].shuffle(seed=42).select(range(1000))
ds = ds["train"].train_test_split(test_size=0.1)
def tokenize(batch):
return tok(batch["text"], truncation=True, max_length=256)
ds = ds.map(tokenize, batched=True, num_proc=4,
remove_columns=["text"])
ds = ds.filter(lambda ex: len(ex["input_ids"]) > 5)
ds = ds.rename_column("label", "labels")
ds.set_format("torch")
batched=True is much faster than per-row map
# Datasets too large for disk: stream lazily
ds = load_dataset("HuggingFaceFW/fineweb", split="train", streaming=True)
for ex in ds.take(3):
print(ex["text"][:80])
# Publish your own
ds.push_to_hub("your-username/my-dataset", private=True)
from transformers import (AutoModelForSequenceClassification,
TrainingArguments, Trainer)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
args = TrainingArguments(
output_dir="out",
per_device_train_batch_size=16,
learning_rate=2e-5,
num_train_epochs=3,
eval_strategy="epoch",
save_strategy="epoch",
bf16=True,
load_best_model_at_end=True,
push_to_hub=False,
)
trainer = Trainer(model=model, args=args,
train_dataset=ds["train"], eval_dataset=ds["test"],
compute_metrics=compute_metrics)
trainer.train()
trainer.save_model("out/final")
LoRA freezes the base model and trains small low-rank adapter matrices, so you train well under 1% of parameters.
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import BitsAndBytesConfig
# QLoRA: load the base model in 4-bit
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained(name, quantization_config=bnb,
device_map="auto")
model = prepare_model_for_kbit_training(model)
cfg = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
model = get_peft_model(model, cfg)
model.print_trainable_parameters()
r: adapter rank; higher = more capacity, more memory
lora_alpha: scaling factor (alpha / r)
merge: model.merge_and_unload() folds adapters into the base weights
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
model=name,
train_dataset=ds, # "messages" or "text" column
args=SFTConfig(output_dir="sft-out", per_device_train_batch_size=4,
gradient_accumulation_steps=4, learning_rate=2e-4,
num_train_epochs=1, bf16=True),
peft_config=cfg, # optional LoRA
)
trainer.train()
- SFTTrainer: instruction / chat tuning
- DPOTrainer: preference pairs (chosen / rejected)
- GRPOTrainer: RL with verifiable rewards
hf download Qwen/Qwen2.5-0.5B-Instruct --local-dir ./qwen
hf download org/repo config.json # single file
hf upload your-username/my-model ./out . # upload a folder
# Python
model.push_to_hub("your-username/my-model")
tok.push_to_hub("your-username/my-model")
from huggingface_hub import snapshot_download
snapshot_download("org/repo", allow_patterns=["*.safetensors", "*.json"])
accelerate config # one-time interactive setup
accelerate launch train.py # runs on all configured GPUs
# In code
from accelerate import Accelerator
acc = Accelerator(mixed_precision="bf16", gradient_accumulation_steps=4)
model, opt, loader = acc.prepare(model, opt, loader)
for batch in loader:
with acc.accumulate(model):
loss = model(**batch).loss
acc.backward(loss)
opt.step(); opt.zero_grad()
Trainer and TRL already use Accelerate under the hood
bitsandbytes 8-bit / 4-bit: easy on-the-fly loading; good for QLoRA
GPTQ / AWQ: post-training 4-bit weight quantization for fast GPU inference
GGUF: llama.cpp / Ollama format
torch_dtype="auto": loads weights in their saved precision
from transformers import BitsAndBytesConfig
model = AutoModelForCausalLM.from_pretrained(
name, device_map="auto",
quantization_config=BitsAndBytesConfig(load_in_8bit=True))
# Rough memory: params x bytes/param (fp16 = 2, int8 = 1, int4 = 0.5)