Instruction Data Creation › Seed Task Expansion

Michael BrenndoerferDecember 16, 202516 min read
Language AI HandbookAll chapters
Part 36 of 67Instruction Tuning
Chapter 267Instruction Data Creation › Seed Task Expansion
Reading section 4 of 9 · Seed Task Expansion · 16 minSection 4 of 9 · 16 min

Book contents

Section 4 of 9 · 16 min read

Instruction Data Creation › Seed Task ExpansionOne section · Sections in this chapter4 / 9 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Seed task expansion bridges the gap between expensive human annotation and mechanical template conversion. The approach starts with a small set of carefully crafted seed examples, then uses various techniques to expand this seed into a larger, more diverse dataset. This method preserves the quality and naturalness of human-written examples while achieving scale through systematic augmentation. Think of it as using master-crafted templates as a starting point and then having skilled craftspeople produce variations that respect the spirit of the original.

The motivation for seed expansion comes directly from the limitations we identified in both human annotation and template conversion. Human annotation produces excellent examples but at prohibitive cost. Template conversion produces many examples but lacks naturalness and creative breadth. Seed expansion attempts to get the best of both approaches: by starting from human-quality seed examples and expanding them through principled techniques, we can build datasets that are larger than pure human annotation can produce while retaining more naturalness than pure template conversion.

The key insight in seed expansion is that a well-chosen example encodes information about an entire class of similar examples. A seed that demonstrates how to answer a question about a historical event implicitly teaches the model about the structure of historical questions more generally. A seed that demonstrates creative brainstorming implies a space of similar creative tasks. By expanding from carefully designed seeds, we can efficiently populate the space of possible instructions without needing to enumerate every possible instance explicitly.

The Seed Set Philosophy

A good seed set is small but carefully curated. The philosophy behind seed expansion recognizes that a few excellent examples, chosen to cover the space of possible instructions, can serve as anchors for generating many more examples. The key is ensuring that the seeds represent the diversity you want in the final dataset. A seed set that covers only question answering and summarization will produce expansions that cover only those tasks, no matter how many expansion techniques you apply.

A well-designed seed set should demonstrate the following properties:

  • Task diversity: Including examples from many task categories (creative writing, question answering, coding, analysis, etc.) ensures that expansion can generate examples across the full range of desired capabilities.
  • Format diversity: Showing different input/output structures (single-turn, multi-turn, with/without context) teaches the model that instructions can take many forms.
  • Complexity range: Spanning from simple lookups to multi-step reasoning ensures the model learns to handle both easy and difficult requests.
  • Style variety: Demonstrating different appropriate tones and verbosity levels teaches the model to adapt its communication style to different contexts.

The Self-Instruct paper, which the next chapter explores in detail, started with just 175 seed tasks. Each seed was written to be distinct, covering a different aspect of instruction-following capability. This small but diverse seed set enabled the generation of tens of thousands of additional examples while maintaining quality and coverage. The success of Self-Instruct demonstrated that the seed set, not the expansion volume, is the critical determinant of final dataset quality. Expanding from 175 excellent seeds produced better results than expanding from 500 mediocre seeds.

Designing seed sets is itself a creative challenge that rewards careful thought. A practical approach is to enumerate the capabilities you want the final model to have, then write seeds that clearly demonstrate each capability. Creative writing, factual question answering, logical reasoning, code generation, summarization, translation, advice-giving, and task decomposition are examples of capabilities worth explicit seed coverage. Within each capability, seeds should cover different topics and difficulty levels, with varied response lengths to signal the range that expansion should produce.

