Fine tuning strategy

From FerroxLabs/wayland · View interactive version

Fine tuning strategy is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level fine-tuning strategy implementation: ai-ml and optimization decision frameworks, production-ready patterns, and concrete templates for fine tuning strategy workflows. Use when the user asks about fine-tuning strategy, fine tuning strategy configuration, or ai-ml best practices fo

How to use this skill

Skill file

Fine Tuning Strategy

When to Use

Use this skill when:

Do NOT use this skill when:


Process

Step 1: Determine Whether Fine-Tuning Is the Right Tool

Before touching any training infrastructure, validate that fine-tuning is actually justified.

Step 2: Select the Fine-Tuning Method

The choice of fine-tuning method determines compute cost, catastrophic forgetting risk, and deployment complexity.

Step 3: Design and Curate the Training Dataset

Dataset quality is the single most important variable in fine-tuning success -- more important than architecture choices, hyperparameters, or model size.

Step 4: Configure the Training Hyperparameters

Hyperparameter choices interact strongly with dataset size and model scale. Use these calibrated defaults as starting points.

Step 5: Execute Training with Proper Observability

Running training without systematic monitoring produces uninterpretable results and wasted compute.

Step 6: Evaluate the Fine-Tuned Model

Evaluation is where most fine-tuning projects fail -- they measure the wrong things or measure too little.

Step 7: Iterate, Merge, and Deploy

Fine-tuning is not a one-shot process -- structure your iteration cycle to converge efficiently.


Output Format

Fine-Tuning Strategy Decision Report

╔═══════════════════════════════════════════════════════════╗
║           FINE-TUNING STRATEGY ASSESSMENT                 ║
╚═══════════════════════════════════════════════════════════╝

PROJECT: [Name/Description]
DATE: [Date]
ANALYST: [AI Assistant]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SECTION 1: FINE-TUNING JUSTIFICATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Task Type:              [classification | extraction | generation | instruction-following]
Baseline Method Tried:  [prompt-engineering | RAG | few-shot | none]
Baseline Quality Score: [X%] on [metric] with [N] examples
Target Quality Score:   [X%]
Gap:                    [X%] -- [justifies / does not justify] fine-tuning

Primary Failure Mode:   [format | knowledge | reasoning | style]
Fine-Tuning Addressable: [YES / NO / PARTIALLY]

Decision: [PROCEED WITH FINE-TUNING / USE ALTERNATIVE APPROACH]
Rationale: [2--3 sentences]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SECTION 2: METHOD SELECTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Base Model:             [model name and parameter count]
Fine-Tuning Method:     [LoRA | QLoRA | DoRA | Full Fine-Tune]
Justification:          [compute constraint | data size | quality requirement]

LoRA Configuration (if applicable):
  rank (r):             [8 | 16 | 32 | 64]
  alpha:                [16 | 32 | 64 | 128]
  dropout:              [0.0 | 0.05 | 0.1]
  target_modules:       [q_proj, v_proj | all linear layers]

Hardware Requirement:   [GPU type and count]
Estimated Training Time:[X hours]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SECTION 3: DATASET PLAN
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Collection Strategy:    [human-labeled | GPT-4 distillation | log mining | synthetic]
Target Dataset Size:    [N examples total]
  Train split:          [N examples]
  Validation split:     [N examples]
  Test split:           [N examples]

Input Format:           [describe the prompt template]
Output Format:          [describe the expected completion format]
Quality Filter Method:  [LLM judge | human review | rule-based filter]
Deduplication Method:   [MinHash | SHA-256 | none]

Known Data Risks:       [imbalance | noise | PII | terms of service]
Mitigation:             [specific mitigation steps]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SECTION 4: TRAINING CONFIGURATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

| Hyperparameter          | Value          | Rationale                        |
|-------------------------|----------------|----------------------------------|
| Learning rate           | [value]        | [rationale]                      |
| LR schedule             | cosine + warmup| Standard for fine-tuning         |
| Warmup steps            | [N steps]      | [X%] of total steps              |
| Per-device batch size   | [N]            | GPU memory constraint            |
| Gradient accum. steps   | [N]            | Effective batch size = [N]       |
| Epochs                  | [N]            | Dataset size [N], expected [N]   |
| Max sequence length     | [N tokens]     | [Percentile] of examples         |
| Gradient clipping       | 1.0            | Universal stability practice     |
| Weight decay            | [0.01 | 0.1]  | [Regularization strength]        |
| Mixed precision         | bf16 / fp16    | Hardware dependent               |

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SECTION 5: EVALUATION PLAN
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Primary Metric:         [metric name + measurement method]
Secondary Metrics:      [list 2--3 with measurement method]
Catastrophic Forgetting Test: [benchmark subset + regression threshold]
Comparison Baselines:
  - Base model + best prompt: [current score]
  - Target fine-tuned model:  [target score]

