DSPy: The framework for programming—not prompting—language models
Python
feat(gepa): parallelize candidate evaluation (#10210)
Isaac Miller822f393194b8
diff --git a/dspy/teleprompt/gepa/gepa.py b/dspy/teleprompt/gepa/gepa.pyindex 5c0f40e91..48be13b29 100644--- a/dspy/teleprompt/gepa/gepa.py+++ b/dspy/teleprompt/gepa/gepa.py@@ -279,7 +279,8 @@ class GEPA(Teleprompter):add_format_failure_as_feedback: Whether to add format failures as feedback. Default is False.use_merge: Whether to use merge-based optimization. Default is True.max_merge_invocations: The maximum number of merge invocations to perform. Default is 5.- num_threads: The number of threads to use for evaluation with `Evaluate`. Optional.+ num_threads: The total number of threads available for candidate and example evaluation. Multi-proposal+ candidate evaluations share this budget. Optional.failure_score: The score to assign to failed examples. Default is 0.0.perfect_score: The maximum score achievable by the metric. Default is 1.0. Used by GEPAto determine if all examples in a minibatch are perfect.@@ -325,7 +326,7 @@ class GEPA(Teleprompter):- mlflow_tracking_uri: The tracking URI to use for MLflow (when use_mlflow=True).- mlflow_experiment_name: The experiment name to use for MLflow (when use_mlflow=True).- sampling_strategy, selection_strategy, acceptance_criterion: GEPA 0.1.4 proposal controls.- DSPy supports these using GEPA's sequential candidate-evaluation fallback.+ DSPy evaluates proposal candidates concurrently within the `num_threads` budget.- wandb_attach_existing, mlflow_attach_existing, tracking_key_prefix: GEPA 0.1.4 tracking controls.`max_reflection_cost` is not supported yet because DSPy LMs do not expose the cumulative cost@@ -346,8 +347,9 @@ class GEPA(Teleprompter):Merge Configuration: GEPA can merge successful program variants using `use_merge=True`.The `max_merge_invocations` parameter controls how many merge attempts are made during optimization.- Evaluation Configuration: Use `num_threads` to parallelize evaluation. The `failure_score` and- `perfect_score` parameters help GEPA understand your metric's range and optimize accordingly.+ Evaluation Configuration: `num_threads` controls total evaluation concurrency and is shared across+ candidates in multi-proposal batches. The `failure_score` and `perfect_score` parameters help GEPA+ understand your metric's range and optimize accordingly.Logging Configuration: Set `log_dir` to save detailed logs and enable checkpoint resuming.Use `track_stats=True` to access detailed optimization results via the `detailed_results` attribute.diff --git a/dspy/teleprompt/gepa/gepa_utils.py b/dspy/teleprompt/gepa/gepa_utils.pyindex dabb0937e..16d067e01 100644--- a/dspy/teleprompt/gepa/gepa_utils.py+++ b/dspy/teleprompt/gepa/gepa_utils.py@@ -1,5 +1,7 @@import loggingimport random+from concurrent.futures import ThreadPoolExecutor+from contextvars import copy_contextfrom typing import Any, Callable, Protocol, TypedDictfrom gepa import EvaluationBatch, GEPAAdapter@@ -189,7 +191,8 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):return new_prog- def evaluate(self, batch, candidate, capture_traces=False):+ def evaluate(self, batch, candidate, capture_traces=False, num_threads=None):+ num_threads = self.num_threads if num_threads is None else num_threadstry:program = self.build_program(candidate)except (SyntaxError, CodeInterpreterError) as e:@@ -217,7 +220,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):program,batch,metric_fn=self.metric_fn,- num_threads=self.num_threads,+ num_threads=num_threads,failure_score=self.failure_score,callback_metadata=callback_metadata,capture_traces=capture_traces,@@ -231,7 +234,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):program=program,dataset=batch,metric=self.metric_fn,- num_threads=self.num_threads,+ num_threads=num_threads,raise_on_error=False,capture_failed_parses=True,failure_score=self.failure_score,@@ -255,7 +258,7 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):evaluator = Evaluate(devset=batch,metric=self.metric_fn,- num_threads=self.num_threads,+ num_threads=num_threads,return_all_scores=True,failure_score=self.failure_score,provide_traceback=True,@@ -268,6 +271,28 @@ class DspyAdapter(GEPAAdapter[Example, TraceData, Prediction]):scores = [s["score"] if hasattr(s, "score") else s for s in scores]return EvaluationBatch(outputs=outputs, scores=scores, trajectories=None)+ def batch_evaluate(self, items, *, capture_traces=True):+ total_threads = self.num_threads or dspy.settings.num_threads+ candidate_workers = min(len(items), total_threads) or 1+ threads_per_candidate, extra_threads = divmod(total_threads, candidate_workers)++ def evaluate(item):+ context, (candidate, batch), num_threads = item+ return context.run(+ self.evaluate,+ batch,+ candidate,+ capture_traces=capture_traces,+ num_threads=num_threads,+ )++ work = [+ (copy_context(), item, threads_per_candidate + (index < extra_threads))+ for index, item in enumerate(items)+ ]+ with ThreadPoolExecutor(max_workers=candidate_workers) as executor:+ return list(executor.map(evaluate, work))+def get_adapter_state(self) -> dict[str, Any]:return {"rng_state": self.rng.getstate()}diff --git a/tests/teleprompt/test_gepa.py b/tests/teleprompt/test_gepa.pyindex b940a3a8a..2999aa18d 100644--- a/tests/teleprompt/test_gepa.py+++ b/tests/teleprompt/test_gepa.py@@ -661,3 +661,43 @@ def test_adapter_state_round_trips_rng():adapter.rng.random()adapter.set_adapter_state(state)assert adapter.rng.random() == expected+++def test_batch_evaluate_is_parallel_and_preserves_context():+ from gepa import EvaluationBatch++ from dspy.teleprompt.gepa.gepa_utils import DspyAdapter+ from dspy.utils.callback_context import ACTIVE_CALL_ID++ adapter = DspyAdapter(SimpleModule("input -> output"), simple_metric, {}, num_threads=4)+ barrier = threading.Barrier(2)+ trace_modes = []+ thread_budgets = []++ def evaluate(batch, candidate, capture_traces=False, num_threads=None):+ if capture_traces:+ barrier.wait(timeout=1)+ trace_modes.append(capture_traces)+ thread_budgets.append(num_threads)+ return EvaluationBatch(outputs=[(candidate, dspy.settings.lm, ACTIVE_CALL_ID.get())], scores=[1.0])++ adapter.evaluate = evaluate+ lm = DummyLM([])+ token = ACTIVE_CALL_ID.set("parent")+ try:+ with dspy.context(lm=lm):+ results = adapter.batch_evaluate([("first", []), ("second", [])])+ finally:+ ACTIVE_CALL_ID.reset(token)++ assert [result.outputs[0] for result in results] == [("first", lm, "parent"), ("second", lm, "parent")]++ adapter.batch_evaluate([("first", [])], capture_traces=False)+ assert trace_modes == [True, True, False]+ assert thread_budgets == [2, 2, 4]++ adapter.num_threads = 8+ adapter.batch_evaluate([("first", []), ("second", []), ("third", [])], capture_traces=False)+ assert trace_modes == [True, True, False, False, False, False]+ assert sorted(thread_budgets[-3:]) == [2, 3, 3]+ assert sum(thread_budgets[-3:]) == 8