Skill — Fine-Tuning Workflow
When this skill activates
Any task involving LLM fine-tuning, training dataset preparation, LoRA/QLoRA
adaptation, model evaluation during training, or model deployment with A/B testing.
Mandatory actions when this skill is active
Before writing any code
- Define the fine-tuning objective (style adaptation, domain knowledge, task specialization).
- Audit training data quality (deduplication, format consistency, bias check).
- Establish baseline metrics with the un-tuned model.
During implementation
- Run evaluation on held-out validation set at regular intervals during training.
- Implement early stopping on quality degradation.
- Track training metrics: loss, eval metrics, learning rate schedule.
After implementation
- Compare fine-tuned model against baseline on the eval suite.
- Deploy with canary traffic (shadow or A/B testing).
- Document the model card with training details and performance.
Dataset Preparation
Data Requirements by Objective
| Objective |
Min Examples |
Quality Requirement |
| Style/tone adaptation |
100-500 |
High quality exemplars of target style |
| Domain knowledge |
1,000-10,000 |
Accurate, diverse domain Q&A pairs |
| Task specialization |
500-5,000 |
Varied task examples with edge cases |
| Instruction following |
1,000+ |
Diverse instruction/response pairs |
Data Format (Instruction Tuning)
{"messages": [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Write a function to reverse a string in Python."},
{"role": "assistant", "content": "def reverse_string(s: str) -> str:\n return s[::-1]"}
]}
Data Quality Checklist
Data Cleaning Pipeline
- Deduplication: hash-based exact dedup + embedding-based semantic dedup.
- Format validation: ensure all examples match expected schema.
- Quality filtering: remove low-quality examples (too short, incoherent).
- Balance check: verify distribution across categories.
- Contamination check: ensure eval data not in training set.
Training Approaches
Full Fine-Tuning
- Updates all model parameters.
- Use for: significant behavior changes, large datasets.
- Cost: high (full model in GPU memory, long training time).
- Risk: catastrophic forgetting of base model capabilities.
LoRA (Low-Rank Adaptation)
- Adds small trainable matrices alongside frozen base model.
- Use for: most fine-tuning tasks (efficient, less forgetting).
- Cost: low (only adapter weights in GPU memory).
- Benefit: merge adapter with base model for zero-overhead inference.
QLoRA (Quantized LoRA)
- Base model quantized to 4-bit, LoRA adapters in 16-bit.
- Use for: large models on limited GPU memory.
- Cost: very low (fits 70B model on single GPU for training).
- Trade-off: slight quality reduction from quantization.
Key Hyperparameters
| Parameter |
Typical Range |
Notes |
| Learning rate |
1e-5 to 5e-5 |
Lower for larger models |
| Batch size |
4-32 |
Larger = more stable, needs more memory |
| Epochs |
1-5 |
More epochs risk overfitting |
| LoRA rank |
8-64 |
Higher = more capacity, more compute |
| LoRA alpha |
16-128 |
Usually 2x rank |
| Warmup steps |
5-10% of total |
Prevents early divergence |
Evaluation During Training
Validation Set
- Hold out 10-20% of data as validation (never train on it).
- Evaluate every N steps (e.g., every 100 steps or every epoch).
- Track: validation loss, task-specific metrics.
Early Stopping
- Stop training if validation metric doesn't improve for N evaluations.
- Prevents overfitting (model memorizes training data).
- Save checkpoint at best validation score, not last step.
Evaluation Metrics
| Metric |
Use Case |
What It Measures |
| Perplexity |
General quality |
Model confidence on held-out data |
| ROUGE-L |
Summarization |
Overlap with reference summaries |
| Exact Match |
Q&A, classification |
Correct answer percentage |
| Human preference |
Style/quality |
A/B comparison by annotators |
| Task-specific |
Custom tasks |
Domain-specific correctness |
Model Deployment
Deployment Pipeline
Train → Evaluate → Register → Shadow Test → Canary → Full Rollout
Model Registry
- Version every model with: training data hash, hyperparameters, eval scores.
- Store model artifacts in versioned storage (S3, GCS, MLflow).
- Link to training run for full reproducibility.
Shadow Traffic Testing
- Deploy new model alongside production model.
- Route production traffic to both (only serve old model's response).
- Compare outputs offline (quality, latency, error rate).
- Promote to canary only if shadow results are satisfactory.
Canary Rollout
- Route 5% of traffic to new model.
- Monitor: quality metrics, latency p99, error rate, user feedback.
- If metrics are good after 24-48 hours: increase to 25% → 50% → 100%.
- Rollback instantly if any metric degrades.
A/B Testing
Experiment Design
- Split users randomly (not requests — same user should see same model).
- Define primary metric (quality score, user satisfaction, task completion).
- Define guardrail metrics (latency, error rate, cost).
- Run for statistical significance (typically 1-2 weeks).
Analysis
- Compare primary metric between control (old model) and treatment (new model).
- Verify guardrail metrics haven't degraded.
- Check for segment effects (does new model help some users but hurt others?).
- Document results and decision in model card.
Model Versioning (Model Card)
model_card:
name: customer-support-assistant-v3
base_model: llama-3-8b
adapter: LoRA (rank 32)
training_data:
source: customer_support_conversations_2024
examples: 5,432
hash: sha256:def456...
hyperparameters:
learning_rate: 2e-5
epochs: 3
batch_size: 16
lora_rank: 32
evaluation:
held_out_accuracy: 0.89
human_preference_win_rate: 0.72
latency_p99_ms: 340
deployed_at: 2024-01-20
parent_version: customer-support-assistant-v2
Self-check before task completion
Before marking a task done when this skill was active:
1---2name: fine-tuning-workflow3description: Skill — Fine-Tuning Workflow4---56# Skill — Fine-Tuning Workflow78## When this skill activates9Any task involving LLM fine-tuning, training dataset preparation, LoRA/QLoRA10adaptation, model evaluation during training, or model deployment with A/B testing.1112## Mandatory actions when this skill is active1314### Before writing any code151. Define the fine-tuning objective (style adaptation, domain knowledge, task specialization).162. Audit training data quality (deduplication, format consistency, bias check).173. Establish baseline metrics with the un-tuned model.1819### During implementation20- Run evaluation on held-out validation set at regular intervals during training.21- Implement early stopping on quality degradation.22- Track training metrics: loss, eval metrics, learning rate schedule.2324### After implementation25- Compare fine-tuned model against baseline on the eval suite.26- Deploy with canary traffic (shadow or A/B testing).27- Document the model card with training details and performance.2829## Dataset Preparation3031### Data Requirements by Objective32| Objective | Min Examples | Quality Requirement |33|-----------|-------------|-------------------|34| Style/tone adaptation | 100-500 | High quality exemplars of target style |35| Domain knowledge | 1,000-10,000 | Accurate, diverse domain Q&A pairs |36| Task specialization | 500-5,000 | Varied task examples with edge cases |37| Instruction following | 1,000+ | Diverse instruction/response pairs |3839### Data Format (Instruction Tuning)40```jsonl41{"messages": [42 {"role": "system", "content": "You are a helpful coding assistant."},43 {"role": "user", "content": "Write a function to reverse a string in Python."},44 {"role": "assistant", "content": "def reverse_string(s: str) -> str:\n return s[::-1]"}45]}46```4748### Data Quality Checklist49- [ ] Deduplicated (no exact or near-duplicate examples).50- [ ] Consistent format across all examples.51- [ ] Balanced across categories/topics.52- [ ] No PII or sensitive data (unless intentional and consented).53- [ ] Correct and high-quality responses (garbage in = garbage out).54- [ ] Diverse inputs (length, complexity, edge cases).5556### Data Cleaning Pipeline571. **Deduplication**: hash-based exact dedup + embedding-based semantic dedup.582. **Format validation**: ensure all examples match expected schema.593. **Quality filtering**: remove low-quality examples (too short, incoherent).604. **Balance check**: verify distribution across categories.615. **Contamination check**: ensure eval data not in training set.6263## Training Approaches6465### Full Fine-Tuning66- Updates all model parameters.67- Use for: significant behavior changes, large datasets.68- Cost: high (full model in GPU memory, long training time).69- Risk: catastrophic forgetting of base model capabilities.7071### LoRA (Low-Rank Adaptation)72- Adds small trainable matrices alongside frozen base model.73- Use for: most fine-tuning tasks (efficient, less forgetting).74- Cost: low (only adapter weights in GPU memory).75- Benefit: merge adapter with base model for zero-overhead inference.7677### QLoRA (Quantized LoRA)78- Base model quantized to 4-bit, LoRA adapters in 16-bit.79- Use for: large models on limited GPU memory.80- Cost: very low (fits 70B model on single GPU for training).81- Trade-off: slight quality reduction from quantization.8283### Key Hyperparameters84| Parameter | Typical Range | Notes |85|-----------|--------------|-------|86| Learning rate | 1e-5 to 5e-5 | Lower for larger models |87| Batch size | 4-32 | Larger = more stable, needs more memory |88| Epochs | 1-5 | More epochs risk overfitting |89| LoRA rank | 8-64 | Higher = more capacity, more compute |90| LoRA alpha | 16-128 | Usually 2x rank |91| Warmup steps | 5-10% of total | Prevents early divergence |9293## Evaluation During Training9495### Validation Set96- Hold out 10-20% of data as validation (never train on it).97- Evaluate every N steps (e.g., every 100 steps or every epoch).98- Track: validation loss, task-specific metrics.99100### Early Stopping101- Stop training if validation metric doesn't improve for N evaluations.102- Prevents overfitting (model memorizes training data).103- Save checkpoint at best validation score, not last step.104105### Evaluation Metrics106| Metric | Use Case | What It Measures |107|--------|----------|-----------------|108| Perplexity | General quality | Model confidence on held-out data |109| ROUGE-L | Summarization | Overlap with reference summaries |110| Exact Match | Q&A, classification | Correct answer percentage |111| Human preference | Style/quality | A/B comparison by annotators |112| Task-specific | Custom tasks | Domain-specific correctness |113114## Model Deployment115116### Deployment Pipeline117```118Train → Evaluate → Register → Shadow Test → Canary → Full Rollout119```120121### Model Registry122- Version every model with: training data hash, hyperparameters, eval scores.123- Store model artifacts in versioned storage (S3, GCS, MLflow).124- Link to training run for full reproducibility.125126### Shadow Traffic Testing127- Deploy new model alongside production model.128- Route production traffic to both (only serve old model's response).129- Compare outputs offline (quality, latency, error rate).130- Promote to canary only if shadow results are satisfactory.131132### Canary Rollout133- Route 5% of traffic to new model.134- Monitor: quality metrics, latency p99, error rate, user feedback.135- If metrics are good after 24-48 hours: increase to 25% → 50% → 100%.136- Rollback instantly if any metric degrades.137138## A/B Testing139140### Experiment Design141- Split users randomly (not requests — same user should see same model).142- Define primary metric (quality score, user satisfaction, task completion).143- Define guardrail metrics (latency, error rate, cost).144- Run for statistical significance (typically 1-2 weeks).145146### Analysis147- Compare primary metric between control (old model) and treatment (new model).148- Verify guardrail metrics haven't degraded.149- Check for segment effects (does new model help some users but hurt others?).150- Document results and decision in model card.151152## Model Versioning (Model Card)153154```yaml155model_card:156 name: customer-support-assistant-v3157 base_model: llama-3-8b158 adapter: LoRA (rank 32)159 training_data:160 source: customer_support_conversations_2024161 examples: 5,432162 hash: sha256:def456...163 hyperparameters:164 learning_rate: 2e-5165 epochs: 3166 batch_size: 16167 lora_rank: 32168 evaluation:169 held_out_accuracy: 0.89170 human_preference_win_rate: 0.72171 latency_p99_ms: 340172 deployed_at: 2024-01-20173 parent_version: customer-support-assistant-v2174```175176## Self-check before task completion177178Before marking a task done when this skill was active:179180- [ ] Did I read the full SKILL.md before starting? (Not just the triggers)181- [ ] Is training data deduplicated, validated, and quality-checked?182- [ ] Is evaluation running on held-out validation set during training?183- [ ] Is early stopping configured to prevent overfitting?184- [ ] Are baseline metrics established for comparison?185- [ ] Is the model versioned with full training lineage?186- [ ] Is deployment using canary/A/B testing (not instant full rollout)?