Page cover image

DSPy: Compiling Declarative Language Model Calls

This October 2023 paper introduces a programming model and framework called DSPy, designed for developing and optimizing language model (LM) pipelines, addresses critical challenges faced by AI researchers and developers.

The Current Landscape and Its Challenges

As language models have grown in complexity and capability, so too have the methods for harnessing their power. However, the current approach to building LM pipelines often relies on hard-coded "prompt templates." These templates, typically crafted through painstaking trial and error, present several limitations:

  1. Lack of scalability

  2. Brittleness across different tasks or models

  3. Heavy reliance on expert knowledge and manual fine-tuning

DSPy: A Shift in AI Pipeline Design

DSPy introduces a more systematic and programmatic approach to designing AI pipelines. At its core, DSPy reimagines LM pipelines as text transformation graphs with declarative modules. This conceptualization brings several key innovations:

  1. Modular Design: DSPy modules are parameterized, learnable components that can apply various techniques including prompting, finetuning, augmentation, and reasoning.

  2. Automated Optimization: The DSPy compiler optimizes pipelines by generating effective LM invocation strategies and prompts, reducing the need for manual prompt engineering.

  3. Flexible Learning Strategies: Teleprompters in DSPy determine how modules learn from data, allowing for adaptable optimization strategies.

The Promise of DSPy

DSPy's approach offers several compelling benefits:

  • More flexible and modular pipeline design

  • Reduced reliance on expert-crafted prompts

  • Enablement of optimization for complex, multi-stage NLP systems

  • Effective performance with smaller, more efficient LMs

Through case studies on math word problems and multi-hop question answering, DSPy has demonstrated significant performance improvements over standard few-shot prompting and expert-created demonstrations.

Notably, it has shown competitive results using smaller, open-source LMs compared to larger, proprietary models.

The DSPy programming model

This section of the paper delves deeper into the core components of the DSPy programming model. Here's a detailed analysis and summary of the key concepts:

Natural Language Signatures

DSPy introduces "signatures" as a way to abstract the input/output behavior of language model tasks. Instead of using free-form string prompts, signatures provide a structured way to declare what a text transformation should do.

Key points:

  • Signatures are tuples of input and output fields, with optional instructions.

  • They use natural language typing, inferring roles based on field names (e.g., "question" vs "answer").

  • Can be expressed in shorthand notation, e.g., "question -> answer".

  • Offer benefits over traditional prompts: can be compiled into self-improving, pipeline-adaptive prompts or fine-tunes.

Example:

qa = dspy.Predict("question -> answer")
result = qa(question="Where is Guaraní spoken?")
# Output: Prediction(answer='Guaraní is spoken mainly in South America.')

Parameterized and Templated Modules

Modules in DSPy are the building blocks that implement signatures. They abstract various prompting techniques into reusable, parameterized components.

Key points:

  • The core module is Predict, which handles basic signature implementation.

  • Other built-in modules like ChainOfThought, ProgramOfThought, etc., implement more complex prompting techniques.

  • Modules are parameterized, allowing for optimization of LM selection, prompt instructions, and demonstrations.

Example of a custom module (ChainOfThought):

class ChainOfThought(dspy.Module):
    def __init__(self, signature):
        rationale_field = dspy.OutputField(prefix="Reasoning: Let's think step by step.")
        signature = dspy.Signature(signature).prepend_output_field(rationale_field)
        self.predict = dspy.Predict(signature)
    
    def forward(self, **kwargs):
        return self.predict(**kwargs)

Programs

DSPy allows for the composition of modules into complex pipelines using a define-by-run interface.

Example of a Retrieval-Augmented Generation (RAG) system:

class RAG(dspy.Module):
    def __init__(self, num_passages=3):
        self.retrieve = dspy.Retrieve(k=num_passages)
        self.generate_answer = dspy.ChainOfThought("context, question -> answer")
    
    def forward(self, question):
        context = self.retrieve(question).passages
        return self.generate_answer(context=context, question=question)

Teleprompters

Teleprompters are optimizers in DSPy that tune the parameters of DSPy programs to maximize specified metrics.

Key points:

  • Take a program, training set, and metric as inputs.

  • Can work with small, potentially incomplete training sets.

  • Support various optimization strategies.

Example of using a teleprompter:

qa_trainset = [dspy.Example(question="What is the capital of France?", answer="Paris")]
teleprompter = dspy.BootstrapFewShot(metric=dspy.evaluate.answer_exact_match)
compiled_rag = teleprompter.compile(RAG(), trainset=qa_trainset)

Metrics and Customization

DSPy allows for custom metrics to guide the optimization process.

Example of a custom metric:

def answer_and_context_match(example, pred, trace=None):
    answer_match = dspy.evaluate.answer_exact_match(example, pred)
    context_match = any((pred.answer.lower() in c) for c in pred.context)
    return answer_match and context_match

