Lesson 27 Dataset Preparation
Theme:
Lesson 27 · Slide 1

Dataset Preparation

Curating high-quality training data for fine-tuning — the single biggest factor in whether your fine-tuned model succeeds or fails.

Learning Objectives

Lesson 27 · Slide 2

Quality Over Quantity

A fine-tuned model learns the patterns in your dataset — including the bad ones. 500 carefully crafted examples consistently outperform 10,000 noisy ones.

What "Quality" Means

  • Correct: Answers are factually accurate
  • Consistent: Same style, tone, and format throughout
  • Complete: Responses fully address the instruction
  • Diverse: Covers the full range of expected inputs

Common Mistakes

  • Scraping web data without filtering — garbage in, garbage out
  • Copy-pasting from ChatGPT without review — inherits its biases
  • All examples follow the same template — model only learns that template
  • Inconsistent formatting across examples — model produces inconsistent output
Notes: The LIMA paper (2023) showed that fine-tuning LLaMA-65B on just 1,000 high-quality examples produced results competitive with GPT-4 on many benchmarks. Quality is not just nice to have — it is the dominant factor.
Lesson 27 · Slide 3

The Instruction-Response Format

Supervised fine-tuning (SFT) datasets follow a consistent structure. The model learns to map instructions to responses.

Standard JSONL Format

{"instruction": "Summarise the following customer complaint in one sentence.",
 "input": "I ordered a blue widget on March 3rd and received a red one...",
 "output": "Customer received incorrect colour (red instead of blue) for widget ordered on March 3rd."}

{"instruction": "Classify the sentiment of this review.",
 "input": "The battery life is amazing but the screen is too dim outdoors.",
 "output": "mixed"}

Chat Format (Messages Array)

{"messages": [
  {"role": "system", "content": "You are a concise customer support agent."},
  {"role": "user", "content": "My order #4521 hasn't arrived."},
  {"role": "assistant", "content": "I'll look into order #4521 right away. Could you confirm your shipping address?"}
]}

Choose the format that matches your target API. Anthropic fine-tuning uses the messages array; many open-source tools accept the instruction/input/output format.

Lesson 27 · Slide 4

Data Collection Strategies

1. Manual Creation

Domain experts write instruction-response pairs by hand. Highest quality, but expensive and slow. Best for: seed datasets, edge cases, establishing gold-standard style.

Tip: Create a style guide first. Define tone, length, format, and common patterns before writing any examples.

2. Synthetic Generation

Use a strong model (e.g., Claude Sonnet) to generate training data for a smaller model. Provide few-shot examples and a clear schema. Fast and scalable, but requires validation.

Tip: Always have a human review a random sample (10-20%) of synthetic data before training.

3. Document Conversion

Transform existing assets — FAQs, docs, support tickets, wikis — into instruction-response pairs. Leverages existing knowledge, but needs reformatting.

Tip: Extract Q&A pairs from documentation headings. Each heading becomes an instruction; the section content becomes the response.

Recommended Mix

  • Start with 50-100 manual examples as a seed set
  • Generate 500-2000 synthetic examples using the seed as few-shot context
  • Convert existing docs for domain coverage
  • Human-review everything before training
Lesson 27 · Slide 5

Data Cleaning Pipeline

Raw collected data is never ready for training. Every dataset needs a cleaning pass — ideally automated with spot-checks.

Step 1: Deduplication

Exact and near-duplicate examples cause the model to memorise rather than generalise. Use hash-based exact dedup and MinHash/LSH for fuzzy matching.

Step 2: Length Filtering

Remove examples that are too short (likely incomplete) or too long (exceed your training context). Set min/max token thresholds for both instructions and responses.

Step 3: Quality Scoring

Use a strong model to score each example on a 1-5 scale for correctness, completeness, and style adherence. Filter out examples scoring below your threshold.

import pandas as pd
from datasets import Dataset

def clean_dataset(df: pd.DataFrame) -> pd.DataFrame:
    # 1. Dedup on instruction+output hash
    df = df.drop_duplicates(subset=["instruction", "output"])
    # 2. Length filter (token counts)
    df = df[df["output_tokens"].between(20, 1024)]
    df = df[df["instruction_tokens"].between(5, 512)]
    # 3. Quality filter
    df = df[df["quality_score"] >= 3]
    return df.reset_index(drop=True)
Lesson 27 · Slide 6

Train/Validation Splits & Augmentation

Splitting Strategy

SplitProportionPurpose
Train80-90%Model learns from these examples
Validation10-20%Monitors for overfitting during training
Test (optional)5-10%Final held-out evaluation

Critical Rule: No Data Leakage

If you generated variations of the same base example, all variations must go in the same split. Otherwise the model has effectively "seen" the validation data during training, and your metrics will be misleadingly optimistic.

Data Augmentation Techniques

Lesson 27 · Slide 7

Common Pitfalls

Data Leakage

Validation examples that overlap with training data give false confidence. Always split before augmentation. Check for near-duplicates across splits.

Bias Amplification

If 90% of your examples are about topic A and 10% about topic B, the model will over-index on A and underperform on B. Audit your topic distribution and balance deliberately.

Overfitting to Format

If every response starts with "Sure! Here's..." the model will always start that way — even when inappropriate. Vary your response openings and structure.

Benchmark Contamination

If your training data includes examples from standard eval benchmarks, your model will appear better than it is. Screen training data against common benchmarks.

Notes: Walk through a real example of data leakage: a student generates 5 paraphrases of each question, randomly splits, and gets 95% val accuracy. After fixing the split, val accuracy drops to 72% — the real number.
Lesson 27 · Slide 8

Lab & Homework

Lab: Dataset Pipeline

  1. Collect — Create seed examples manually and generate synthetic data with Claude
  2. Clean — Deduplicate, filter by length, score quality
  3. Format — Convert to instruction/input/output JSONL
  4. Validate — Run automated checks (schema, length, duplicates)
  5. Split — Create train/validation sets with leakage prevention

Homework Tasks

  1. Domain Dataset — Build a 200+ example dataset for a domain of your choice using all three collection strategies
  2. Quality Audit — Score a sample of 50 examples and compute inter-rater agreement
  3. Distribution Analysis — Visualise your dataset's topic, length, and difficulty distributions
1 / ?