An ensemble runs multiple programs and reduces their outputs to one result. Combining imperfect programs can improve quality, at the cost of running them all in production. section 6.6
In DSPy, an ensemble is assembled by:
- Passing a list of programs to the Ensemble optimizer; the programs may use different optimizations, language models, or modules. section 6.6
- Defining a reduce function that combines their predictions. Majority vote is one option; a custom function can return a label only when all programs agree, and otherwise return “Uncertain.” section 6.6
- At inference time, the resulting program executes the listed programs and applies the reducer; compilation itself takes virtually no time. section 6.6
Listing 6.15 Calling the Ensemble optimizer with a custom reduce function
def reduce_func(predictions):
intent_labels = [p.intent_label for p in predictions]
num_unique_labels = len(set(intent_labels))
if num_unique_labels == 1:
return dspy.Prediction(intent_label=intent_labels[0])
return dspy.Prediction(intent_label="Uncertain")
ensemble_optimizer = Ensemble(reduce_fn=reduce_func)
prog_ensemble = ensemble_optimizer.compile([prog_copro, prog_mipro,
prog_infer_rules])
print(prog_ensemble(message="What meals are served on the 3pm flight to
Madrid?"))
A custom reducer for classifier predictions returns the shared intent label when all programs agree, or “Uncertain” otherwise. section 6.6
Table 6.5 Tracking the predictions to create a strong ensemble
|
Ex 1
|
Ex 2
|
Ex 3
|
Ex 4
|
Ex 5
|
|
|---|---|---|---|---|---|
|
Prog 1
|
Correct
|
–
|
–
|
Correct
|
Correct
|
|
Prog 2
|
Correct
|
Correct
|
Correct
|
–
|
–
|
|
Prog 3
|
Correct
|
–
|
Correct
|
Correct
|
Correct
|
|
Prog 4
|
Correct
|
–
|
–
|
Correct
|
–
|
|
Prog 5
|
–
|
Correct
|
Correct
|
Correct
|
–
|
|
Majority
|
Correct
|
Correct
|
Correct
|
Correct
|
Correct
|
|
Majority of 1, 2, 5
|
Correct
|
Correct
|
Correct
|
Correct
|
Correct
|
Prediction results across examples show how tracking program strengths can help identify a useful subset for an ensemble. section 6.6