LLM Judge:              [GPT-4o | Claude 3.5 | manual rubric]
Human Evaluation:       [YES / NO] -- [N] examples if YES

Pass Criteria:          [specific threshold for go/no-go decision]

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SECTION 6: COST ESTIMATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Dataset Curation:       ~[N] hours @ [$X/hr] = $[total]
Training Compute:       ~[N] GPU-hours @ [$X/hr] = $[total]
Evaluation:             ~[N] hours = $[total]
Total One-Time Cost:    ~$[total]

Inference Cost (baseline): $[X] per 1000 requests (large model + long prompt)
Inference Cost (fine-tuned): $[X] per 1000 requests (small model + short prompt)
Monthly Savings at [N] req/month: $[X]
Payback Period:         [N months]

Training Launch Script (annotated)

# fine_tune_lora.py
# LoRA fine-tuning script using HuggingFace PEFT + TRL SFTTrainer
# Tested with: transformers>=4.40, peft>=0.10, trl>=0.8, bitsandbytes>=0.43

import torch
from datasets import load_dataset
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    BitsAndBytesConfig,
    TrainingArguments,
)
from peft import LoraConfig, get_peft_model, TaskType
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM

# ── Model and task configuration ──────────────────────────────────────────────
BASE_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
OUTPUT_DIR = "./llama3-8b-invoice-extraction-v1"
TASK_NAME  = "invoice-extraction"

# ── LoRA configuration ────────────────────────────────────────────────────────
# r=16, alpha=32: safe default for focused extraction tasks
# Targeting all linear layers for extraction tasks (more expressive than attn-only)
lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    bias="none",
    target_modules=[
        "q_proj", "k_proj", "v_proj", "o_proj",
        "gate_proj", "up_proj", "down_proj",
    ],
    use_dora=True,  # DoRA: slight quality boost over standard LoRA at same cost
)

# ── 4-bit quantization for QLoRA (remove if using full 16-bit LoRA) ───────────
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",           # NF4 is better than fp4 for LLMs
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,      # Nested quantization saves ~0.4 GB
)

# ── Load model and tokenizer ──────────────────────────────────────────────────
model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    quantization_config=bnb_config,
    device_map="auto",
    attn_implementation="flash_attention_2",  # Requires flash-attn>=2.0
    torch_dtype=torch.bfloat16,
)
model.config.use_cache = False           # Disable KV cache during training
model.config.pretraining_tp = 1         # Disable tensor parallelism during training

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
tokenizer.pad_token = tokenizer.eos_token   # Llama-3 has no pad token by default
tokenizer.padding_side = "right"            # Right-padding for causal LM training

# ── Dataset loading and formatting ────────────────────────────────────────────
# Training examples MUST use the same chat template as inference
def format_example(example):
    """Apply Llama-3 chat template. System prompt is baked into training examples."""
    messages = [
        {
            "role": "system",
            "content": "Extract structured invoice data as JSON. "
                       "Return only valid JSON with no explanation.",
        },
        {"role": "user", "content": example["invoice_text"]},
        {"role": "assistant", "content": example["extracted_json"]},
    ]
    return {"text": tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=False
    )}

dataset = load_dataset("json", data_files={
    "train": "data/train.jsonl",
    "validation": "data/validation.jsonl",
})
dataset = dataset.map(format_example, remove_columns=dataset["train"].column_names)

# Train only on the assistant response (not the prompt) using response template
response_template = "<|start_header_id|>assistant<|end_header_id|>"
collator = DataCollatorForCompletionOnlyLM(
    response_template=response_template,
    tokenizer=tokenizer,
)

# ── Training arguments ─────────────────────────────────────────────────────────
training_args = TrainingArguments(
    output_dir=OUTPUT_DIR,
    num_train_epochs=3,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=16,      # Effective batch size = 32
    learning_rate=2e-4,
    lr_scheduler_type="cosine",
    warmup_ratio=0.05,                   # Warmup over first 5% of steps
    max_grad_norm=1.0,
    weight_decay=0.01,
    bf16=True,                           # Use bf16 on Ampere+ GPUs
    optim="paged_adamw_32bit",           # Paged optimizer reduces GPU memory spikes
    logging_steps=10,
    eval_strategy="steps",
    eval_steps=50,
    save_strategy="steps",
    save_steps=50,
    save_total_limit=3,                  # Keep top-3 checkpoints
    load_best_model_at_end=True,
    metric_for_best_model="eval_loss",
    report_to="wandb",                   # Log to Weights & Biases
    run_name=f"{TASK_NAME}-run1",
)

# ── Trainer ────────────────────────────────────────────────────────────────────
trainer = SFTTrainer(
    model=model,
    args=training_args,
    train_dataset=dataset["train"],
    eval_dataset=dataset["validation"],
    peft_config=lora_config,
    data_collator=collator,
    max_seq_length=2048,
    dataset_text_field="text",
    packing=True,                        # Pack short examples for GPU efficiency
)

