Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Fixed and Improved Optimizer Docs (#8159)

Michael Ryan145ab791a3c9
diff --git a/docs/docs/api/optimizers/MIPROv2.md b/docs/docs/api/optimizers/MIPROv2.md
index 1d801c479..edb711e0f 100644
--- a/docs/docs/api/optimizers/MIPROv2.md
+++ b/docs/docs/api/optimizers/MIPROv2.md
@@ -1,6 +1,6 @@
# dspy.MIPROv2
-MIPROv2 optimizer optimizes instruction and also build few-shot examples.
+`MIPROv2` (<u>M</u>ultiprompt <u>I</u>nstruction <u>PR</u>oposal <u>O</u>ptimizer Version 2) is an prompt optimizer capable of optimizing both instructions and few-shot examples jointly. It does this by bootstrapping few-shot example candidates, proposing instructions grounded in different dynamics of the task, and finding an optimized combination of these options using Bayesian Optimization. It can be used for optimizing few-shot examples & instructions jointly, or just instructions for 0-shot optimization.
<!-- START_API_REF -->
::: dspy.MIPROv2
@@ -19,5 +19,49 @@ MIPROv2 optimizer optimizes instruction and also build few-shot examples.
inherited_members: true
<!-- END_API_REF -->
+## Example Usage
-[Slightly outdated content here, to be moved and updated](https://github.com/stanfordnlp/dspy/blob/b40f359ec567a04a7f8d1d5d1a744ca9c32d5339/docs/docs/deep-dive/optimizers/miprov2.md)
+The program below shows optimizing a math program with MIPROv2
+
+```python
+import dspy
+from dspy.datasets.gsm8k import GSM8K, gsm8k_metric
+
+# Import the optimizer
+from dspy.teleprompt import MIPROv2
+
+# Initialize the LM
+lm = dspy.LM('openai/gpt-4o-mini', api_key='YOUR_OPENAI_API_KEY')
+dspy.configure(lm=lm)
+
+# Initialize optimizer
+teleprompter = MIPROv2(
+ metric=gsm8k_metric,
+ auto="medium", # Can choose between light, medium, and heavy optimization runs
+)
+
+# Optimize program
+print(f"Optimizing program with MIPROv2...")
+optimized_program = teleprompter.compile(
+ dspy.ChainOfThought("question -> answer"),
+ trainset=gsm8k.train,
+ requires_permission_to_run=False,
+)
+
+# Save optimize program for future use
+optimized_program.save(f"optimized.json")
+```
+
+## How `MIPROv2` works
+
+At a high level, `MIPROv2` works by creating both few-shot examples and new instructions for each predictor in your LM program, and then searching over these using Bayesian Optimization to find the best combination of these variables for your program. If you want a visual explanation check out this [twitter thread](https://x.com/michaelryan207/status/1804189184988713065).
+
+These steps are broken down in more detail below:
+
+1) **Bootstrap Few-Shot Examples**: Randomly samples examples from your training set, and run them through your LM program. If the output from the program is correct for this example, it is kept as a valid few-shot example candidate. Otherwise, we try another example until we've curated the specified amount of few-shot example candidates. This step creates `num_candidates` sets of `max_bootstrapped_demos` bootstrapped examples and `max_labeled_demos` basic examples sampled from the training set.
+
+2) **Propose Instruction Candidates**. The instruction proposer includes (1) a generated summary of properties of the training dataset, (2) a generated summary of your LM program's code and the specific predictor that an instruction is being generated for, (3) the previously bootstrapped few-shot examples to show reference inputs / outputs for a given predictor and (4) a randomly sampled tip for generation (i.e. "be creative", "be concise", etc.) to help explore the feature space of potential instructions. This context is provided to a `prompt_model` which writes high quality instruction candidates.
+
+3) **Find an Optimized Combination of Few-Shot Examples & Instructions**. Finally, we use Bayesian Optimization to choose which combinations of instructions and demonstrations work best for each predictor in our program. This works by running a series of `num_trials` trials, where a new set of prompts are evaluated over our validation set at each trial. The new set of prompts are only evaluated on a minibatch of size `minibatch_size` at each trial (when `minibatch`=`True`). The best averaging set of prompts is then evalauted on the full validation set every `minibatch_full_eval_steps`. At the end of the optimization process, the LM program with the set of prompts that performed best on the full validation set is returned.
+
+For those interested in more details, more information on `MIPROv2` along with a study on `MIPROv2` compared with other DSPy optimizers can be found in [this paper](https://arxiv.org/abs/2406.11695).
diff --git a/docs/docs/learn/optimization/optimizers.md b/docs/docs/learn/optimization/optimizers.md
index dd00e4a53..fb6f575ec 100644
--- a/docs/docs/learn/optimization/optimizers.md
+++ b/docs/docs/learn/optimization/optimizers.md
@@ -41,34 +41,34 @@ Optimizers can be accessed via `from dspy.teleprompt import *`.
These optimizers extend the signature by automatically generating and including **optimized** examples within the prompt sent to the model, implementing few-shot learning.
-1. **`LabeledFewShot`**: Simply constructs few-shot examples (demos) from provided labeled input and output data points. Requires `k` (number of examples for the prompt) and `trainset` to randomly select `k` examples from.
+1. [**`LabeledFewShot`**](/api/optimizers/LabeledFewShot): Simply constructs few-shot examples (demos) from provided labeled input and output data points. Requires `k` (number of examples for the prompt) and `trainset` to randomly select `k` examples from.
-2. **`BootstrapFewShot`**: Uses a `teacher` module (which defaults to your program) to generate complete demonstrations for every stage of your program, along with labeled examples in `trainset`. Parameters include `max_labeled_demos` (the number of demonstrations randomly selected from the `trainset`) and `max_bootstrapped_demos` (the number of additional examples generated by the `teacher`). The bootstrapping process employs the metric to validate demonstrations, including only those that pass the metric in the "compiled" prompt. Advanced: Supports using a `teacher` program that is a *different* DSPy program that has compatible structure, for harder tasks.
+2. [**`BootstrapFewShot`**](/api/optimizers/BootstrapFewshot): Uses a `teacher` module (which defaults to your program) to generate complete demonstrations for every stage of your program, along with labeled examples in `trainset`. Parameters include `max_labeled_demos` (the number of demonstrations randomly selected from the `trainset`) and `max_bootstrapped_demos` (the number of additional examples generated by the `teacher`). The bootstrapping process employs the metric to validate demonstrations, including only those that pass the metric in the "compiled" prompt. Advanced: Supports using a `teacher` program that is a *different* DSPy program that has compatible structure, for harder tasks.
-3. [**`BootstrapFewShotWithRandomSearch`**](/deep-dive/optimizers/bootstrap-fewshot): Applies `BootstrapFewShot` several times with random search over generated demonstrations, and selects the best program over the optimization. Parameters mirror those of `BootstrapFewShot`, with the addition of `num_candidate_programs`, which specifies the number of random programs evaluated over the optimization, including candidates of the uncompiled program, `LabeledFewShot` optimized program, `BootstrapFewShot` compiled program with unshuffled examples and `num_candidate_programs` of `BootstrapFewShot` compiled programs with randomized example sets.
+3. [**`BootstrapFewShotWithRandomSearch`**](/api/optimizers/BootstrapFewshotWithRandomSearch): Applies `BootstrapFewShot` several times with random search over generated demonstrations, and selects the best program over the optimization. Parameters mirror those of `BootstrapFewShot`, with the addition of `num_candidate_programs`, which specifies the number of random programs evaluated over the optimization, including candidates of the uncompiled program, `LabeledFewShot` optimized program, `BootstrapFewShot` compiled program with unshuffled examples and `num_candidate_programs` of `BootstrapFewShot` compiled programs with randomized example sets.
-4. **`KNNFewShot`**. Uses k-Nearest Neighbors algorithm to find the nearest training example demonstrations for a given input example. These nearest neighbor demonstrations are then used as the trainset for the BootstrapFewShot optimization process.
+4. [**`KNNFewShot`**](/api/optimizers/KNNFewShot/). Uses k-Nearest Neighbors algorithm to find the nearest training example demonstrations for a given input example. These nearest neighbor demonstrations are then used as the trainset for the BootstrapFewShot optimization process.
### Automatic Instruction Optimization
These optimizers produce optimal instructions for the prompt and, in the case of MIPROv2 can also optimize the set of few-shot demonstrations.
-5. [**`COPRO`**](/deep-dive/optimizers/copro): Generates and refines new instructions for each step, and optimizes them with coordinate ascent (hill-climbing using the metric function and the `trainset`). Parameters include `depth` which is the number of iterations of prompt improvement the optimizer runs over.
+5. [**`COPRO`**](/api/optimizers/COPRO): Generates and refines new instructions for each step, and optimizes them with coordinate ascent (hill-climbing using the metric function and the `trainset`). Parameters include `depth` which is the number of iterations of prompt improvement the optimizer runs over.
-6. [**`MIPROv2`**](/deep-dive/optimizers/miprov2): Generates instructions *and* few-shot examples in each step. The instruction generation is data-aware and demonstration-aware. Uses Bayesian Optimization to effectively search over the space of generation instructions/demonstrations across your modules.
+6. [**`MIPROv2`**](/api/optimizers/MIPROv2): Generates instructions *and* few-shot examples in each step. The instruction generation is data-aware and demonstration-aware. Uses Bayesian Optimization to effectively search over the space of generation instructions/demonstrations across your modules.
### Automatic Finetuning
This optimizer is used to fine-tune the underlying LLM(s).
-7. **`BootstrapFinetune`**: Distills a prompt-based DSPy program into weight updates. The output is a DSPy program that has the same steps, but where each step is conducted by a finetuned model instead of a prompted LM.
+7. [**`BootstrapFinetune`**](/api/optimizers/BootstrapFinetune): Distills a prompt-based DSPy program into weight updates. The output is a DSPy program that has the same steps, but where each step is conducted by a finetuned model instead of a prompted LM.
### Program Transformations
-8. **`Ensemble`**: Ensembles a set of DSPy programs and either uses the full set or randomly samples a subset into a single program.
+8. [**`Ensemble`**](/api/optimizers/Ensemble): Ensembles a set of DSPy programs and either uses the full set or randomly samples a subset into a single program.
## Which optimizer should I use?
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
index 5520658dc..71c3cca31 100644
--- a/docs/mkdocs.yml
+++ b/docs/mkdocs.yml
@@ -210,7 +210,13 @@ plugins:
"intro/index.md": "index.md"
"intro.md": "index.md"
- "deep-dive/optimizers/miprov2": "api/optimizers/MIPROv2"
+ "deep-dive/optimizers/bootstrap-fewshot.md": "api/optimizers/BootstrapFewShot.md"
+ "deep-dive/optimizers/bfrs.md": "api/optimizers/BootstrapFewShotWithRandomSearch.md"
+ "deep-dive/optimizers/BootstrapFinetune.md": "api/optimizers/BootstrapFinetune.md"
+ "deep-dive/optimizers/copro.md": "api/optimizers/COPRO.md"
+ "deep-dive/optimizers/Ensemble.md": "api/optimizers/Ensemble.md"
+ "deep-dive/optimizers/LabeledFewShot.md": "api/optimizers/LabeledFewShot.md"
+ "deep-dive/optimizers/miprov2.md": "api/optimizers/MIPROv2.md"
"docs/quick-start/getting-started-01.md": "tutorials/rag/index.ipynb"
"docs/quick-start/getting-started-02.md": "tutorials/rag/index.ipynb"