Key ideas
- Pipelines.
pipeline(task)bundles three steps: the tokenizer preprocesses the text, the model runs, and the output is post-processed into labels, scores or text; withoutmodel=a default checkpoint for the task is used1. Know which task does what:text-classification/sentiment-analysis(a label for a whole text),ner(entity spans such as PER, ORG, LOC),fill-mask,zero-shot-classification(you supplycandidate_labelsat call time),text-generation,summarization,translation1. - Mask tokens differ between checkpoints: the course's default fill-mask model uses
<mask>, whilebert-base-caseduses[MASK](see the code below); check the model before writing the prompt1. - Tokenizers turn text into numbers. Most checkpoints use subword tokenization: frequent words stay whole, rare words are split into meaningful pieces (BERT marks continuations with
##)2.tokenize()returns a list of strings;convert_tokens_to_ids()maps them to vocabulary IDs;decode()goes back to text2. Calling the tokenizer directly does everything at once: tokens, IDs, the model's special tokens ([CLS]β¦[SEP]for BERT), padding/truncation and anattention_mask, withreturn_tensors="pt"for PyTorch. - Auto classes.
AutoTokenizer.from_pretrained(ckpt)andAutoModelβ¦from_pretrained(ckpt)read the checkpoint and build the right class. Load tokenizer and model from the same checkpoint, or the IDs mean nothing to the model2. - The Hub. Every model on the Hugging Face Hub is stored as a git repository, so its files are versioned; the Hub is not tied to π€ Transformers and also hosts models from libraries such as timm (vision), pyannote and Asteroid (speech) or Flair (NLP)7. A repo's
README.mdis its model card, a Markdown document on what the model is, its intended uses and limitations (bias included), its training data and procedure and its evaluation results, so others can judge whether it suits them8. - Datasets: map.
Dataset.map(fn, batched=True)passes many examples per call (each column as a list); with a fast tokenizer this was about 30 times faster than unbatched slow tokenization in the course's test3. Padding is a separate step: a data collator pads each batch6. - Datasets: slicing. A random sample is
ds.shuffle(seed=β¦).select(range(n)), shuffle first;selecttakes row indices,filtertakes a function that returnsTruefor rows to keep3. There is nods.sample(), and the first argument ofshuffleis the seed. - Big data. π€ Datasets stores data with Apache Arrow as memory-mapped files, a mapping between RAM and disk: you can work with datasets much larger than RAM, and several processes can share the file, so
map()can run in parallel without copying4. Withstreaming=True,load_datasetreturns anIterableDataset: nothing is downloaded up front, and examples are read by iterating (next(iter(ds)),take(n),skip(n)), not by index4. - Custom training loop. Drop the raw text columns the model does not expect, rename
labeltolabels, set the format to PyTorch tensors, and move both model and batches to one device5. Every π€ Transformers model returnsoutputs.losswhen the batch containslabels, so you calloutputs.loss.backward()without writing a loss function5. Evaluate withmodel.eval()andtorch.no_grad(). Accelerate runs the same loop on multiple GPUs/TPUs:accelerator.prepare(...)wraps model, optimizer and dataloaders, andaccelerator.backward(loss)replacesloss.backward()5. - Trainer. The
Trainer(orSeq2SeqTrainer) takes the model, the training arguments, the datasets, a data collator and an optionalcompute_metrics, which receives(predictions, labels)at evaluation time and returns a dict of metric values such as BLEU or accuracy6. It does not compute the training loss. - Sequence-to-sequence. Padded positions in
labelsare set to β100 so the loss ignores them (PyTorch's cross-entropy skips index β100);DataCollatorForSeq2Seqdoes this, whileDataCollatorWithPaddingpads only the inputs6.Seq2SeqTraineraddsgenerate()to evaluation, because at inference the decoder must produce its output token by token6.
Formulas
- Mean token loss with ignored positions: .
- Tokenized batch:
input_idsandattention_maskboth have shape (batch, longest sequence); the mask is 1 on real tokens and 0 on padding.
Worked example
Token logits , , over a 2-word vocabulary, labels :
- position 1: ;
- position 2 is padding and is skipped, so it does not matter that the model "predicted" word 1 there;
- position 3: .
The loss is , an average over the 2 real targets, not 3. Had the padding been labelled with the pad token's ID instead, the model would be trained to predict padding.
In code
from transformers import AutoTokenizer
from datasets import Dataset
tok = AutoTokenizer.from_pretrained("bert-base-cased")
print(tok.tokenize("Hello!"), tok.mask_token) # ['Hello', '!'] [MASK]
enc = tok(["Hello!", "Hi"], padding=True, return_tensors="pt")
print(tok.convert_ids_to_tokens(enc["input_ids"][1])) # ['[CLS]', 'Hi', '[SEP]', '[PAD]']
print(enc["attention_mask"].tolist()) # [[1, 1, 1, 1], [1, 1, 1, 0]]
ds = Dataset.from_dict({"name": ["Luna", "Max", "Leo", "Bella"], "label": [0, 1, 1, 0]})
print(len(ds.shuffle(seed=0).select(range(2)))) # 2: a random sample of 2 rows
print(list(ds.filter(lambda x: x["name"].startswith("L"))["name"])) # ['Luna', 'Leo']
ds = ds.map(lambda b: {"n_chars": [len(n) for n in b["name"]]}, batched=True)
print(ds.column_names) # ['name', 'label', 'n_chars']
Common pitfalls
tokenizer.tokenize(text)gives token strings, not IDs and not tensors2.- Special tokens such as
[CLS]and[SEP]are added by the tokenizer, not by the model; padding comes last, after the special tokens. - A BERT tokenizer with a GPT-2 model (or any mismatched pair) runs without error but feeds the model meaningless IDs2.
zero-shot-classificationneedscandidate_labels; afill-maskprompt needs that model's own mask token1.ds.select(range(50)).shuffle()only reorders the first 50 rows;ds.shuffle(50)shuffles everything with seed 503.batched=Truespeeds upmap; it neither pads, nor saves memory, nor converts to tensors3.- A streamed
IterableDatasethas no random access, sods[0]does not give the first example; usenext(iter(ds))4. - Label padding must be β100, not the pad token ID6; the loss comes from the model when
labelsare given, not fromcompute_metrics5.
References
- Hugging Face LLM Course β Chapter 1.3 Transformers, what can they do?: Working with pipelines; Zero-shot classification; Mask filling; Named entity recognition
- Hugging Face LLM Course β Chapter 2.4 Tokenizers: Subword tokenization; Loading and saving; Encoding; Decoding
- Hugging Face LLM Course β Chapter 5.3 Time to slice and dice: Slicing and dicing our data; The map() method's superpowers
- Hugging Face LLM Course β Chapter 5.4 Big data? π€ Datasets to the rescue!: The magic of memory mapping; Streaming datasets
- Hugging Face LLM Course β Chapter 3.4 A full training loop: Prepare for training; The training loop; Supercharge your training loop with π€ Accelerate
- Hugging Face LLM Course β Chapter 7.4 Translation: Data collation; Metrics; Fine-tuning the model
- Hugging Face LLM Course β Chapter 4.1 The Hugging Face Hub (introduction)
- Hugging Face LLM Course β Chapter 4.4 Building a model card: introduction; Intended uses & limitations; Training data; Evaluation results