In[10]:
Code
# Example seed tasks demonstrating diversity
seed_tasks = [
    # Creative writing
    {
        "category": "creative_writing",
        "instruction": "Write a haiku about artificial intelligence.",
        "input": "",
        "output": "Silicon neurons\nDreaming in binary code\nLearning to be real",
    },
    # Question answering with context
    {
        "category": "reading_comprehension",
        "instruction": "Answer the question based on the given passage.",
        "input": "Passage: The Great Wall of China was built over many centuries, with the most well-known sections constructed during the Ming Dynasty (1368-1644). It stretches approximately 13,171 miles.\n\nQuestion: During which dynasty were the most famous parts of the Great Wall built?",
        "output": "The most well-known sections of the Great Wall were built during the Ming Dynasty (1368-1644).",
    },
    # Code generation
    {
        "category": "coding",
        "instruction": "Write a Python function that checks if a number is prime.",
        "input": "",
        "output": """def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True""",
    },
    # Analysis
    {
        "category": "analysis",
        "instruction": "Identify the logical fallacy in the following argument.",
        "input": "Everyone I know loves this restaurant, so it must be the best restaurant in the city.",
        "output": "This argument commits the hasty generalization fallacy. The speaker assumes that because everyone they personally know loves the restaurant, it must be the best in the entire city. However, their personal acquaintances represent a small, potentially unrepresentative sample of all restaurant-goers in the city.",
    },
    # Classification
    {
        "category": "classification",
        "instruction": "Determine whether the following email is spam or legitimate.",
        "input": "Subject: Meeting Tomorrow\n\nHi John,\n\nJust a reminder about our 3 PM meeting tomorrow to discuss the Q3 budget. Please bring the latest projections.\n\nBest,\nSarah",
        "output": "Legitimate. This email appears to be a genuine business communication about an internal meeting, with specific details about timing, purpose, and attendees.",
    },
    # Summarization
    {
        "category": "summarization",
        "instruction": "Summarize the following paragraph in one sentence.",
        "input": "Machine learning models require large amounts of data to learn patterns effectively. This data must be properly cleaned and preprocessed before training. Additionally, the choice of model architecture depends heavily on the specific task and available computational resources. Hyperparameter tuning is often necessary to achieve optimal performance.",
        "output": "Effective machine learning requires substantial clean data, appropriate architecture selection based on task requirements and resources, and careful hyperparameter optimization.",
    },
]
Out[11]:
Console
Seed set contains 6 diverse examples across categories:

  creative_writing: 1 example(s)
  reading_comprehension: 1 example(s)
  coding: 1 example(s)
  analysis: 1 example(s)
  classification: 1 example(s)
  summarization: 1 example(s)

Example seed task (coding):
  Instruction: "Write a Python function that checks if a number is prime."
  Output preview: def is_prime(n):
    if n < 2:
        return Fals...
Out[12]:
Visualization
Horizontal bar chart showing one seed task in each of six categories: creative writing, reading comprehension, coding, analysis, classification, and summarization.
Distribution of the six seed tasks across creative writing, reading comprehension, coding, analysis, classification, and summarization. One example in each category gives this small demonstration balanced functional coverage before expansion.

Augmentation Techniques

Once you have a seed set, several techniques can expand it without requiring additional human annotation. These techniques use the structure and content of existing examples to generate new variations that preserve the essential characteristics while adding diversity. The goal is to fill in the space around each seed example, populating the neighborhood of each capability cluster with many closely related examples so the model encounters that capability in many forms.

Paraphrasing generates alternative wordings for existing instructions. The goal is to teach the model that the same task can be expressed in many different ways. You might say "Write a poem" or "Compose a poem" or "Create a poem," and the model should recognize these as equivalent requests. Paraphrasing is particularly valuable for instructions that users are likely to phrase in many different ways, such as creative writing tasks or general knowledge questions. When paraphrasing is done by another language model rather than through rules, it can produce remarkably natural variations that capture stylistic subtleties a rule-based system would miss.

In[13]:
Code
# Simple rule-based paraphrasing for demonstration
# In practice, you might use a language model for more natural paraphrases


def paraphrase_instruction(instruction: str) -> list:
    """Generate paraphrased versions of an instruction."""
    paraphrases = []

    # Pattern: "Write X" -> "Compose X" / "Create X" / "Draft X"
    if instruction.startswith("Write"):
        for verb in ["Compose", "Create", "Draft", "Produce"]:
            paraphrases.append(instruction.replace("Write", verb, 1))

    # Pattern: "Determine X" -> "Figure out X" / "Identify X"
    if instruction.startswith("Determine"):
        for verb in ["Figure out", "Identify", "Assess"]:
            paraphrases.append(instruction.replace("Determine", verb, 1))

    # Pattern: "Answer X" -> "Respond to X" / "Address X"
    if instruction.lower().startswith("answer"):
        for verb in ["Respond to", "Address"]:
            paraphrases.append(
                instruction.replace("Answer", verb, 1).replace(
                    "answer", verb, 1
                )
            )

    # Add question form variations
    if not instruction.endswith("?"):
        question_form = (
            f"Can you {instruction[0].lower()}{instruction[1:].rstrip('.')}?"
        )
        paraphrases.append(question_form)

    return paraphrases


