Hugging Face, End to EndLesson 58 of 75

Module 7 · Training and adapting, with the libraries the Hub is built on

Trainer, and what it saves you writing

In this lesson

  • 9 min read
  • 7 reading sections
  • Knowledge check
  • Lesson 2 of 9 in this chapter

This chapter’s goalDecide from evidence whether a task needs fine-tuning at all, run a LoRA or QLoRA adaptation with Trainer or SFTTrainer on a single free GPU, read a loss curve well enough to name what is wrong, and publish an adapter a stranger can apply to the base model.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch2:08Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 9Free · no account needed
Lesson steps

The whole thing, for a classifier

Python
import numpy as np, evaluate
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
                          TrainingArguments, Trainer, DataCollatorWithPadding)

tok = AutoTokenizer.from_pretrained("distilbert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained(
    "distilbert-base-uncased", num_labels=3,
    id2label={0: "neg", 1: "neu", 2: "pos"},
    label2id={"neg": 0, "neu": 1, "pos": 2},
)

ds = ds.map(lambda b: tok(b["text"], truncation=True, max_length=256), batched=True)

f1 = evaluate.load("f1")
def metrics(p):
    preds = np.argmax(p.predictions, axis=1)
    return f1.compute(predictions=preds, references=p.label_ids, average="macro")

args = TrainingArguments(
    output_dir="out",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    num_train_epochs=3,
    eval_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
    metric_for_best_model="f1",
    push_to_hub=True,
    hub_model_id="your-name/reviews-classifier",
)

trainer = Trainer(
    model=model, args=args,
    train_dataset=ds["train"], eval_dataset=ds["validation"],
    data_collator=DataCollatorWithPadding(tok),
    compute_metrics=metrics,
)
trainer.train()
trainer.push_to_hub()

That is a complete, publishable fine-tune. Note id2label passed at construction: the thing whose absence produces LABEL_0 outputs forever, and the cheapest fix in this course.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Every lesson here is open. Your progress is recorded once you pass the Image Generation, in Practice exam.

Stuck on something?Ask Arjun, your AI tutor

How to cite: Addaly (2026) ‘Trainer, and what it saves you writing’, in Hugging Face, End to End. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/hugging-face/the-trainer-api (Accessed: 29 November 2026).