Loading...
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Hugging Face is an ecosystem for using, training, and sharing ML models—especially transformers—through a model hub plus libraries like Transformers, Datasets, and Tokenizers.
Hosted models with versioned weights, configs, and cards. Search 500k+ public checkpoints; push your own with huggingface_hub.
High-level APIs for inference and training across tasks: NLP, vision, speech, multimodal. Supports PyTorch, TensorFlow, and JAX.
Dataset loading, preprocessing, caching, and streaming. Memory-mapped Arrow format keeps RAM usage low even for huge corpora.
Fast Rust-backed tokenization aligned with pretrained model vocabularies. Handles BPE, WordPiece, Unigram, and SentencePiece.
Minimal wrapper to run the same PyTorch training loop on CPU, multi-GPU, or TPU without rewriting your code.
Parameter-Efficient Fine-Tuning methods (LoRA, Prefix Tuning, Adapter layers) that fine-tune large models with a fraction of the compute.
Standardised metric implementations (BLEU, F1, Accuracy, ROUGE) with consistent interfaces across tasks.
Free hosting for Gradio or Streamlit demos backed by your Hub models — shareable links with zero DevOps.
Treat Hugging Face as a package manager for models + the runtime tooling to use them. You pick a checkpoint, load it with the right tokenizer, and run inference or fine-tuning with a trainer.
Every workflow follows the same three-step pattern: checkpoint → tokenizer → model. The checkpoint ID (e.g. bert-base-uncased) is the single source of truth; passing it to both AutoTokenizer.from_pretrained() and AutoModel.from_pretrained() guarantees they always match.
pipeline(task) selects a sensible default model. Pass an explicit model= argument to override.
| Task string | What it does | Example model |
|---|---|---|
| sentiment-analysis | Classify text sentiment (pos/neg/neutral) | distilbert-base-uncased-finetuned-sst-2-english |
| text-generation | Auto-regressively generate text | gpt2 |
| text2text-generation | Seq2seq: summarise, translate, Q&A | t5-small |
| fill-mask | Predict masked tokens in a sentence | bert-base-uncased |
| question-answering | Extract an answer span from a passage | deepset/roberta-base-squad2 |
| summarization | Compress long text to a shorter summary | facebook/bart-large-cnn |
| translation | Translate between language pairs | Helsinki-NLP/opus-mt-en-fr |
| ner | Named-entity recognition | dbmdz/bert-large-cased-finetuned-conll03-english |
| zero-shot-classification | Classify without task-specific training | facebook/bart-large-mnli |
| image-classification | Classify an image into categories | google/vit-base-patch16-224 |
| object-detection | Bounding-box detection in images | facebook/detr-resnet-50 |
| automatic-speech-recognition | Transcribe audio to text | openai/whisper-base |
Use Auto* classes whenever you do not know the exact architecture ahead of time — they inspect the config and load the right class automatically.
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
model_id = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id)
inputs = tokenizer("Hugging Face makes ML accessible.", return_tensors="pt")
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=-1)
label = model.config.id2label[probs.argmax().item()]
print(label, probs.max().item())load_dataset downloads, caches, and memory-maps the data as Apache Arrow. Use streaming=True for datasets that do not fit in RAM.
from datasets import load_dataset, DatasetDict
ds = load_dataset("imdb") # DatasetDict with train/test splits
print(ds["train"][0]) # {'text': '...', 'label': 1}
# Tokenize the whole split in parallel (fast Rust tokenizer)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, padding="max_length")
tokenized = ds.map(tokenize, batched=True, num_proc=4)Trainerhandles the training loop, gradient accumulation, evaluation, checkpointing, and logging to TensorBoard / W&B with zero boilerplate.
from transformers import TrainingArguments, Trainer
import numpy as np
from evaluate import load as load_metric
accuracy = load_metric("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=-1)
return accuracy.compute(predictions=preds, references=labels)
args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
logging_dir="./logs",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=tokenized["train"],
eval_dataset=tokenized["test"],
compute_metrics=compute_metrics,
)
trainer.train()LoRA freezes the base model and injects trainable low-rank matrices into attention layers. You typically train under 1% of parameters, making it feasible on a single GPU.
from peft import LoraConfig, get_peft_model, TaskType
lora_cfg = LoraConfig(
task_type=TaskType.SEQ_CLS,
r=8, # rank of the low-rank matrices
lora_alpha=16, # scaling factor
lora_dropout=0.1,
target_modules=["q_lin", "v_lin"],
)
peft_model = get_peft_model(model, lora_cfg)
peft_model.print_trainable_parameters()
# trainable params: 294,912 || all params: 66,955,010 || trainable%: 0.44
trainer = Trainer(model=peft_model, args=args, ...)Share your fine-tuned model (weights + tokenizer + config + model card) in one call. The repo is versioned with Git-LFS under the hood.
# Authenticate once in terminal: huggingface-cli login
trainer.push_to_hub("my-org/distilbert-sst2-finetuned")
# Or push individually:
model.push_to_hub("my-org/my-model")
tokenizer.push_to_hub("my-org/my-model")Wrap your existing training loop with Accelerator. No conditional if cuda blocks — the same script runs on a laptop or an 8-GPU node.
from accelerate import Accelerator
accelerator = Accelerator()
model, optimizer, train_dl, eval_dl = accelerator.prepare(
model, optimizer, train_dataloader, eval_dataloader
)
for batch in train_dl:
outputs = model(**batch)
loss = outputs.loss
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()Always prefer Auto* over architecture-specific classes unless you are deliberately targeting a single architecture.
| Class | Use for |
|---|---|
| AutoTokenizer | Any tokenizer matching the checkpoint |
| AutoConfig | Inspect hyperparams without loading weights |
| AutoModel | Bare model — raw hidden states, no task head |
| AutoModelForSequenceClassification | Text classification / regression |
| AutoModelForTokenClassification | NER, POS tagging |
| AutoModelForQuestionAnswering | Extractive QA (span prediction) |
| AutoModelForSeq2SeqLM | Summarisation, translation, T5-style tasks |
| AutoModelForCausalLM | GPT-style auto-regressive generation |
| AutoModelForMaskedLM | BERT-style masked-language modelling |
| AutoModelForImageClassification | Vision classification |
| AutoModelForSpeechSeq2Seq | ASR (e.g. Whisper) |
| AutoProcessor | Multimodal (image+text, audio+text) preprocessing |
The tokenizer splits text into sub-word tokens, maps them to integer IDs, and optionally adds special tokens ([CLS], [SEP], etc.). Decode with tokenizer.decode(ids, skip_special_tokens=True).
padding="longest" pads to the longest sequence in the batch. padding="max_length" pads to the model's maximum context window. truncation=True silently drops tokens beyond max_length — always set it explicitly.
Pass return_tensors="pt" for PyTorch, "tf" for TensorFlow, or "np" for NumPy. Omit it for plain Python lists (useful for inspection).
The tokenizer automatically produces attention_mask tensors (1 = real token, 0 = padding). Always pass the mask to the model so padding tokens are ignored during attention.
HuggingFace ships both a Rust-backed fast tokenizer and a Python slow one. The fast version is 10-100x faster and required for some post-processing features (offset mapping for NER, word IDs). It is loaded by default when available.
from datasets import load_dataset, DatasetDict, Dataset
# Load
ds = load_dataset("glue", "mrpc")
ds = load_dataset("csv", data_files={"train": "train.csv", "test": "test.csv"})
ds = load_dataset("json", data_files="data.jsonl")
# Inspect
print(ds)
print(ds["train"].features)
# Select / filter
small = ds["train"].select(range(1000))
filtered = ds["train"].filter(lambda x: len(x["text"]) > 50)
# Map (batched for speed)
def preprocess(batch):
return tokenizer(batch["sentence1"], batch["sentence2"],
truncation=True, padding="max_length")
encoded = ds.map(preprocess, batched=True,
remove_columns=["sentence1","sentence2","idx"])
encoded.set_format("torch", columns=["input_ids","attention_mask","label"])
# Save / load from disk
encoded.save_to_disk("./encoded_mrpc")
reloaded = DatasetDict.load_from_disk("./encoded_mrpc")from evaluate import load, combine
# Single metric
rouge = load("rouge")
results = rouge.compute(
predictions=["The quick brown fox"],
references=["The fast brown fox jumps"]
)
print(results) # {'rouge1': 0.8, 'rouge2': 0.5, 'rougeL': 0.8, ...}
# Multiple metrics at once
clf_metrics = combine(["accuracy", "f1", "precision", "recall"])
clf_metrics.add_batch(predictions=[0,1,1,0], references=[0,1,0,0])
print(clf_metrics.compute())A README.md with YAML front-matter becomes your model card. Declare language, license, tags, datasets, and metrics so the Hub can index and filter your model correctly.
from huggingface_hub import hf_hub_download, list_models, snapshot_download
# Download a single file
path = hf_hub_download(repo_id="bert-base-uncased", filename="config.json")
# Clone the whole repo (useful for non-Transformers models)
snapshot_download(repo_id="stabilityai/stable-diffusion-2-1", local_dir="./sd21")
# Search the Hub
models = list_models(filter="text-classification", sort="downloads", limit=5)
for m in models:
print(m.modelId, m.downloads)# app.py (push this file + requirements.txt to your Space repo)
import gradio as gr
from transformers import pipeline
pipe = pipeline("sentiment-analysis")
def predict(text):
result = pipe(text)[0]
return f"{result['label']} ({result['score']:.2%})"
gr.Interface(fn=predict, inputs="text", outputs="text").launch()Loading a GPT-2 tokenizer with a BERT model produces silently wrong results. Always use the same checkpoint ID for both. If in doubt, check model.config._name_or_path.
Reduce per_device_train_batch_size, enable gradient checkpointing (model.gradient_checkpointing_enable()), or use fp16=True in TrainingArguments. LoRA / PEFT is often the cleanest solution for large models.
Hugging Face occasionally changes the default model behind a pipeline task. Pin an explicit model= argument in production to avoid silent regressions after package upgrades.
Run .map() with batched=True and num_proc > 1. The fast tokenizer processes thousands of sequences per second; the slow one is orders of magnitude slower at scale.
Dropout and batch-normalisation layers behave differently in training vs eval mode. Always call model.eval() before inference and wrap with torch.no_grad() to save memory.
Pin versions in requirements.txt: transformers, datasets, tokenizers, accelerate, and your PyTorch/CUDA build must be mutually compatible. The HF release notes list known constraints.
Pipeline inference + tokenizer/model loading.
| Framework | Best at | Typical tasks | Output |
|---|---|---|---|
| NumPy | Fast array math + linear algebra | Numerics, prototyping, preprocessing | ndarray (CPU) |
| Pandas | Tabular ETL + joins + aggregation | Cleaning, feature engineering, analysis | DataFrame / Series |
| scikit-learn | Classical ML + evaluation + pipelines | Baselines, CV, model selection | Estimator / Pipeline |
| PyTorch | Neural nets + custom training loops | Deep learning, research, fine-tuning | Tensors + nn.Module |
| TensorFlow | Keras training + production deployment | Deep learning, serving, mobile/edge | Tensors + Keras Model |
| Hugging Face | Model hub + transformer tooling | Inference, fine-tuning, sharing | Checkpoints + pipelines |