{"data":{"slug":"discovered-3d755638f0a3d2f30da6c4f5c5d6cf0da77322c386e5e517","title":"Fine Tuning Expert","summary":"Configure LoRA\/QLoRA adapters, prepare JSONL training datasets, set hyperparameters for fine-tuning runs, and deploy fine-tuned models. Deliverables include dataset preparation scripts, training configurations, evaluation scripts, and design rationales.","url":"https:\/\/skillshunter.net\/skills\/discovered-3d755638f0a3d2f30da6c4f5c5d6cf0da77322c386e5e517","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-3d755638f0a3d2f30da6c4f5c5d6cf0da77322c386e5e517","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-3d755638f0a3d2f30da6c4f5c5d6cf0da77322c386e5e517.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-3d755638f0a3d2f30da6c4f5c5d6cf0da77322c386e5e517\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before starting, validate dataset quality and run the dataset preparation script with validation logic (schema checks, token-length histogram, deduplication). Choose a PEFT technique based on GPU memory and task requirements \u2014 use LoRA for most tasks, QLoRA (4-bit) when GPU memory is constrained, and full fine-tune only for small models.","instructions":"---\nname: fine-tuning-expert\ndescription: \"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.\"\nlicense: MIT\nmetadata:\n  author: https:\/\/github.com\/Jeffallan\n  company: https:\/\/synergetic.solutions\n  version: \"1.1.0\"\n  domain: data-ml\n  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\n  role: expert\n  scope: implementation\n  output-format: code\n  related-skills: devops-engineer\n---\n\n# Fine-Tuning Expert\n\nSenior ML engineer specializing in LLM fine-tuning, parameter-efficient methods, and production model optimization.\n\n## Core Workflow\n\n1. **Dataset preparation** \u2014 Validate and format data; run quality checks before training starts\n   - Checkpoint: `python validate_dataset.py --input data.jsonl` \u2014 fix all errors before proceeding\n2. **Method selection** \u2014 Choose PEFT technique based on GPU memory and task requirements\n   - Use LoRA for most tasks; QLoRA (4-bit) when GPU memory is constrained; full fine-tune only for small models\n3. **Training** \u2014 Configure hyperparameters, monitor loss curves, checkpoint regularly\n   - Checkpoint: validation loss must decrease; plateau or increase signals overfitting\n4. **Evaluation** \u2014 Benchmark against the base model; test on held-out set and edge cases\n   - Checkpoint: collect perplexity, task-specific metrics (BLEU\/ROUGE), and latency numbers\n5. **Deployment** \u2014 Merge adapter weights, quantize, measure inference throughput before serving\n\n## Reference Guide\n\nLoad detailed guidance based on context:\n\n| Topic | Reference | Load When |\n|-------|-----------|-----------|\n| LoRA\/PEFT | `references\/lora-peft.md` | Parameter-efficient fine-tuning, adapters |\n| Dataset Prep | `references\/dataset-preparation.md` | Training data formatting, quality checks |\n| Hyperparameters | `references\/hyperparameter-tuning.md` | Learning rates, batch sizes, schedulers |\n| Evaluation | `references\/evaluation-metrics.md` | Benchmarking, metrics, model comparison |\n| Deployment | `references\/deployment-optimization.md` | Model merging, quantization, serving |\n\n## Minimal Working Example \u2014 LoRA Fine-Tuning with Hugging Face PEFT\n\n```python\nfrom datasets import load_dataset\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments\nfrom peft import LoraConfig, get_peft_model, TaskType\nfrom trl import SFTTrainer\nimport torch\n\n# 1. Load base model and tokenizer\nmodel_id = \"meta-llama\/Llama-3-8B\"\ntokenizer = AutoTokenizer.from_pretrained(model_id)\ntokenizer.pad_token = tokenizer.eos_token\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    torch_dtype=torch.bfloat16,\n    device_map=\"auto\",\n)\n\n# 2. Configure LoRA adapter\nlora_config = LoraConfig(\n    task_type=TaskType.CAUSAL_LM,\n    r=16,               # rank \u2014 increase for more capacity, decrease to save memory\n    lora_alpha=32,      # scaling factor; typically 2\u00d7 rank\n    target_modules=[\"q_proj\", \"v_proj\"],\n    lora_dropout=0.05,\n    bias=\"none\",\n)\nmodel = get_peft_model(model, lora_config)\nmodel.print_trainable_parameters()  # verify: should be ~0.1\u20131% of total params\n\n# 3. Load and format dataset (Alpaca-style JSONL)\ndataset = load_dataset(\"json\", data_files={\"train\": \"train.jsonl\", \"test\": \"test.jsonl\"})\n\ndef format_prompt(example):\n    return {\"text\": f\"### Instruction:\\n{example['instruction']}\\n\\n### Response:\\n{example['output']}\"}\n\ndataset = dataset.map(format_prompt)\n\n# 4. Training arguments\ntraining_args = TrainingArguments(\n    output_dir=\".\/checkpoints\",\n    num_train_epochs=3,\n    per_device_train_batch_size=4,\n    gradient_accumulation_steps=4,     # effective batch size = 16\n    learning_rate=2e-4,\n    lr_scheduler_type=\"cosine\",\n    warmup_ratio=0.03,                 # always use warmup\n    fp16=False,\n    bf16=True,\n    logging_steps=10,\n    eval_strategy=\"steps\",\n    eval_steps=100,\n    save_steps=200,\n    load_best_model_at_end=True,\n)\n\n# 5. Train\ntrainer = SFTTrainer(\n    model=model,\n    args=training_args,\n    train_dataset=dataset[\"train\"],\n    eval_dataset=dataset[\"test\"],\n    dataset_text_field=\"text\",\n    max_seq_length=2048,\n)\ntrainer.train()\n\n# 6. Save adapter weights only\nmodel.save_pretrained(\".\/lora-adapter\")\ntokenizer.save_pretrained(\".\/lora-adapter\")\n```\n\n**QLoRA variant** \u2014 add these lines before loading the model to enable 4-bit quantization:\n```python\nfrom transformers import BitsAndBytesConfig\n\nbnb_config = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_quant_type=\"nf4\",\n    bnb_4bit_compute_dtype=torch.bfloat16,\n    bnb_4bit_use_double_quant=True,\n)\nmodel = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config, device_map=\"auto\")\n```\n\n**Merge adapter into base model for deployment:**\n```python\nfrom peft import PeftModel\n\nbase = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16)\nmerged = PeftModel.from_pretrained(base, \".\/lora-adapter\").merge_and_unload()\nmerged.save_pretrained(\".\/merged-model\")\n```\n\n## Constraints\n\n### MUST DO\n- Validate dataset quality before training\n- Use parameter-efficient methods for large models (>7B)\n- Monitor training\/validation loss curves\n- Document hyperparameters and training config\n- Version datasets and model checkpoints\n- Always include a learning rate warmup\n\n### MUST NOT DO\n- Skip data quality validation\n- Overfit on small datasets \u2014 use regularisation (dropout, weight decay) and early stopping\n- Merge incompatible adapters (mismatched rank, base model, or target modules)\n- Deploy without evaluation against a held-out set and latency benchmark\n\n## Output Templates\n\nWhen implementing fine-tuning, always provide:\n1. **Dataset preparation script** with validation logic (schema checks, token-length histogram, deduplication)\n2. **Training configuration** (full `TrainingArguments` + `LoraConfig` block, commented)\n3. **Evaluation script** reporting perplexity, task-specific metrics, and latency\n4. **Brief design rationale** \u2014 why this PEFT method, rank, and learning rate were chosen for this task\n\nMaintained by [@jeffallan](https:\/\/github.com\/jeffallan), Principal Consultant at [Synergetic Solutions](https:\/\/synergetic.solutions)\n\n[Documentation](https:\/\/jeffallan.github.io\/claude-skills\/skills\/data-ml\/fine-tuning-expert\/)\n","use_cases":["Configuring LoRA\/QLoRA adapters for large language models","Preparing JSONL training datasets with quality checks","Setting hyperparameters for fine-tuning runs","Evaluating fine-tuned models with perplexity and task-specific metrics","Deploying fine-tuned models with quantization and latency benchmarks"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/Jeffallan\/claude-skills\/blob\/a8be463010e2ca23afe00ea00773aea7128e8971\/plugin\/skills\/fine-tuning-expert\/SKILL.md","source_commit":"a8be463010e2ca23afe00ea00773aea7128e8971","license":null,"version":null,"listing_approved_at":"2026-11-29","created_at":"2026-11-28T18:47:04.000000Z","updated_at":"2026-11-29T10:53:15.000000Z","seo_title":"Fine Tuning Expert - Configure LoRA\/QLoRA Adapters, Prepare Datasets,","seo_description":"Configure LoRA\/QLoRA adapters, prepare JSONL training datasets, set hyperparameters for fine-tuning runs, and deploy fine-tuned models. Deliverables include dataset prep,","seo_keywords":["LoRA","QLoRA","PEFT","fine-tuning","adapter tuning","LLM training","model training","custom model"]}}