# Example paraphrasing
original = "Write a haiku about artificial intelligence."
paraphrased = paraphrase_instruction(original)
Out[14]:
Console
Original: "Write a haiku about artificial intelligence."

Paraphrased versions:
  - "Compose a haiku about artificial intelligence."
  - "Create a haiku about artificial intelligence."
  - "Draft a haiku about artificial intelligence."
  - "Produce a haiku about artificial intelligence."
  - "Can you write a haiku about artificial intelligence?"

The rule-based approach generates several valid syntactic variations of the original instruction, expanding the dataset without changing the semantic intent. This teaches the model that different queries you write can map to the same underlying task. While rule-based paraphrasing is limited in its flexibility, it provides a foundation that can be enhanced with more sophisticated language model-based paraphrasing techniques. A language model prompted to paraphrase an instruction can capture idiomatic variations, stylistic shifts, and colloquial phrasings that rule-based systems cannot produce, though at higher computational cost.

Input variation creates new examples by substituting different inputs into the same instruction template. This technique recognizes that many instructions follow reusable patterns where the specific content can change while the task structure remains constant. A request to "write a Python function" can apply to countless different programming problems. A request to "analyze the logical fallacy in this argument" works for any argument that contains a fallacy. By systematically varying the input while keeping the instruction structure constant, we create many training examples from a single seed at very low cost.

In[15]:
Code
# Input variation for the prime number coding task
coding_variations = [
    {
        "instruction": "Write a Python function that checks if a string is a palindrome.",
        "input": "",
        "base_concept": "string validation",
    },
    {
        "instruction": "Write a Python function that calculates the factorial of a number.",
        "input": "",
        "base_concept": "mathematical computation",
    },
    {
        "instruction": "Write a Python function that finds the largest element in a list.",
        "input": "",
        "base_concept": "list processing",
    },
    {
        "instruction": "Write a Python function that reverses a string.",
        "input": "",
        "base_concept": "string manipulation",
    },
]

# Topic variation for creative writing
creative_variations = [
    "Write a haiku about the ocean.",
    "Write a haiku about autumn leaves.",
    "Write a haiku about morning coffee.",
    "Write a haiku about city life.",
    "Write a haiku about solitude.",
]
Out[16]:
Console
Input variations for coding task pattern:
  - Write a Python function that checks if a string is a palindrome. (string validation)
  - Write a Python function that calculates the factorial of a number. (mathematical computation)
  - Write a Python function that finds the largest element in a list. (list processing)
  - Write a Python function that reverses a string. (string manipulation)

Topic variations for creative writing pattern:
  - Write a haiku about the ocean.
  - Write a haiku about autumn leaves.
  - Write a haiku about morning coffee.
  - Write a haiku about city life.
  - Write a haiku about solitude.

The coding variations demonstrate a pattern common in real instruction datasets: a single structural template ("Write a Python function that...") applied to many different problems. Each resulting instruction is distinct and useful as a training example, but the cost of creation is minimal because the structure is reused. The creative writing variations work similarly, substituting different topics into a fixed poetic form. For both types, the variation is in the content, not the format, so the model learns the task structure from the seed and content generalization from the variations.

A third augmentation technique is complexity scaling, where we take simple seed examples and create more complex versions by adding constraints, combining multiple sub-tasks, or requiring multi-step reasoning. A simple "Summarize this article in one sentence" can be scaled to "Summarize this article in one sentence, then identify the three most important supporting points." A simple "Classify this email as spam or not spam" can be scaled to "Classify this email as spam or not spam, explain your reasoning, and suggest how to improve the spam filter to catch similar messages." Complexity scaling ensures the dataset covers the full range of difficulty that users might require.

Diversity Sampling

When expanding from seeds, maintaining diversity matters. Without careful sampling, expansion tends to produce many similar examples clustered around popular seed patterns while neglecting rarer but important task types. This clustering reduces the effective size of the dataset and can lead to models that perform well on common tasks but poorly on less frequent ones. The problem is analogous to class imbalance in supervised learning: if 80% of your training examples are sentiment classification tasks, the model will be very good at sentiment classification but mediocre at everything else.

Diversity sampling techniques help ensure balanced coverage across task types and linguistic patterns. The goal is not to produce equal numbers of every type, but to prevent any type from becoming so dominant that it crowds out others. A dataset that covers many task types with adequate representation for each produces more capable, general-purpose models than one that over-specializes in any particular direction.

