Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.The toolbox for open language models
Hugging Face is like a shared workshop: a library of ready-made models and datasets, plus tools to load them, feed them data and adapt them to your task. Most of the work in practice is plumbing: getting text into the right format, batching it efficiently and making it fit in memory. One easy win is not to fill batches with blank padding. The demo shows how much of a batch is padding.
Teams fine-tune open models on maintenance logs or mission reports with transformers, PEFT and TRL on a single GPU.
- 1. The Hugging Face Hub hosts…
- 2. PEFT is for…
- 3. Padding wastes…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- transformers: AutoTokenizer, AutoModelForCausalLM, pipeline; device_map=“auto”, torch_dtype, attn_implementation (sdpa, flash_attention_2); generate with GenerationConfig; quantised loading via bitsandbytes.
- tokenizers: fast Rust tokenizers; apply_chat_template formats conversations exactly as the model was trained.
- datasets: load_dataset, Arrow memory mapping, map with batched=True and num_proc, streaming for large corpora.
- accelerate: one script for CPU, multi-GPU, DeepSpeed and FSDP; mixed precision and gradient accumulation.
- PEFT: LoraConfig (r, alpha, target_modules), QLoRA with 4-bit base models, adapters merged or swapped at inference.
- TRL: SFTTrainer (completion-only loss, packing), DPOTrainer, GRPOTrainer, RewardTrainer.
- Efficiency: dynamic padding, group_by_length, packing with position_ids or varlen attention, gradient checkpointing.
- Silent errors: wrong chat template, missing pad token, padding side for generation, loss on prompt tokens, tokenizer–model mismatch.
- 1. Format chat data with…
- 2. Multi-GPU training with one script:
- 3. A common silent error:
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Fine-tuning with the stack
Exercise 1.
- A collator with dynamic padding and attention masks.
- Masking prompt tokens out of the loss.
- Counting LoRA parameters.
Practice.
- Start from a strong instruct model; format with its chat template; check a decoded batch by eye.
- Use LoRA or QLoRA first; target all linear layers; r between 8 and 64.
- Enable group_by_length or packing with correct position ids; use bf16 and gradient checkpointing.
- Track runs with report_to (wandb, tensorboard); evaluate with your custom eval (F14-5).
- Push adapters to the Hub privately; merge for serving with vLLM.
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct", torch_dtype="bfloat16")
ds = load_dataset("json", data_files="maintenance_chats.jsonl")["train"]
cfg = SFTConfig(output_dir="out", per_device_train_batch_size=8, gradient_accumulation_steps=4, bf16=True,
packing=True, padding_free=True, completion_only_loss=True, num_train_epochs=2)
SFTTrainer(model=model, args=cfg, train_dataset=ds, processing_class=tok,
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear")).train()- 1. A typical LoRA rank range:
- 2. Check training data by…
- 3. Serve merged adapters with…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Padding cost. With batch-level padding, each batch costs B · max length. For long-tailed lengths, almost every random batch of 16 contains a long example, so dynamic padding still pays for the tail; sorting by length makes batches homogeneous.
Packing and attention. Packing concatenates examples into full rows. With a plain causal mask, tokens attend to earlier examples in the row: the model sees unrelated context and attention cost grows with the row length squared rather than the sum of squared example lengths. Passing position ids or cumulative sequence lengths lets varlen attention kernels keep examples separate.
Memory. Weights take params × bytes; mixed-precision Adam needs about 16 bytes per trained parameter; LoRA trains r(d_out + d_in) parameters per adapted matrix, so optimizer memory almost vanishes.
- 1. Dynamic padding still wastes compute when lengths are…
- 2. Packing with a plain causal mask lets examples…
- 3. Mixed-precision Adam needs about…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How much compute do common batching strategies waste on padding, and what does packing cost?
History.
- T. Wolf et al., “Transformers: state-of-the-art natural language processing” (2020).
- Q. Lhoest et al., “Datasets: a community library for natural language processing” (2021).
- M. Krell et al., “Efficient sequence packing without cross-contamination” (2021).
Exercise 2. 20000 training examples.
- Lengths: log-normal with median 200 tokens and a long tail, clipped to 8–2048 (mean 296).
- Batching: batches of 16; strategies are padding to 2048, dynamic padding in random order, length grouping (sort within groups of 50 batches), greedy packing into 2048-token rows, and concatenate-and-chunk.
- Measures: padding share of token slots; for packing, the share of causal attention pairs that cross example boundaries and attention compute relative to per-example attention.
| strategy | padding share | notes |
|---|---|---|
| pad to 2048 | 0.856 | – |
| dynamic padding | 0.717 | – |
| grouped by length | 0.064 | – |
| greedy packing | 0.141 | 67% of attention pairs cross examples; 3.03× attention compute |
| concatenate and chunk | 0.0 | 14.4% of examples split across rows |
- Dynamic padding alone helped little: most random batches contain one long example.
- Length grouping removed nearly all padding, more than tripling useful throughput.
- Packing removed most padding but, without separate masks, mixed examples and tripled attention compute; concatenate-and-chunk wastes nothing but cuts examples.
- Seeds 1 and 2 agreed within 0.005 on every share (attention compute 3.05 and 3.02).
- Caveat: compute modelled as token slots and attention pairs; real speedups depend on kernels and memory.
The Hugging Face stack in AI, robotics and aerospace
- Domain fine-tuning: LoRA adapters on open models for technical documents, trained on one GPU and served with vLLM.
- Robotics: LeRobot builds on the same Hub and datasets tooling for robot learning data and policies.
- On-premise use: models and datasets mirrored internally for export-controlled or sensitive data.
References
- T. Wolf et al. (2020). “Transformers: state-of-the-art natural language processing.” EMNLP Demos.
- Q. Lhoest et al. (2021). “Datasets: a community library for natural language processing.” EMNLP Demos.
- M. Krell, M. Kosec, S. Perez and A. Fitzgibbon (2021). “Efficient sequence packing without cross-contamination.” arXiv.
- T. Dettmers et al. (2023). “QLoRA: efficient finetuning of quantized LLMs.” NeurIPS.