fine-tuning-expert
jeffallan/claude-skills
Expert guidance for fine-tuning LLMs with LoRA, QLoRA, and parameter-efficient methods.
What is fine-tuning-expert?
Specializes in adapting foundation models for specific tasks using parameter-efficient fine-tuning techniques. Use this skill when preparing datasets, configuring adapters, tuning hyperparameters, evaluating models, or deploying fine-tuned LLMs to production.
- Configure LoRA/QLoRA adapters with optimal rank and scaling factors
- Prepare and validate JSONL training datasets with quality checks
- Set hyperparameters (learning rates, batch sizes, schedulers) for stable training
- Monitor training/validation loss curves and detect overfitting
- Merge adapter weights and quantize models for deployment
- Benchmark fine-tuned models against base models on held-out test sets
How to install fine-tuning-expert
npx skills add https://github.com/jeffallan/claude-skills --skill fine-tuning-expert- Python 3.8+
- Hugging Face transformers and PEFT libraries
- PyTorch with CUDA support (or CPU for small models)
- Training dataset in JSONL format
How to use fine-tuning-expert
- 1.Validate your training dataset using the provided validation script to catch schema errors and token-length issues
- 2.Select a PEFT method: LoRA for most tasks, QLoRA for memory-constrained GPUs, full fine-tune only for small models
- 3.Configure LoRA rank, learning rate, batch size, and warmup ratio based on your model size and GPU memory
- 4.Run training with the provided SFTTrainer setup, monitoring loss curves at each checkpoint
- 5.Evaluate the fine-tuned model on a held-out test set, collecting perplexity and task-specific metrics
- 6.Merge adapter weights into the base model and quantize if needed, then benchmark inference latency
Use cases
- Fine-tune Llama or Mistral models on domain-specific instruction data using LoRA
- Adapt a 70B model on consumer GPUs using QLoRA 4-bit quantization
- Prepare Alpaca-style JSONL datasets with validation and deduplication
- Evaluate fine-tuned models with perplexity and task-specific metrics (BLEU/ROUGE)
- Merge LoRA adapters into base models and measure inference latency before serving
- ML engineers implementing LLM fine-tuning pipelines
- Data scientists adapting foundation models for custom tasks
- MLOps engineers deploying parameter-efficient models to production
- Researchers experimenting with instruction tuning, RLHF, or DPO
fine-tuning-expert FAQ
Use LoRA for most tasks on models >7B with sufficient GPU memory (24GB+). Use QLoRA (4-bit) when GPU memory is constrained (<24GB). Use full fine-tuning only for small models (<7B) or when maximum accuracy is critical and memory allows.
Start with rank=16 and lora_alpha=32 for most tasks. Increase rank (32, 64) if you have more GPU memory and need higher capacity; decrease to 8 if memory is tight. Monitor validation loss to find the sweet spot.
Track training and validation loss curves. If validation loss plateaus or increases while training loss continues to decrease, you are overfitting. Mitigate by reducing learning rate, increasing dropout, adding weight decay, or using early stopping.
No. Adapters are tied to their base model and rank configuration. Merging incompatible adapters will corrupt the model. Always merge an adapter into the exact base model it was trained on.
JSONL format with fields like 'instruction', 'input', and 'output' (Alpaca-style). Each line must be valid JSON. The skill includes validation scripts to check schema, detect duplicates, and analyze token lengths before training.
Full instructions (SKILL.md)
Source of truth, from jeffallan/claude-skills.
name: fine-tuning-expert description: "Use when fine-tuning LLMs, training custom models, or adapting foundation models for specific tasks. Invoke for configuring LoRA/QLoRA adapters, preparing JSONL training datasets, setting hyperparameters for fine-tuning runs, adapter training, transfer learning, finetuning with Hugging Face PEFT, OpenAI fine-tuning, instruction tuning, RLHF, DPO, or quantizing and deploying fine-tuned models. Trigger terms include: LoRA, QLoRA, PEFT, finetuning, fine-tuning, adapter tuning, LLM training, model training, custom model." license: MIT metadata: author: https://github.com/Jeffallan version: "1.1.0" domain: data-ml triggers: fine-tuning, fine tuning, finetuning, LoRA, QLoRA, PEFT, adapter tuning, transfer learning, model training, custom model, LLM training, instruction tuning, RLHF, model optimization, quantization role: expert scope: implementation output-format: code related-skills: devops-engineer
Fine-Tuning Expert
Senior ML engineer specializing in LLM fine-tuning, parameter-efficient methods, and production model optimization.
Core Workflow
- Dataset preparation — Validate and format data; run quality checks before training starts
- Checkpoint:
python validate_dataset.py --input data.jsonl— fix all errors before proceeding
- Checkpoint:
- Method selection — Choose PEFT technique based on GPU memory and task requirements
- Use LoRA for most tasks; QLoRA (4-bit) when GPU memory is constrained; full fine-tune only for small models
- Training — Configure hyperparameters, monitor loss curves, checkpoint regularly
- Checkpoint: validation loss must decrease; plateau or increase signals overfitting
- Evaluation — Benchmark against the base model; test on held-out set and edge cases
- Checkpoint: collect perplexity, task-specific metrics (BLEU/ROUGE), and latency numbers
- Deployment — Merge adapter weights, quantize, measure inference throughput before serving
Reference Guide
Load detailed guidance based on context:
| Topic | Reference | Load When |
|---|---|---|
| LoRA/PEFT | references/lora-peft.md | Parameter-efficient fine-tuning, adapters |
| Dataset Prep | references/dataset-preparation.md | Training data formatting, quality checks |
| Hyperparameters | references/hyperparameter-tuning.md | Learning rates, batch sizes, schedulers |
| Evaluation | references/evaluation-metrics.md | Benchmarking, metrics, model comparison |
| Deployment | references/deployment-optimization.md | Model merging, quantization, serving |
Minimal Working Example — LoRA Fine-Tuning with Hugging Face PEFT
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments
from peft import LoraConfig, get_peft_model, TaskType
from trl import SFTTrainer
import torch
# 1. Load base model and tokenizer
model_id = "meta-llama/Llama-3-8B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
)
# 2. Configure LoRA adapter
lora_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=16, # rank — increase for more capacity, decrease to save memory
lora_alpha=32, # scaling factor; typically 2× rank
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters() # verify: should be ~0.1–1% of total params
# 3. Load and format dataset (Alpaca-style JSONL)
dataset = load_dataset("json", data_files={"train": "train.jsonl", "test": "test.jsonl"})
def format_prompt(example):
return {"text": f"### Instruction:\n{example['instruction']}\n\n### Response:\n{example['output']}"}
dataset = dataset.map(format_prompt)
# 4. Training arguments
training_args = TrainingArguments(
output_dir="./checkpoints",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4, # effective batch size = 16
learning_rate=2e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.03, # always use warmup
fp16=False,
bf16=True,
logging_steps=10,
eval_strategy="steps",
eval_steps=100,
save_steps=200,
load_best_model_at_end=True,
)
# 5. Train
trainer = SFTTrainer(
model=model,
args=training_args,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
dataset_text_field="text",
max_seq_length=2048,
)
trainer.train()
# 6. Save adapter weights only
model.save_pretrained("./lora-adapter")
tokenizer.save_pretrained("./lora-adapter")
QLoRA variant — add these lines before loading the model to enable 4-bit quantization:
from transformers import BitsAndBytesConfig
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(model_id, quantization_config=bnb_config, device_map="auto")
Merge adapter into base model for deployment:
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16)
merged = PeftModel.from_pretrained(base, "./lora-adapter").merge_and_unload()
merged.save_pretrained("./merged-model")
Constraints
MUST DO
- Validate dataset quality before training
- Use parameter-efficient methods for large models (>7B)
- Monitor training/validation loss curves
- Document hyperparameters and training config
- Version datasets and model checkpoints
- Always include a learning rate warmup
MUST NOT DO
- Skip data quality validation
- Overfit on small datasets — use regularisation (dropout, weight decay) and early stopping
- Merge incompatible adapters (mismatched rank, base model, or target modules)
- Deploy without evaluation against a held-out set and latency benchmark
Output Templates
When implementing fine-tuning, always provide:
- Dataset preparation script with validation logic (schema checks, token-length histogram, deduplication)
- Training configuration (full
TrainingArguments+LoraConfigblock, commented) - Evaluation script reporting perplexity, task-specific metrics, and latency
- Brief design rationale — why this PEFT method, rank, and learning rate were chosen for this task
Related skills
More from jeffallan/claude-skills and the wider catalog.

flutter-expert
Senior Flutter engineer for cross-platform apps with Riverpod, Bloc, GoRouter, and performance optimization.

fullstack-guardian
Security-focused full-stack web development—frontend, backend, and database with integrated auth, validation, and output encoding.

game-developer
Build optimized game systems with ECS architecture, physics, networking, and performance targeting 60+ FPS.

golang-pro
Senior Go developer for concurrent systems, microservices, and production-grade performance optimization.

graphql-architect
Design scalable GraphQL schemas with Apollo Federation, resolvers, and real-time subscriptions.

java-architect
Enterprise Java specialist for Spring Boot 3.x, microservices, and cloud-native development with Java 21 LTS.