Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Build transformer fine-tuning plans for classification and generation
.claude/skills/brycewang-stanford-dl-transformer-finetune/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-08 | ✗→✓ | ▲ Improved | 72% | 0% |
| case-11 | ✗→✓ | ▲ Improved | 123% | 0% |
| case-14 | ✗→✓ | ▲ Improved | 78% | 0% |
| case-24 | ✗→✓ | ▲ Improved | 52% | 0% |
| case-03 | ✓→✓ | = Same ✓ | 107% | 0% |
Fine-tuning pretrained transformers is the dominant paradigm in modern NLP and increasingly in vision, audio, and multimodal research. The core idea is simple: take a model pretrained on massive data, then adapt it to your specific task with a comparatively small labeled dataset. But the practical details -- which layers to freeze, which optimizer and learning rate to use, how to handle catastrophic forgetting, when to use parameter-efficient methods -- determine whether fine-tuning succeeds or fails.
This guide covers the full spectrum of fine-tuning approaches: full fine-tuning for maximum performance, parameter-efficient fine-tuning (PEFT) for resource-constrained settings, and the decision framework for choosing between them. The patterns are drawn from hundreds of published papers and the Hugging Face ecosystem that supports them.
Whether you are fine-tuning BERT for text classification in a domain-specific corpus, adapting a large language model with LoRA for instruction following, or building a multi-task model for your research pipeline, this guide provides the recipes you need.
pythonfrom transformers import ( AutoModelForSequenceClassification, AutoTokenizer, TrainingArguments, Trainer, ) from datasets import load_dataset import numpy as np from sklearn.metrics import accuracy_score, f1_score # Load model and tokenizer model_name = "bert-base-uncased" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained( model_name, num_labels=3 ) # Prepare dataset dataset = load_dataset("multi_nli") def tokenize_function(examples): return tokenizer( examples["premise"], examples["hypothesis"], truncation=True, max_length=128, padding="max_length", ) tokenized = dataset.map(tokenize_function, batched=True) # Metrics def compute_metrics(eval_pred): logits, labels = eval_pred preds = np.argmax(logits, axis=-1) return { "accuracy": accuracy_score(labels, preds), "f1_macro": f1_score(labels, preds, average="macro"), } # Training arguments (research-grade defaults) training_args = TrainingArguments( output_dir="./results", num_train_epochs=3, per_device_train_batch_size=32, per_device_eval_batch_size=64, learning_rate=2e-5, # Standard for BERT fine-tuning weight_decay=0.01, warmup_ratio=0.06, # 6% warmup evaluation_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, metric_for_best_model="f1_macro", fp16=True, dataloader_num_workers=4, seed=42, report_to="wandb", ) trainer = Trainer( model=model, args=training_args, train_dataset=tokenized["train"], eval_dataset=tokenized["validation_matched"], compute_metrics=compute_metrics, ) trainer.train()
| Model Size | Recommended LR | Warmup | Weight Decay | |-----------|----------------|--------|--------------| | BERT-base (110M) | 2e-5 to 5e-5 | 6-10% | 0.01 | | BERT-large (340M) | 1e-5 to 3e-5 | 6-10% | 0.01 | | RoBERTa-large (355M) | 1e-5 to 2e-5 | 6% | 0.01 | | T5-base (220M) | 3e-4 to 1e-3 | 0-5% | 0.01 | | LLaMA-7B (full FT) | 1e-5 to 2e-5 | 3% | 0.0 | | LLaMA-7B (LoRA) | 1e-4 to 3e-4 | 3% | 0.0 |
LoRA freezes the pretrained weights and injects trainable low-rank decomposition matrices. It typically trains only 0.1-1% of parameters while achieving 95-100% of full fine-tuning performance.
pythonfrom peft import LoraConfig, get_peft_model, TaskType from transformers import AutoModelForCausalLM, AutoTokenizer # Load base model model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-2-7b-hf", torch_dtype=torch.bfloat16, device_map="auto", ) # Configure LoRA lora_config = LoraConfig( task_type=TaskType.CAUSAL_LM, r=16, # Rank (8-64 typical) lora_alpha=32, # Scaling factor (usually 2*r) lora_dropout=0.05, target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], bias="none", ) model = get_peft_model(model, lora_config) model.print_trainable_parameters() # Output: trainable params: 4,194,304 || all params: 6,742,609,920 || trainable%: 0.062
pythonfrom transformers import BitsAndBytesConfig # 4-bit quantization config bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, ) model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-2-7b-hf", quantization_config=bnb_config, device_map="auto", ) # Apply LoRA on top of quantized model model = get_peft_model(model, lora_config) # Now fits on a single 24GB GPU!
| Method | Trainable % | Memory | Performance | Best For | |--------|------------|--------|-------------|----------| | Full fine-tuning | 100% | High | Best | Sufficient compute + data | | LoRA | 0.1-1% | Low | 95-100% | Most scenarios | | QLoRA | 0.1-1% | Very low | 93-98% | Consumer GPUs | | Prefix tuning | ~0.1% | Low | 90-95% | Generation tasks | | Adapter layers | 1-5% | Medium | 95-99% | Multi-task | | Prompt tuning | <0.01% | Minimal | 85-95% | Large models, many tasks |
python# Strategy 1: Gradual unfreezing (Howard & Ruder, 2018) def gradual_unfreeze(model, epoch, total_layers=12): """Unfreeze one more layer group per epoch, from top to bottom.""" layers_to_unfreeze = min(epoch + 1, total_layers) for i, (name, param) in enumerate(reversed(list(model.named_parameters()))): param.requires_grad = i < layers_to_unfreeze * 10 # ~10 params per layer # Strategy 2: Discriminative learning rates def get_layer_lrs(model, base_lr=2e-5, decay_factor=0.95): """Apply lower learning rates to earlier layers.""" params = [] num_layers = 12 # BERT-base for i in range(num_layers): lr = base_lr * (decay_factor ** (num_layers - i - 1)) layer_params = [p for n, p in model.named_parameters() if f"layer.{i}." in n] params.append({"params": layer_params, "lr": lr}) return params # Strategy 3: EWC (Elastic Weight Consolidation) # Add a penalty term that keeps important weights close to pretrained values
Before fine-tuning:
[ ] Report exact pretrained model name and version
[ ] Document dataset size, splits, and preprocessing
[ ] Specify hardware (GPU model, count, precision)
[ ] Set random seeds (Python, NumPy, PyTorch, CUDA)
During fine-tuning:
[ ] Use validation set for hyperparameter selection
[ ] Log training curves (loss, metrics per epoch)
[ ] Monitor for overfitting (val loss divergence)
[ ] Try at least 3 learning rates from the recommended range
Reporting:
[ ] Report mean and std across 3-5 random seeds
[ ] Include training time and compute cost
[ ] Compare against published baselines using same evaluation
[ ] Release model weights or LoRA adapters for reproducibility| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→fail | 19,308 | 26,803 | +39% | 1 | 1 | 0% | 3,638 | 7,049 | +94% | 0 | 0 | — |
case-02 | fail→fail | 23,550 | 21,985 | -7% | 1 | 1 | 0% | 4,315 | 6,473 | +50% | 0 | 0 | — |
case-03 | pass→pass | 13,817 | 14,372 | +4% | 1 | 1 | 0% | 2,527 | 5,236 | +107% | 0 | 0 | — |
case-04 | pass→pass | 13,758 | 13,722 | -0% | 1 | 1 | 0% | 2,532 | 5,081 | +101% | 0 | 0 | — |
case-05 | fail→fail | 13,690 | 10,578 | -23% | 1 | 1 | 0% | 2,455 | 4,501 | +83% | 0 | 0 | — |
case-06 | pass→pass | 15,104 | 6,189 | -59% | 1 | 1 | 0% | 2,936 | 3,683 | +25% | 0 | 0 | — |
case-07 | pass→pass | 11,010 | 11,242 | +2% | 1 | 1 | 0% | 1,951 | 4,702 | +141% | 0 | 0 | — |
case-08 | fail→pass | 15,001 | 9,037 | -40% | 1 | 1 | 0% | 2,352 | 4,049 | +72% | 0 | 0 | — |
case-09 | fail→fail | 17,771 | 16,494 | -7% | 1 | 1 | 0% | 3,065 | 5,284 | +72% | 0 | 0 | — |
case-10 | pass→pass | 16,078 | 16,789 | +4% | 1 | 1 | 0% | 3,126 | 5,825 | +86% | 0 | 0 | — |
case-23 | pass→pass | 19,475 | 26,820 | +38% | 1 | 1 | 0% | 3,819 | 6,875 | +80% | 0 | 0 | — |
case-11 | fail→pass | 14,275 | 14,362 | +1% | 1 | 1 | 0% | 2,255 | 5,038 | +123% | 0 | 0 | — |
case-12 | pass→pass | 19,759 | 17,900 | -9% | 1 | 1 | 0% | 3,285 | 5,516 | +68% | 0 | 0 | — |
case-13 | pass→pass | 17,271 | 20,090 | +16% | 1 | 1 | 0% | 2,889 | 5,896 | +104% | 0 | 0 | — |
case-14 | fail→pass | 18,576 | 20,336 | +9% | 1 | 1 | 0% | 3,687 | 6,581 | +78% | 0 | 0 | — |
case-24 | fail→pass | 24,044 | 22,337 | -7% | 1 | 1 | 0% | 4,384 | 6,678 | +52% | 0 | 0 | — |
case-15 | pass→pass | 20,272 | 25,456 | +26% | 1 | 1 | 0% | 3,360 | 7,058 | +110% | 0 | 0 | — |
case-16 | pass→pass | 16,414 | 17,604 | +7% | 1 | 1 | 0% | 2,810 | 5,590 | +99% | 0 | 0 | — |
case-17 | pass→pass | 9,208 | 2,340 | -75% | 1 | 1 | 0% | 1,576 | 2,882 | +83% | 0 | 0 | — |
case-18 | pass→pass | 7,498 | 8,938 | +19% | 1 | 1 | 0% | 1,467 | 4,229 | +188% | 0 | 0 | — |
case-19 | pass→pass | 10,826 | 12,165 | +12% | 1 | 1 | 0% | 2,016 | 4,767 | +136% | 0 | 0 | — |
case-20 | pass→pass | 10,999 | 8,624 | -22% | 1 | 1 | 0% | 2,149 | 4,209 | +96% | 0 | 0 | — |
case-21 | fail→fail | 12,531 | 10,101 | -19% | 1 | 1 | 0% | 2,458 | 4,480 | +82% | 0 | 0 | — |
case-22 | pass→pass | 19,374 | 22,210 | +15% | 1 | 1 | 0% | 3,401 | 6,723 | +98% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 24 cases were attempted. The headline lift of +17 percentage points is the difference between those two pass rates over the 24 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.