Advanced Composition

Teleprompters can be composed, allowing for complex optimization strategies. For instance, using a large language model to supervise the training of a smaller, more efficient model.

Example:

finetuning_teleprompter = BootstrapFinetune(metric=dspy.evaluate.answer_passage_match)
compiled_rag_via_finetune = finetuning_teleprompter.compile(RAG(), teacher=compiled_rag, trainset=unlabeled_questions, target='google/flan-t5-large')

THER DSPy compiler

The DSPy compiler is a component of the framework responsible for automatically optimizing DSPy programs.

It works through a process called "compiling," which uses a teleprompter (an optimizer for DSPy programs) to improve the quality or efficiency of modules via prompting or fine-tuning. Let's break down the compiler's operation into its three main stages:

Stage 1: Candidate Generation

  • The compiler first recursively identifies all unique Predict modules (predictors) in a program, including those nested under other modules.

  • For each unique predictor, the teleprompter generates candidate values for the predictor's parameters. These parameters include: a) Instructions b) Field descriptions c) Demonstrations (example input-output pairs)

  • The paper focuses primarily on generating and selecting demonstrations, as these are found to be particularly effective in bootstrapping complex multi-stage systems.

Example: BootstrapFewShot Teleprompter (or Optimizer)

  • Simulates a teacher program (or a zero-shot version of the program being compiled) on training inputs.

  • May run multiple times with high temperature to increase diversity.

  • Tracks multi-stage traces transparently and in a thread-safe manner during execution.

  • Uses the program's metric to filter for multi-stage traces that help the pipeline pass the metric.

  • Keeps good examples as potential demonstrations and discards bad ones.

Key Insight: While language models can be unreliable, they can efficiently search the solution space for multi-stage designs. A well-decomposed program can typically find at least a few training examples where the LM passes the constraints enforced by the signatures and metrics.

Stage 2: Parameter Optimization

  • Each parameter now has a discrete set of candidates (demonstrations, instructions, etc.).

  • Various hyperparameter tuning algorithms can be applied for selection among candidates: a) Random search b) Tree-structured Parzen Estimators (as in HyperOpt and Optuna)

  • The paper mentions two implementations: a) BootstrapFewShotWithRandomSearch b) BootstrapFewShotWithOptuna

  • Another optimization approach is fine-tuning with BootstrapFinetune:

    • Uses demonstrations to update the LM's weights for each predictor.

    • Updates the LM parameter of each module to the new LM weights.

  • Typically, optimization aims to improve average quality using the metric with cross-validation over the training set or a validation set.

  • This process can work even without labels for intermediate stages, depending on the nature of the metric.

Stage 3: Higher-Order Program Optimization

  • This stage involves modifying the control flow of the program itself.

  • One simple form is ensembles:

    • Bootstraps multiple copies of the same program.

    • Replaces the original program with a new one that runs all copies in parallel.

    • Reduces their predictions into one with a custom function (e.g., majority voting).

  • Future potential:

    • Accommodate techniques for more dynamic (test-time) bootstrapping.

    • Implement automatic backtracking-like logic.

The DSPy compiler's approach is powerful because it can optimize complex, multi-stage language model pipelines without requiring extensive manual tuning or large amounts of labeled data.

By generating and selecting effective demonstrations, optimizing parameters, and even modifying program structure, the compiler can significantly improve the performance and efficiency of DSPy programs.

This automated optimization process allows developers to focus on high-level task definitions and pipeline structures, while the compiler handles the intricate details of making the system work effectively with various language models and tasks.

Evaluation

In the evaluation section, the researchers aimed to test three main hypotheses about DSPy:

  1. That DSPy can replace hand-crafted prompts with well-defined modules without losing quality.

  2. That DSPy's approach makes it better at adapting to different language models and can outperform expert-written prompts.

  3. That DSPy's modularity allows for exploring complex pipelines that can meet specific performance needs.

To test these ideas, they focused on math word problems using a dataset called GSM8K. They created three different programs using DSPy:

  1. A simple one-step program (vanilla)

  2. A two-step program that uses chain-of-thought reasoning (CoT)

  3. A more complex program that generates multiple reasoning attempts and compares them (reflection)

They then tested these programs in different ways:

  • Without any optimization (zero-shot)

  • With a simple few-shot learning approach

  • With more advanced optimization techniques (bootstrap and ensemble)

They tried these approaches with two different language models: GPT-3.5 and Llama2-13b-chat.

The results showed that:

  • The simple vanilla program struggled without optimization but improved significantly with DSPy's optimization techniques.

  • The CoT program performed well, especially when optimized, and could match or beat expert-written prompts.

  • The reflection program, despite being only slightly more complex, performed the best overall.

