Skip to content
ml-recall

Topic notes

Hugging Face Ecosystem

Hugging Face in practice β€” pipelines, tokenizers and Auto classes, the Hub and model cards, πŸ€— Datasets (map, slicing, memory mapping, streaming), and training with Trainer and Accelerate.

4-min read AI-checked

Practise 30 questions Take a test

Key ideas

Formulas

Worked example

Token logits (2,0)(2, 0), (0,2)(0, 2), (1,1)(1, 1) over a 2-word vocabulary, labels (0,βˆ’100,1)(0, -100, 1):

The loss is (0.127+0.693)/2β‰ˆ0.41(0.127 + 0.693)/2 \approx 0.41, 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

References

  1. Hugging Face LLM Course β€” Chapter 1.3 Transformers, what can they do?: Working with pipelines; Zero-shot classification; Mask filling; Named entity recognition
  2. Hugging Face LLM Course β€” Chapter 2.4 Tokenizers: Subword tokenization; Loading and saving; Encoding; Decoding
  3. Hugging Face LLM Course β€” Chapter 5.3 Time to slice and dice: Slicing and dicing our data; The map() method's superpowers
  4. Hugging Face LLM Course β€” Chapter 5.4 Big data? πŸ€— Datasets to the rescue!: The magic of memory mapping; Streaming datasets
  5. Hugging Face LLM Course β€” Chapter 3.4 A full training loop: Prepare for training; The training loop; Supercharge your training loop with πŸ€— Accelerate
  6. Hugging Face LLM Course β€” Chapter 7.4 Translation: Data collation; Metrics; Fine-tuning the model
  7. Hugging Face LLM Course β€” Chapter 4.1 The Hugging Face Hub (introduction)
  8. Hugging Face LLM Course β€” Chapter 4.4 Building a model card: introduction; Intended uses & limitations; Training data; Evaluation results