Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Move num_threads into global settings (#8071)

TomuHirata08dc9b77f94d
diff --git a/dspy/dsp/utils/settings.py b/dspy/dsp/utils/settings.py
index cc3262b6f..983927f33 100644
--- a/dspy/dsp/utils/settings.py
+++ b/dspy/dsp/utils/settings.py
@@ -25,6 +25,7 @@ DEFAULT_CONFIG = dotdict(
caller_predict=None,
stream_listeners=[],
provide_traceback=False, # Whether to include traceback information in error logs.
+ num_threads=8, # Number of threads to use for parallel processing.
)
# Global base configuration and owner tracking
diff --git a/dspy/evaluate/evaluate.py b/dspy/evaluate/evaluate.py
index e03956d75..a4ed0b2f8 100644
--- a/dspy/evaluate/evaluate.py
+++ b/dspy/evaluate/evaluate.py
@@ -52,7 +52,7 @@ class Evaluate:
*,
devset: List["dspy.Example"],
metric: Optional[Callable] = None,
- num_threads: int = 1,
+ num_threads: Optional[int] = None,
display_progress: bool = False,
display_table: Union[bool, int] = False,
max_errors: int = 5,
@@ -66,7 +66,7 @@ class Evaluate:
Args:
devset (List[dspy.Example]): the evaluation dataset.
metric (Callable): The metric function to use for evaluation.
- num_threads (int): The number of threads to use for parallel evaluation.
+ num_threads (Optional[int]): The number of threads to use for parallel evaluation.
display_progress (bool): Whether to display progress during evaluation.
display_table (Union[bool, int]): Whether to display the evaluation results in a table.
If a number is passed, the evaluation results will be truncated to that number before displayed.
@@ -105,7 +105,7 @@ class Evaluate:
program (dspy.Module): The DSPy program to evaluate.
metric (Callable): The metric function to use for evaluation. if not provided, use `self.metric`.
devset (List[dspy.Example]): the evaluation dataset. if not provided, use `self.devset`.
- num_threads (int): The number of threads to use for parallel evaluation. if not provided, use
+ num_threads (Optional[int]): The number of threads to use for parallel evaluation. if not provided, use
`self.num_threads`.
display_progress (bool): Whether to display progress during evaluation. if not provided, use
`self.display_progress`.
diff --git a/dspy/predict/parallel.py b/dspy/predict/parallel.py
index 6b0c35305..03a423524 100644
--- a/dspy/predict/parallel.py
+++ b/dspy/predict/parallel.py
@@ -3,12 +3,13 @@ from typing import Any, List, Tuple, Optional
from dspy.primitives.example import Example
from dspy.utils.parallelizer import ParallelExecutor
+from dspy.dsp.utils.settings import settings
class Parallel:
def __init__(
self,
- num_threads: int = 32,
+ num_threads: Optional[int] = None,
max_errors: int = 10,
access_examples: bool = True,
return_failed_examples: bool = False,
@@ -16,7 +17,7 @@ class Parallel:
disable_progress_bar: bool = False,
):
super().__init__()
- self.num_threads = num_threads
+ self.num_threads = num_threads or settings.num_threads
self.max_errors = max_errors
self.access_examples = access_examples
self.return_failed_examples = return_failed_examples
@@ -29,7 +30,7 @@ class Parallel:
self.failed_examples = []
self.exceptions = []
- def forward(self, exec_pairs: List[Tuple[Any, Example]], num_threads: int = None) -> List[Any]:
+ def forward(self, exec_pairs: List[Tuple[Any, Example]], num_threads: Optional[int] = None) -> List[Any]:
num_threads = num_threads if num_threads is not None else self.num_threads
executor = ParallelExecutor(
diff --git a/dspy/primitives/program.py b/dspy/primitives/program.py
index 523df78ed..a5f88f17a 100644
--- a/dspy/primitives/program.py
+++ b/dspy/primitives/program.py
@@ -93,7 +93,7 @@ class Module(BaseModule, metaclass=ProgramMeta):
def batch(
self,
examples,
- num_threads: int = 32,
+ num_threads: Optional[int] = None,
max_errors: int = 10,
return_failed_examples: bool = False,
provide_traceback: Optional[bool] = None,
diff --git a/dspy/teleprompt/avatar_optimizer.py b/dspy/teleprompt/avatar_optimizer.py
index c41c6bfe5..43fa1d57b 100644
--- a/dspy/teleprompt/avatar_optimizer.py
+++ b/dspy/teleprompt/avatar_optimizer.py
@@ -120,10 +120,11 @@ class AvatarOptimizer(Teleprompter):
return 0
- def thread_safe_evaluator(self, devset, actor, return_outputs=False, num_threads=60):
+ def thread_safe_evaluator(self, devset, actor, return_outputs=False, num_threads=None):
total_score = 0
total_examples = len(devset)
results = []
+ num_threads = num_threads or dspy.settings.num_threads
with ThreadPoolExecutor(max_workers=num_threads) as executor:
futures = [executor.submit(self.process_example, actor, example, return_outputs) for example in devset]
diff --git a/dspy/teleprompt/bootstrap_finetune.py b/dspy/teleprompt/bootstrap_finetune.py
index 6e5bf569a..129a8f793 100644
--- a/dspy/teleprompt/bootstrap_finetune.py
+++ b/dspy/teleprompt/bootstrap_finetune.py
@@ -41,7 +41,7 @@ class BootstrapFinetune(FinetuneTeleprompter):
train_kwargs: Optional[Union[Dict[str, Any], Dict[LM, Dict[str, Any]]]] = None,
adapter: Optional[Union[Adapter, Dict[LM, Adapter]]] = None,
exclude_demos: bool = False,
- num_threads: int = 6,
+ num_threads: Optional[int] = None,
):
# TODO(feature): Inputs train_kwargs (a dict with string keys) and
# adapter (Adapter) can depend on the LM they are used with. We are
@@ -71,10 +71,11 @@ class BootstrapFinetune(FinetuneTeleprompter):
teachers = teacher if isinstance(teacher, list) else [teacher]
teachers = [prepare_teacher(student, t) for t in teachers]
+ num_threads = self.num_threads or dspy.settings.num_threads
for t in teachers:
set_missing_predictor_lms(t)
trace_data += bootstrap_trace_data(
- program=t, dataset=trainset, metric=self.metric, num_threads=self.num_threads
+ program=t, dataset=trainset, metric=self.metric, num_threads=num_threads
)
logger.info("Preparing the train data...")
@@ -98,11 +99,11 @@ class BootstrapFinetune(FinetuneTeleprompter):
logger.info("Starting LM fine-tuning...")
# TODO(feature): We could run batches of fine-tuning jobs in sequence
# to avoid exceeding the number of threads.
- if len(key_to_data) > self.num_threads:
+ if len(key_to_data) > num_threads:
raise ValueError(
"BootstrapFinetune requires `num_threads` to be bigger than or equal to the number of fine-tuning "
f"jobs. There are {len(key_to_data)} fine-tuning jobs to start, but the number of threads is: "
- f"{self.num_threads}! If the `multitask` flag is set to False, the number of fine-tuning jobs will "
+ f"{num_threads}! If the `multitask` flag is set to False, the number of fine-tuning jobs will "
"be equal to the number of predictors in the student program. If the `multitask` flag is set to True, "
"the number of fine-tuning jobs will be equal to: 1 if there is only a context LM, or the number of "
"unique LMs attached to the predictors in the student program. In any case, the number of fine-tuning "
@@ -203,7 +204,7 @@ def bootstrap_trace_data(
program: Program,
dataset: List[Example],
metric: Optional[Callable] = None,
- num_threads=6,
+ num_threads: Optional[int] = None,
) -> List[Dict[str, Any]]:
# Return a list of dicts with the following keys: example_ind, example, prediction, trace, and score
# (if metric != None)
diff --git a/dspy/teleprompt/infer_rules.py b/dspy/teleprompt/infer_rules.py
index 2eb7af63a..7d4d7e620 100644
--- a/dspy/teleprompt/infer_rules.py
+++ b/dspy/teleprompt/infer_rules.py
@@ -11,7 +11,7 @@ logger = logging.getLogger(__name__)
class InferRules(BootstrapFewShot):
- def __init__(self, num_candidates=10, num_rules=10, num_threads=8, teacher_settings=None, **kwargs):
+ def __init__(self, num_candidates=10, num_rules=10, num_threads=None, teacher_settings=None, **kwargs):
super().__init__(teacher_settings=teacher_settings, **kwargs)
self.num_candidates = num_candidates
diff --git a/dspy/teleprompt/mipro_optimizer_v2.py b/dspy/teleprompt/mipro_optimizer_v2.py
index 375eb6e3e..8aa48fe90 100644
--- a/dspy/teleprompt/mipro_optimizer_v2.py
+++ b/dspy/teleprompt/mipro_optimizer_v2.py
@@ -55,7 +55,7 @@ class MIPROv2(Teleprompter):
max_labeled_demos: int = 4,
auto: Optional[Literal["light", "medium", "heavy"]] = "medium",
num_candidates: int = 10,
- num_threads: int = 6,
+ num_threads: Optional[int] = None,
max_errors: int = 10,
seed: int = 9,
init_temperature: float = 0.5,
diff --git a/dspy/teleprompt/random_search.py b/dspy/teleprompt/random_search.py
index c054b1058..caba1474b 100644
--- a/dspy/teleprompt/random_search.py
+++ b/dspy/teleprompt/random_search.py
@@ -32,7 +32,7 @@ class BootstrapFewShotWithRandomSearch(Teleprompter):
max_labeled_demos=16,
max_rounds=1,
num_candidate_programs=16,
- num_threads=6,
+ num_threads=None,
max_errors=10,
stop_at_score=None,
metric_threshold=None,
diff --git a/dspy/teleprompt/simba.py b/dspy/teleprompt/simba.py
index 8554d0b1e..c7942a3a9 100644
--- a/dspy/teleprompt/simba.py
+++ b/dspy/teleprompt/simba.py
@@ -21,7 +21,7 @@ class SIMBA(Teleprompter):
max_steps=8,
max_demos=4,
demo_input_field_maxlen=100_000,
- num_threads=16,
+ num_threads=None,
temperature_for_sampling=0.2,
temperature_for_candidates=0.2,
):
diff --git a/dspy/teleprompt/teleprompt_optuna.py b/dspy/teleprompt/teleprompt_optuna.py
index 2922daf17..b82d122dc 100644
--- a/dspy/teleprompt/teleprompt_optuna.py
+++ b/dspy/teleprompt/teleprompt_optuna.py
@@ -15,14 +15,12 @@ class BootstrapFewShotWithOptuna(Teleprompter):
max_labeled_demos=16,
max_rounds=1,
num_candidate_programs=16,
- num_threads=6,
+ num_threads=None,
):
self.metric = metric
self.teacher_settings = teacher_settings
self.max_rounds = max_rounds
-
self.num_threads = num_threads
-
self.min_num_samples = 1
self.max_num_samples = max_bootstrapped_demos
self.num_candidate_sets = num_candidate_programs
diff --git a/dspy/utils/parallelizer.py b/dspy/utils/parallelizer.py
index ded549d21..99c9a39c4 100644
--- a/dspy/utils/parallelizer.py
+++ b/dspy/utils/parallelizer.py
@@ -16,7 +16,7 @@ logger = logging.getLogger(__name__)
class ParallelExecutor:
def __init__(
self,
- num_threads,
+ num_threads=None,
max_errors=5,
disable_progress_bar=False,
provide_traceback=None,
@@ -30,7 +30,7 @@ class ParallelExecutor:
"""
from dspy.dsp.utils.settings import settings
- self.num_threads = num_threads
+ self.num_threads = num_threads or settings.num_threads
self.max_errors = max_errors
self.disable_progress_bar = disable_progress_bar
self.provide_traceback = provide_traceback if provide_traceback is not None else settings.provide_traceback
diff --git a/tests/evaluate/test_evaluate.py b/tests/evaluate/test_evaluate.py
index a1b47c386..44e0cec75 100644
--- a/tests/evaluate/test_evaluate.py
+++ b/tests/evaluate/test_evaluate.py
@@ -30,7 +30,7 @@ def test_evaluate_initialization():
)
assert ev.devset == devset
assert ev.metric == answer_exact_match
- assert ev.num_threads == len(devset)
+ assert ev.num_threads is None
assert ev.display_progress == False