In general, using DSPy's optimization methods (bootstrap and ensemble) led to big improvements for all programs and both language models.

The researchers found that by using DSPy's modules and optimization techniques, they could improve the accuracy of these language models on math problems from as low as 4-20% to as high as 49-88%.

They also compared their results to other published studies and found that their approach using DSPy could achieve competitive or better results, even when using smaller language models or less human-provided information.

Overall, the evaluation showed that DSPy could effectively replace hand-crafted prompts, adapt well to different language models, and allow for the creation of powerful, flexible AI pipelines without needing extensive manual tuning.

Case Study

This case study focuses on evaluating DSPy's performance on complex question answering using the HotPotQA dataset. Here's a breakdown of the key points:

Task and Dataset

  • Multi-hop question answering using HotPotQA

  • Open-domain "fullwiki" setting

  • Used ColBERTv2 retriever for searching Wikipedia abstracts

Programs Tested: a) Vanilla: Simple question-to-answer program b) RAG (Retrieval-Augmented Generation): Uses chain-of-thought reasoning c) ReAct: Multi-step agent for tool use d) BasicMultiHop: Custom program simulating information flow in more complex systems

Compilation Strategies

  • Similar to the GSM8K case study (few-shot, bootstrap, ensemble)

  • Added fine-tuning with T5-Large for the multihop program

Key Findings

  • Chain-of-thought and retrieval-augmented generation (CoT RAG) improved performance significantly over vanilla few-shot prompting.

  • ReAct and multihop programs performed better by generating queries for multiple "hops" of retrieval.

  • The simple multihop program performed best overall.

  • Bootstrap compilation was very effective at improving quality for both tested language models (GPT-3.5 and Llama2-13b-chat).

  • DSPy's compilation strategies often outperformed few-shot prompting and expert human reasoning.

  • Llama2-13b-chat became competitive with GPT-3.5 when using DSPy's compilation techniques.

Noteworthy Result

  • A fine-tuned T5-Large model (770M parameters) achieved 39.3% answer exact match and 46.0% passage accuracy using only 200 labeled inputs and 800 unlabeled questions.

  • This smaller, locally-available model could potentially offer significant cost savings compared to using proprietary models like GPT-3.5.

Comparisons to Other Studies

  • DSPy's results are competitive with or surpass those reported in recent papers using various prompting techniques and larger language models.

This case study demonstrates DSPy's effectiveness in handling complex, multi-step reasoning tasks.

The framework's ability to improve performance across different model sizes and types (from T5-Large to GPT-3.5) showcases its versatility. The success of the multihop program highlights how DSPy allows for the creation of more sophisticated AI pipelines without extensive manual prompt engineering.

The study also emphasizes DSPy's potential for democratizing AI development. By achieving competitive results with smaller, open-source models like Llama2-13b-chat and even T5-Large, DSPy opens up possibilities for researchers and developers who may not have access to the largest, most expensive language models.

Overall, this case study provides strong evidence for DSPy's ability to optimize language model performance on complex tasks, potentially reducing the reliance on manually crafted prompts and very large language models.

Summary: DSPy Framework and Evaluation

DSPy is a novel programming model and framework designed to streamline the development and optimization of language model (LM) pipelines. It addresses key challenges in current AI development practices, particularly the reliance on hand-crafted prompts.

Key Components:

  1. Natural Language Signatures: Abstract input/output behavior of LM tasks

  2. Parameterized Modules: Reusable components implementing various prompting techniques

  3. Programs: Compositions of modules to create complex AI workflows

  4. Teleprompters (Optimizers): Automatically tune parameters to maximize specified metrics

Core Benefits:

  • Replaces hand-crafted prompts with modular, optimizable components

  • Improves adaptability to different LMs

  • Enables exploration of complex pipelines without extensive manual tuning

Evaluation:

DSPy was tested on two main tasks:

  1. Math Word Problems (GSM8K dataset)

  2. Complex Question Answering (HotPotQA dataset)

Key Findings:

  • Significant performance improvements over standard few-shot prompting and expert-created demonstrations

  • Effective across different LM sizes (from T5-Large to GPT-3.5)

  • Competitive results using smaller, open-source LMs compared to larger, proprietary models

  • Successful optimization of complex, multi-step reasoning tasks

Implications:

  1. Potential to standardize "foundation model programming"

  2. Democratization of AI development by enabling high performance with smaller, more accessible models

  3. Reduction in reliance on manual prompt engineering and very large language models

DSPy represents a significant step towards more systematic, efficient, and accessible AI pipeline development, potentially transforming how researchers and developers work with language models.

Last updated

Logo

Continuum - Accelerated Artificial Intelligence

Continuum WebsiteAxolotl Platform

Copyright Continuum Labs - 2023