trainer.train()
trainer.save_model(OUTPUT_DIR)

# ── Merge LoRA adapter into base model for deployment ─────────────────────────
from peft import PeftModel
merged_model = PeftModel.from_pretrained(
    AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16),
    OUTPUT_DIR,
)
merged_model = merged_model.merge_and_unload()
merged_model.save_pretrained(f"{OUTPUT_DIR}-merged")
tokenizer.save_pretrained(f"{OUTPUT_DIR}-merged")
print("Merged model saved. Ready for deployment.")

Rules

  1. NEVER start training without a prompt-engineered baseline score. You cannot know if fine-tuning succeeded unless you know what you are improving on. The baseline is the minimum bar the fine-tuned model must exceed.
  1. ALWAYS mask the prompt tokens from the training loss. Training the model to predict both the prompt and the completion causes it to learn to reproduce the prompt format rather than the task. Use DataCollatorForCompletionOnlyLM or equivalent to compute loss only on completion tokens.
  1. NEVER use the test split for any decision during training or hyperparameter selection. Using the test set to pick the best checkpoint invalidates your evaluation. Validation loss drives early stopping; test set is used once at the end.
  1. ALWAYS verify the chat template exactly matches inference. A single token difference between training format and inference format (e.g., a missing newline, a different BOS token) can reduce model quality by 10--40%. Print three formatted examples and inspect them visually before starting training.
  1. NEVER fine-tune to inject factual knowledge. Fine-tuning teaches the model how to behave, not what is true. A model fine-tuned on outdated medical protocols will confidently output those protocols even when they are wrong. Use RAG for knowledge grounding.
  1. ALWAYS keep a frozen copy of the base model during iteration. Fine-tuning is destructive to model weights in full fine-tuning and modifies adapter weights in LoRA. Maintain a registry of base model versions and adapter checkpoints to enable rollback.
  1. NEVER set LoRA alpha lower than LoRA rank. The effective learning rate of LoRA adapters is scaled by alpha/rank. Setting alpha < rank suppresses the adapter contribution to near zero, making fine-tuning effectively a no-op. The standard ratio is 1:2 (r=16, alpha=32) or 1:1 (r=16, alpha=16).
  1. ALWAYS check for data leakage between train and test splits before training. If your test examples are near-duplicates of training examples, you will measure memorization, not generalization. Run deduplication across all splits and compute nearest-neighbor similarity between test and train examples.
  1. NEVER deploy a fine-tuned model without a catastrophic forgetting audit. Run the model on 50 general-capability examples (basic reasoning, safety refusals, instruction following in off-task domains) and confirm it has not regressed more than 5% vs. the base model. A fine-tuned model with destroyed general capability is a liability.
  1. ALWAYS document the training data provenance and version. Fine-tuned model behavior is entirely determined by training data. When a production incident occurs (and it will), you must be able to trace the model output back to specific training examples. Maintain a data lineage log including source, curation method, filter criteria, and version hash.

Edge Cases

The Data Cliff: Fewer Than 100 Examples

When you have fewer than 100 high-quality examples, standard LoRA fine-tuning will overfit severely and produce a model that memorizes the training set rather than generalizing.

Multi-Task Fine-Tuning: Avoiding Task Interference

When a single model must perform multiple tasks (e.g., extraction, classification, and summarization), naive mixing of training data from each task causes task interference where the model degrades on each individual task.

Catastrophic Forgetting at Scale (Full Fine-Tuning)

Full fine-tuning of large models (>13B parameters) on narrow datasets routinely destroys general capabilities, especially instruction following, safety behaviors, and reasoning.

Fine-Tuning Proprietary or Confidential Data

When training data contains confidential information (customer records, legal documents, internal communications), the fine-tuned model can memorize and reproduce training examples verbatim.

Continued Fine-Tuning on an Already Fine-Tuned Model

When you need to update a fine-tuned model with new data rather than retraining from scratch, naive continued training causes the model to overfit to new data and forget the original fine-tuning.

Fine-Tuning for Safety-Critical Applications

In domains like medical, legal, or financial advice, a fine-tuned model that is more confident and fluent in the domain but has subtly incorrect behavior is more dangerous than a conservative base model.

Cloud API Fine-Tuning (OpenAI, Cohere, Vertex AI)

When using managed fine-tuning APIs rather than self-hosted training infrastructure, many of the above controls are unavailable or limited.


Example

Input from user:

"We have a legal tech startup. We want to fine-tune a model to extract structured data from commercial contracts -- specifically, extracting the parties, effective date, payment terms, governing law, and termination clauses from uploaded PDFs. We have about 800 labeled contracts. We're currently using GPT-4o with a detailed prompt and getting about 78% exact-match accuracy on our test set, and we want to get to 92%+. What fine-tuning strategy should you recommend?"


Output:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.