# DSPy: Compiling Declarative Language Model Calls

This <mark style="color:blue;">**October 2023**</mark> paper introduces a programming model and framework called <mark style="color:purple;">**DSPy**</mark>, 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 <mark style="color:yellow;">LM pipelines often relies on hard-coded "prompt templates."</mark> 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

{% embed url="<https://arxiv.org/abs/2310.03714>" %}

### <mark style="color:blue;">DSPy: A Shift in AI Pipeline Design</mark>

DSPy introduces a more systematic and programmatic approach to designing AI pipelines. At its core, DSPy reimagines LM pipelines as <mark style="color:yellow;">text transformation graphs with declarative modules</mark>. This conceptualization brings several key innovations:

1. <mark style="color:blue;">**Modular Design**</mark><mark style="color:blue;">:</mark> DSPy modules are parameterized, learnable components that can apply various techniques including prompting, finetuning, augmentation, and reasoning.
2. <mark style="color:blue;">**Automated Optimization**</mark><mark style="color:blue;">:</mark> The DSPy compiler optimizes pipelines by generating effective LM invocation strategies and prompts, reducing the need for manual prompt engineering.
3. <mark style="color:blue;">**Flexible Learning Strategies**</mark><mark style="color:blue;">:</mark> Teleprompters in DSPy determine how modules learn from data, allowing for adaptable optimization strategies.

### <mark style="color:blue;">The Promise of DSPy</mark>

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, <mark style="color:yellow;">DSPy has demonstrated significant performance improvements over standard few-shot prompting and expert-created demonstrations</mark>.&#x20;

Notably, it has shown <mark style="color:yellow;">competitive results using smaller, open-source LMs</mark> compared to larger, proprietary models.

### <mark style="color:purple;">The DSPy programming model</mark>

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:

#### <mark style="color:blue;">Natural Language Signatures</mark>

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 <mark style="color:yellow;">declare what a text transformation should do</mark>.

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:

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

#### <mark style="color:blue;">Parameterized and Templated Modules</mark>

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 <mark style="color:yellow;">`Predict`</mark>, which handles basic signature implementation.
* Other built-in modules like <mark style="color:yellow;">`ChainOfThought`</mark>, <mark style="color:yellow;">`ProgramOfThought`</mark>, etc., implement more complex prompting techniques.
* Modules are parameterized, allowing for optimization of LM selection, prompt instructions, and demonstrations.

#### <mark style="color:green;">Example of a custom module (ChainOfThought):</mark>

```python
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)
```

#### <mark style="color:blue;">Programs</mark>

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

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

```python
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)
```

#### <mark style="color:blue;">Teleprompters</mark>

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:

```python
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)
```

#### <mark style="color:blue;">Metrics and Customization</mark>

DSPy allows for custom metrics to guide the optimization process.

Example of a custom metric:

```python
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
```

#### <mark style="color:blue;">Advanced Composition</mark>

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:

```python
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')
```

### <mark style="color:purple;">THER DSPy compiler</mark>

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:

#### <mark style="color:blue;">Stage 1: Candidate Generation</mark>

* The compiler first <mark style="color:yellow;">recursively identifies all unique Predict modules</mark> (predictors) in a program, including those nested under other modules.
* For each unique predictor, the teleprompter <mark style="color:yellow;">generates candidate values for the predictor's parameters</mark>. 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.

#### <mark style="color:blue;">Example:</mark> 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.

<mark style="color:green;">**Key Insight:**</mark> 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.

#### <mark style="color:blue;">Stage 2: Parameter Optimization</mark>

* 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.

#### <mark style="color:blue;">Stage 3: Higher-Order Program Optimization</mark>

* 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 <mark style="color:yellow;">without requiring extensive manual tuning or large amounts of labeled data</mark>.&#x20;

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.

### <mark style="color:blue;">Evaluation</mark>

In the evaluation section, the researchers aimed to <mark style="color:yellow;">test three main hypotheses</mark> about DSPy:

1. That DSPy can <mark style="color:yellow;">replace hand-crafted prompts</mark> with well-defined modules without losing quality.
2. That DSPy's approach makes it <mark style="color:yellow;">better at adapting to different language models</mark> and can outperform expert-written prompts.
3. That DSPy's modularity allows for <mark style="color:yellow;">exploring complex pipelines</mark> 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) <mark style="color:yellow;">led to big improvements for all programs and both language models</mark>.&#x20;

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.

### <mark style="color:purple;">Case Study</mark>

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:

<mark style="color:blue;">Task and Dataset</mark>

* Multi-hop question answering using HotPotQA
* Open-domain "fullwiki" setting
* Used <mark style="color:yellow;">ColBERTv2 retriever</mark> for searching Wikipedia abstracts

<mark style="color:blue;">**Programs Tested:**</mark> 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

<mark style="color:blue;">Key Findings</mark>

* 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.

<mark style="color:blue;">Noteworthy Result</mark>

* 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.

<mark style="color:blue;">Comparisons to Other Studies</mark>

* 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.&#x20;

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.

### <mark style="color:purple;">Summary: DSPy Framework and Evaluation</mark>

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.