The key diversity mechanisms used in practice include:

  • Category balancing: Ensuring expanded data maintains representation across all task categories prevents any single category from dominating the training signal. This often requires actively sampling underrepresented categories more heavily during expansion.
  • Embedding-based filtering: Using text embeddings to detect and remove examples too similar to existing ones keeps the dataset diverse at a semantic level, catching redundancy that surface-level metrics would miss.
  • Verb/topic tracking: Monitoring the distribution of instruction verbs and topics to prevent overconcentration helps identify when expansion is gravitating toward particular patterns that need to be counterbalanced.
In[17]:
Code
from collections import Counter

import numpy as np


def calculate_instruction_diversity(instructions: list) -> dict:
    """Analyze the diversity of a set of instructions."""

    # Extract first verbs (simplified)
    first_words = [inst.split()[0].lower() for inst in instructions]
    verb_counts = Counter(first_words)

    # Calculate entropy as a diversity measure
    total = len(first_words)
    probabilities = [count / total for count in verb_counts.values()]
    entropy = -sum(p * np.log2(p) for p in probabilities if p > 0)
    max_entropy = np.log2(len(verb_counts))  # Maximum possible entropy

    # Normalized diversity score (0-1)
    diversity_score = entropy / max_entropy if max_entropy > 0 else 0

    return {
        "num_instructions": total,
        "unique_first_words": len(verb_counts),
        "most_common": verb_counts.most_common(5),
        "diversity_score": diversity_score,
    }


# Compare diversity of two hypothetical expanded datasets
diverse_instructions = [
    "Write a poem about nature.",
    "Explain quantum computing.",
    "Summarize the main points.",
    "Calculate the area of a circle.",
    "Translate this to Spanish.",
    "Debug the following code.",
    "Classify this sentiment.",
    "Generate a story beginning.",
    "Analyze the argument's logic.",
    "Compare these two approaches.",
]

repetitive_instructions = [
    "Write a poem about love.",
    "Write a story about adventure.",
    "Write an essay about climate.",
    "Write a haiku about seasons.",
    "Write a limerick about cats.",
    "Write a blog post about technology.",
    "Write a summary of this article.",
    "Write a response to this email.",
    "Write a sonnet about time.",
    "Write a paragraph about history.",
]

diverse_stats = calculate_instruction_diversity(diverse_instructions)
repetitive_stats = calculate_instruction_diversity(repetitive_instructions)
Out[18]:
Console
Diverse instruction set:
  Unique starting words: 10
  Diversity score: 1.000
  Most common: [('write', 1), ('explain', 1), ('summarize', 1), ('calculate', 1), ('translate', 1)]

Repetitive instruction set:
  Unique starting words: 1
  Diversity score: 0.000
  Most common: [('write', 10)]
Out[19]:
Visualization
Bar chart comparing diversity scores between a diverse dataset (near 1.0) and a repetitive dataset (significantly lower), illustrating the impact of varied instruction creation.
Diversity score comparison between diverse and repetitive datasets. The diverse dataset achieves a score near 1.0, indicating high entropy and balanced task representation, while the repetitive dataset scores significantly lower due to pattern reuse across all instructions.
Grouped bar chart showing starting verb frequency for diverse versus repetitive datasets, with repetitive datasets heavily overusing verbs like Write while diverse datasets spread usage more evenly.
Starting verb distribution for diverse versus repetitive datasets. Repetitive datasets heavily overuse specific verbs like 'Write', whereas diverse datasets demonstrate a broader lexical spread and more varied instruction structures throughout the collection.

The diversity score captures how evenly distributed the instruction patterns are. A dataset dominated by "Write..." instructions scores lower than one with balanced representation across different task types. This metric provides a quantitative way to track diversity during expansion and flag potential problems before they affect model training. Monitoring diversity metrics throughout the expansion process, rather than only at the end, allows course correction before the imbalance becomes entrenched.

Diversity measured by instruction verb is a crude proxy for the full diversity we care about. Two instructions that both start with "Explain" may cover completely different knowledge domains and require very different capabilities. More sophisticated diversity measures use embedding-based methods to compare instructions in a semantic space, identifying redundancy at the level of meaning rather than surface form. The verb-based entropy measure above is a useful quick check, but it should be supplemented with semantic diversity analysis.