Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Add support for native parallel execution in DSPy (#1690)

Herumb Shandilya3d36efb19f15
diff --git a/dspy/evaluate/evaluate.py b/dspy/evaluate/evaluate.py
index a8af70373..6b74645a8 100644
--- a/dspy/evaluate/evaluate.py
+++ b/dspy/evaluate/evaluate.py
@@ -1,24 +1,20 @@
-import contextlib
import logging
-import signal
-import sys
-import threading
-import traceback
+import tqdm
import types
from typing import Any
import pandas as pd
-import tqdm
-from tqdm.contrib.logging import logging_redirect_tqdm
+
import dspy
+from dspy.utils.parallelizer import ParallelExecutor
try:
from IPython.display import HTML
from IPython.display import display as display
except ImportError:
-
+
def display(obj: Any):
"""
Display the specified Python object in the console.
@@ -37,11 +33,11 @@ except ImportError:
return x
-from concurrent.futures import ThreadPoolExecutor, as_completed
-
# TODO: Counting failures and having a max_failure count. When that is exceeded (also just at the end),
# we print the number of failures, the first N examples that failed, and the first N exceptions raised.
+logger = logging.getLogger(__name__)
+
logger = logging.getLogger(__name__)
@@ -66,86 +62,10 @@ class Evaluate:
self.display_progress = display_progress
self.display_table = display_table
self.max_errors = max_errors
- self.error_count = 0
- self.error_lock = threading.Lock()
- self.cancel_jobs = threading.Event()
self.return_all_scores = return_all_scores
self.return_outputs = return_outputs
self.provide_traceback = provide_traceback
- def _execute_single_thread(self, wrapped_program, devset, display_progress):
- ncorrect = 0
- ntotal = 0
- reordered_devset = []
-
- pbar = tqdm.tqdm(total=len(devset), dynamic_ncols=True, disable=not display_progress, file=sys.stdout)
- for idx, arg in devset:
- with logging_redirect_tqdm():
- example_idx, example, prediction, score = wrapped_program(idx, arg)
- reordered_devset.append((example_idx, example, prediction, score))
- ncorrect += score
- ntotal += 1
- self._update_progress(pbar, ncorrect, ntotal)
-
- pbar.close()
-
- return reordered_devset, ncorrect, ntotal
-
- def _execute_multi_thread(self, wrapped_program, devset, num_threads, display_progress):
- ncorrect = 0
- ntotal = 0
- reordered_devset = []
- job_cancelled = "cancelled"
-
- # context manger to handle sigint
- @contextlib.contextmanager
- def interrupt_handler_manager():
- """Sets the cancel_jobs event when a SIGINT is received."""
- default_handler = signal.getsignal(signal.SIGINT)
-
- def interrupt_handler(sig, frame):
- self.cancel_jobs.set()
- logger.warning("Received SIGINT. Cancelling evaluation.")
- default_handler(sig, frame)
-
- signal.signal(signal.SIGINT, interrupt_handler)
- yield
- # reset to the default handler
- signal.signal(signal.SIGINT, default_handler)
-
- def cancellable_wrapped_program(idx, arg):
- # If the cancel_jobs event is set, return the cancelled_job literal
- if self.cancel_jobs.is_set():
- return None, None, job_cancelled, None
- return wrapped_program(idx, arg)
-
- with ThreadPoolExecutor(max_workers=num_threads) as executor, interrupt_handler_manager():
- futures = {executor.submit(cancellable_wrapped_program, idx, arg) for idx, arg in devset}
- pbar = tqdm.tqdm(total=len(devset), dynamic_ncols=True, disable=not display_progress)
-
- for future in as_completed(futures):
- example_idx, example, prediction, score = future.result()
-
- # use the cancelled_job literal to check if the job was cancelled - use "is" not "=="
- # in case the prediction is "cancelled" for some reason.
- if prediction is job_cancelled:
- continue
-
- reordered_devset.append((example_idx, example, prediction, score))
- ncorrect += score
- ntotal += 1
- self._update_progress(pbar, ncorrect, ntotal)
- pbar.close()
-
- if self.cancel_jobs.is_set():
- logger.warning("Evaluation was cancelled. The results may be incomplete.")
- raise KeyboardInterrupt
-
- return reordered_devset, ncorrect, ntotal
-
- def _update_progress(self, pbar, ncorrect, ntotal):
- pbar.set_description(f"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)})")
- pbar.update()
def __call__(
self,
@@ -165,62 +85,43 @@ class Evaluate:
display_table = display_table if display_table is not None else self.display_table
return_all_scores = return_all_scores if return_all_scores is not None else self.return_all_scores
return_outputs = return_outputs if return_outputs is not None else self.return_outputs
- results = []
- def wrapped_program(example_idx, example):
- # NOTE: TODO: Won't work if threads create threads!
- thread_stacks = dspy.settings.stack_by_thread
- creating_new_thread = threading.get_ident() not in thread_stacks
- if creating_new_thread:
- thread_stacks[threading.get_ident()] = list(dspy.settings.main_stack)
+ devset = list(enumerate(devset))
+ tqdm.tqdm._instances.clear()
+ executor = ParallelExecutor(
+ num_threads=num_threads,
+ disable_progress_bar=not display_progress,
+ max_errors=self.max_errors,
+ provide_traceback=self.provide_traceback,
+ compare_results=True,
+ )
+
+ def process_item(item):
try:
+ example_idx, example = item
prediction = program(**example.inputs())
- score = metric(
- example,
- prediction,
- ) # FIXME: TODO: What's the right order? Maybe force name-based kwargs!
+ score = metric(example, prediction)
- # increment assert and suggest failures to program's attributes
+ # Increment assert and suggest failures to program's attributes
if hasattr(program, "_assert_failures"):
program._assert_failures += dspy.settings.get("assert_failures")
if hasattr(program, "_suggest_failures"):
program._suggest_failures += dspy.settings.get("suggest_failures")
return example_idx, example, prediction, score
- except Exception as e:
- with self.error_lock:
- self.error_count += 1
- current_error_count = self.error_count
- if current_error_count >= self.max_errors:
- raise e
-
- if self.provide_traceback:
- logger.error(
- f"Error for example in dev set: \t\t {e}\n\twith inputs:\n\t\t{example.inputs()}\n\nStack trace:\n\t{traceback.format_exc()}"
- )
- else:
- logger.error(
- f"Error for example in dev set: \t\t {e}. Set `provide_traceback=True` to see the stack trace."
- )
-
+ except Exception:
return example_idx, example, {}, 0.0
- finally:
- if creating_new_thread:
- del thread_stacks[threading.get_ident()]
- devset = list(enumerate(devset))
- tqdm.tqdm._instances.clear()
+ results = executor.execute(process_item, devset)
+ reordered_devset = [r for r in results if r is not None]
- if num_threads == 1:
- reordered_devset, ncorrect, ntotal = self._execute_single_thread(wrapped_program, devset, display_progress)
- else:
- reordered_devset, ncorrect, ntotal = self._execute_multi_thread(
- wrapped_program,
- devset,
- num_threads,
- display_progress,
- )
+ ncorrect = sum(score for _, _, _, score in reordered_devset)
+ ntotal = len(reordered_devset)
+
+ if ntotal == 0:
+ logger.warning("No valid results to compute metrics.")
+ return 0.0
logger.info(f"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)")
diff --git a/dspy/predict/__init__.py b/dspy/predict/__init__.py
index cf6315f52..d889d8549 100644
--- a/dspy/predict/__init__.py
+++ b/dspy/predict/__init__.py
@@ -6,4 +6,5 @@ from .multi_chain_comparison import MultiChainComparison
from .predict import Predict
from .program_of_thought import ProgramOfThought
from .react import ReAct
-from .retry import Retry
\ No newline at end of file
+from .retry import Retry
+from .parallel import Parallel
\ No newline at end of file
diff --git a/dspy/predict/parallel.py b/dspy/predict/parallel.py
new file mode 100644
index 000000000..88fb37679
--- /dev/null
+++ b/dspy/predict/parallel.py
@@ -0,0 +1,65 @@
+import threading
+
+from typing import Tuple, List, Any
+
+from ..primitives.example import Example
+from ..utils.parallelizer import ParallelExecutor
+
+
+class Parallel:
+ def __init__(
+ self,
+ num_threads: int = 32,
+ max_errors: int = 10,
+ return_failed_examples: bool = False,
+ provide_traceback: bool = False,
+ disable_progress_bar: bool = False,
+ ):
+ super().__init__()
+ self.num_threads = num_threads
+ self.max_errors = max_errors
+ self.return_failed_examples = return_failed_examples
+ self.provide_traceback = provide_traceback
+ self.disable_progress_bar = disable_progress_bar
+
+ self.error_count = 0
+ self.error_lock = threading.Lock()
+ self.cancel_jobs = threading.Event()
+ self.failed_examples = []
+ self.exceptions = []
+
+
+ def forward(self, exec_pairs: List[Tuple[Any, Example]], num_threads: int = None) -> List[Any]:
+ num_threads = num_threads if num_threads is not None else self.num_threads
+
+ executor = ParallelExecutor(
+ num_threads=num_threads,
+ max_errors=self.max_errors,
+ provide_traceback=self.provide_traceback,
+ disable_progress_bar=self.disable_progress_bar,
+ )
+
+ def process_pair(pair):
+ module, example = pair
+
+ if isinstance(example, Example):
+ result = module(**example.inputs())
+ elif isinstance(example, dict):
+ result = module(**example)
+ elif isinstance(example, list) and module.__class__.__name__ == "Parallel":
+ result = module(example)
+ elif isinstance(example, tuple):
+ result = module(*example)
+ return result
+
+ # Execute the processing function over the execution pairs
+ results = executor.execute(process_pair, exec_pairs)
+
+ if self.return_failed_examples:
+ return results, self.failed_examples, self.exceptions
+ else:
+ return results
+
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ return self.forward(*args, **kwargs)
diff --git a/dspy/primitives/program.py b/dspy/primitives/program.py
index eb43af38b..a8b2d1346 100644
--- a/dspy/primitives/program.py
+++ b/dspy/primitives/program.py
@@ -2,6 +2,7 @@ from dspy.utils.callback import with_callbacks
import magicattr
import dspy
+from dspy.predict.parallel import Parallel
from dspy.primitives.assertions import *
from dspy.primitives.module import BaseModule
@@ -94,6 +95,45 @@ class Module(BaseModule, metaclass=ProgramMeta):
# return new_copy
+ def batch(
+ self,
+ examples,
+ num_threads: int = 32,
+ max_errors: int = 10,
+ return_failed_examples: bool = False,
+ provide_traceback: bool = False,
+ disable_progress_bar: bool = False,
+ ) -> Any:
+ """
+ Processes a list of dspy.Example instances in parallel using the Parallel module.
+
+ :param examples: List of dspy.Example instances to process.
+ :param batch_size: Number of threads to use for parallel processing.
+ :param max_errors: Maximum number of errors allowed before stopping execution.
+ :param return_failed_examples: Whether to return failed examples and exceptions.
+ :param provide_traceback: Whether to include traceback information in error logs.
+ :return: List of results, and optionally failed examples and exceptions.
+ """
+ # Create a list of execution pairs (self, example)
+ exec_pairs = [(self, example.inputs()) for example in examples]
+
+ # Create an instance of Parallel
+ parallel_executor = Parallel(
+ num_threads=num_threads,
+ max_errors=max_errors,
+ return_failed_examples=return_failed_examples,
+ provide_traceback=provide_traceback,
+ disable_progress_bar=disable_progress_bar,
+ )
+
+ # Execute the forward method of Parallel
+ if return_failed_examples:
+ results, failed_examples, exceptions = parallel_executor.forward(exec_pairs)
+ return results, failed_examples, exceptions
+ else:
+ results = parallel_executor.forward(exec_pairs)
+ return results
+
def set_attribute_by_name(obj, name, value):
magicattr.set(obj, name, value)
diff --git a/dspy/utils/parallelizer.py b/dspy/utils/parallelizer.py
new file mode 100644
index 000000000..0437b0031
--- /dev/null
+++ b/dspy/utils/parallelizer.py
@@ -0,0 +1,175 @@
+import logging
+import sys
+import tqdm
+import dspy
+import signal
+import threading
+import traceback
+import contextlib
+
+from tqdm.contrib.logging import logging_redirect_tqdm
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+
+logger = logging.getLogger(__name__)
+
+
+class ParallelExecutor:
+ def __init__(
+ self,
+ num_threads,
+ max_errors=5,
+ disable_progress_bar=False,
+ provide_traceback=False,
+ compare_results=False,
+ ):
+ self.num_threads = num_threads
+ self.disable_progress_bar = disable_progress_bar
+ self.max_errors = max_errors
+ self.provide_traceback = provide_traceback
+ self.compare_results = compare_results
+
+ self.error_count = 0
+ self.error_lock = threading.Lock()
+ self.cancel_jobs = threading.Event()
+
+
+ def execute(self, function, data):
+ wrapped_function = self._wrap_function(function)
+ if self.num_threads == 1:
+ return self._execute_single_thread(wrapped_function, data)
+ else:
+ return self._execute_multi_thread(wrapped_function, data)
+
+
+ def _wrap_function(self, function):
+ # Wrap the function with threading context and error handling
+ def wrapped(item, parent_id=None):
+ thread_stacks = dspy.settings.stack_by_thread
+ current_thread_id = threading.get_ident()
+
+ creating_new_thread = current_thread_id not in thread_stacks
+
+ if creating_new_thread:
+ # If we have a parent thread ID, copy its stack
+ if parent_id and parent_id in thread_stacks:
+ thread_stacks[current_thread_id] = list(thread_stacks[parent_id])
+ else:
+ thread_stacks[current_thread_id] = list(dspy.settings.main_stack)
+
+ try:
+ return function(item)
+ except Exception as e:
+ with self.error_lock:
+ self.error_count += 1
+ current_error_count = self.error_count
+ if current_error_count >= self.max_errors:
+ self.cancel_jobs.set()
+ raise e
+ if self.provide_traceback:
+ logger.error(
+ f"Error processing item {item}: {e}\nStack trace:\n{traceback.format_exc()}"
+ )
+ else:
+ logger.error(
+ f"Error processing item {item}: {e}. Set `provide_traceback=True` to see the stack trace."
+ )
+ return None
+ finally:
+ if creating_new_thread:
+ del thread_stacks[threading.get_ident()]
+ return wrapped
+
+
+ def _execute_single_thread(self, function, data):
+ results = []
+ pbar = tqdm.tqdm(
+ total=len(data),
+ dynamic_ncols=True,
+ disable=self.disable_progress_bar,
+ file=sys.stdout,
+ )
+ for item in data:
+ with logging_redirect_tqdm():
+ if self.cancel_jobs.is_set():
+ break
+ result = function(item)
+ results.append(result)
+ if self.compare_results:
+ # Assumes score is the last element of the result tuple
+ self._update_progress(pbar, sum([r[-1] for r in results if r is not None]), len([r for r in data if r is not None]))
+ else:
+ self._update_progress(pbar, len(results), len(data))
+ pbar.close()
+ if self.cancel_jobs.is_set():
+ logger.warning("Execution was cancelled due to errors.")
+ raise Exception("Execution was cancelled due to errors.")
+ return results
+
+
+ def _update_progress(self, pbar, nresults, ntotal):
+ if self.compare_results:
+ pbar.set_description(f"Average Metric: {nresults:.2f} / {ntotal} ({round(100 * nresults / ntotal, 1) if ntotal > 0 else 0}%)")
+ else:
+ pbar.set_description(f"Processed {nresults} / {ntotal} examples")
+ pbar.update()
+
+
+ def _execute_multi_thread(self, function, data):
+ results = [None] * len(data) # Pre-allocate results list to maintain order
+ job_cancelled = "cancelled"
+
+ @contextlib.contextmanager
+ def interrupt_handler_manager():
+ """Sets the cancel_jobs event when a SIGINT is received, only in the main thread."""
+ if threading.current_thread() is threading.main_thread():
+ default_handler = signal.getsignal(signal.SIGINT)
+
+ def interrupt_handler(sig, frame):
+ self.cancel_jobs.set()
+ logger.warning("Received SIGINT. Cancelling execution.")
+ default_handler(sig, frame)
+
+ signal.signal(signal.SIGINT, interrupt_handler)
+ try:
+ yield
+ finally:
+ signal.signal(signal.SIGINT, default_handler)
+ else:
+ # If not in the main thread, skip setting signal handlers
+ yield
+
+ def cancellable_function(index_item, parent_id=None):
+ index, item = index_item
+ if self.cancel_jobs.is_set():
+ return index, job_cancelled
+ return index, function(item, parent_id)
+
+ parent_id = threading.get_ident() if threading.current_thread() is not threading.main_thread() else None
+
+ with ThreadPoolExecutor(max_workers=self.num_threads) as executor, interrupt_handler_manager():
+ futures = {executor.submit(cancellable_function, pair, parent_id): pair for pair in enumerate(data)}
+ pbar = tqdm.tqdm(
+ total=len(data),
+ dynamic_ncols=True,
+ disable=self.disable_progress_bar,
+ file=sys.stdout,
+ )
+
+ for future in as_completed(futures):
+ index, result = future.result()
+
+ if result is job_cancelled:
+ continue
+ results[index] = result
+
+ if self.compare_results:
+ # Assumes score is the last element of the result tuple
+ self._update_progress(pbar, sum([r[-1] for r in results if r is not None]), len([r for r in results if r is not None]))
+ else:
+ self._update_progress(pbar, len([r for r in results if r is not None]), len(data))
+ pbar.close()
+ if self.cancel_jobs.is_set():
+ logger.warning("Execution was cancelled due to errors.")
+ raise Exception("Execution was cancelled due to errors.")
+ return results
diff --git a/tests/predict/test_parallel.py b/tests/predict/test_parallel.py
new file mode 100644
index 000000000..ae143fdd7
--- /dev/null
+++ b/tests/predict/test_parallel.py
@@ -0,0 +1,157 @@
+import dspy
+
+from dspy.utils.dummies import DummyLM
+
+
+def test_parallel_module():
+ lm = DummyLM([
+ {"output": "test output 1"},
+ {"output": "test output 2"},
+ {"output": "test output 3"},
+ {"output": "test output 4"},
+ {"output": "test output 5"},
+ ])
+ dspy.settings.configure(lm=lm)
+
+ class MyModule(dspy.Module):
+ def __init__(self):
+ super().__init__()
+ self.predictor = dspy.Predict("input -> output")
+ self.predictor2 = dspy.Predict("input -> output")
+
+ self.parallel = dspy.Parallel(num_threads=2)
+
+ def forward(self, input):
+ return self.parallel([
+ (self.predictor, input),
+ (self.predictor2, input),
+ (self.predictor, input),
+ (self.predictor2, input),
+ (self.predictor, input),
+ ])
+
+ output = MyModule()(dspy.Example(input="test input").with_inputs("input"))
+
+ assert output[0].output == "test output 1"
+ assert output[1].output == "test output 2"
+ assert output[2].output == "test output 3"
+ assert output[3].output == "test output 4"
+ assert output[4].output == "test output 5"
+
+
+def test_batch_module():
+ lm = DummyLM([
+ {"output": "test output 1"},
+ {"output": "test output 2"},
+ {"output": "test output 3"},
+ {"output": "test output 4"},
+ {"output": "test output 5"},
+ ])
+ res_lm = DummyLM([
+ {"output": "test output 1", "reasoning": "test reasoning 1"},
+ {"output": "test output 2", "reasoning": "test reasoning 2"},
+ {"output": "test output 3", "reasoning": "test reasoning 3"},
+ {"output": "test output 4", "reasoning": "test reasoning 4"},
+ {"output": "test output 5", "reasoning": "test reasoning 5"},
+ ])
+
+ class MyModule(dspy.Module):
+ def __init__(self):
+ super().__init__()
+ self.predictor = dspy.Predict("input -> output")
+ self.predictor2 = dspy.Predict("input -> output, reasoning")
+
+ self.parallel = dspy.Parallel(num_threads=2)
+
+ def forward(self, input):
+ dspy.settings.configure(lm=lm)
+ res1 = self.predictor.batch([input] * 5)
+
+ dspy.settings.configure(lm=res_lm)
+ res2 = self.predictor2.batch([input] * 5)
+
+ return (res1, res2)
+
+ result, reason_result = MyModule()(dspy.Example(input="test input").with_inputs("input"))
+
+ assert result[0].output == "test output 1"
+ assert result[1].output == "test output 2"
+ assert result[2].output == "test output 3"
+ assert result[3].output == "test output 4"
+ assert result[4].output == "test output 5"
+
+ assert reason_result[0].output == "test output 1"
+ assert reason_result[1].output == "test output 2"
+ assert reason_result[2].output == "test output 3"
+ assert reason_result[3].output == "test output 4"
+ assert reason_result[4].output == "test output 5"
+
+ assert reason_result[0].reasoning == "test reasoning 1"
+ assert reason_result[1].reasoning == "test reasoning 2"
+ assert reason_result[2].reasoning == "test reasoning 3"
+ assert reason_result[3].reasoning == "test reasoning 4"
+ assert reason_result[4].reasoning == "test reasoning 5"
+
+
+def test_nested_parallel_module():
+ lm = DummyLM([
+ {"output": "test output 1"},
+ {"output": "test output 2"},
+ {"output": "test output 3"},
+ {"output": "test output 4"},
+ {"output": "test output 5"},
+ ])
+ dspy.settings.configure(lm=lm)
+
+ class MyModule(dspy.Module):
+ def __init__(self):
+ super().__init__()
+ self.predictor = dspy.Predict("input -> output")
+ self.predictor2 = dspy.Predict("input -> output")
+
+ self.parallel = dspy.Parallel(num_threads=2)
+
+ def forward(self, input):
+ return self.parallel([
+ (self.predictor, input),
+ (self.predictor2, input),
+ (self.parallel, [
+ (self.predictor2, input),
+ (self.predictor, input),
+ ]),
+ ])
+
+ output = MyModule()(dspy.Example(input="test input").with_inputs("input"))
+
+ assert output[0].output == "test output 1"
+ assert output[1].output == "test output 2"
+ assert output[2][0].output == "test output 3"
+ assert output[2][1].output == "test output 4"
+
+
+def test_nested_batch_method():
+ lm = DummyLM([
+ {"output": "test output 1"},
+ {"output": "test output 2"},
+ {"output": "test output 3"},
+ {"output": "test output 4"},
+ {"output": "test output 5"},
+ ])
+ dspy.settings.configure(lm=lm)
+
+ class MyModule(dspy.Module):
+ def __init__(self):
+ super().__init__()
+ self.predictor = dspy.Predict("input -> output")
+
+ def forward(self, input):
+ res = self.predictor.batch([dspy.Example(input=input).with_inputs("input")]*2)
+
+ return res
+
+ result = MyModule().batch([dspy.Example(input="test input").with_inputs("input")]*2)
+
+ assert result[0][0].output == "test output 1"
+ assert result[0][1].output == "test output 2"
+ assert result[1][0].output == "test output 3"
+ assert result[1][1].output == "test output 4"