DSPy: The framework for programming—not prompting—language models
Python
Switch settings from contextvar to thread local storage (for Colab) (#1860)
Omar Khattab74b19c8ac885
diff --git a/dsp/utils/settings.py b/dsp/utils/settings.pyindex 4ffbd23d9..16ae6f93b 100644--- a/dsp/utils/settings.py+++ b/dsp/utils/settings.py@@ -1,8 +1,6 @@import copyimport threading-from contextlib import contextmanager-from contextvars import ContextVarfrom dsp.utils.utils import dotdictDEFAULT_CONFIG = dotdict(@@ -31,8 +29,14 @@ DEFAULT_CONFIG = dotdict(# Global base configurationmain_thread_config = copy.deepcopy(DEFAULT_CONFIG)-# Initialize the context variable with an empty dict as default-dspy_ctx_overrides = ContextVar('dspy_ctx_overrides', default=dotdict())++class ThreadLocalOverrides(threading.local):+ def __init__(self):+ self.overrides = dotdict() # Initialize thread-local overrides+++# Create the thread-local storage+thread_local_overrides = ThreadLocalOverrides()class Settings:@@ -53,7 +57,7 @@ class Settings:return cls._instancedef __getattr__(self, name):- overrides = dspy_ctx_overrides.get()+ overrides = getattr(thread_local_overrides, 'overrides', dotdict())if name in overrides:return overrides[name]elif name in main_thread_config:@@ -76,7 +80,7 @@ class Settings:self.__setattr__(key, value)def __contains__(self, key):- overrides = dspy_ctx_overrides.get()+ overrides = getattr(thread_local_overrides, 'overrides', dotdict())return key in overrides or key in main_thread_configdef get(self, key, default=None):@@ -86,45 +90,49 @@ class Settings:return defaultdef copy(self):- overrides = dspy_ctx_overrides.get()+ overrides = getattr(thread_local_overrides, 'overrides', dotdict())return dotdict({**main_thread_config, **overrides})@propertydef config(self):config = self.copy()- del config['lock']+ if 'lock' in config:+ del config['lock']return config# Configuration methods- def configure(self, return_token=False, **kwargs):+ def configure(self, **kwargs):global main_thread_config- overrides = dspy_ctx_overrides.get()- new_overrides = dotdict({**copy.deepcopy(DEFAULT_CONFIG), **main_thread_config, **overrides, **kwargs})- token = dspy_ctx_overrides.set(new_overrides)++ # Get or initialize thread-local overrides+ overrides = getattr(thread_local_overrides, 'overrides', dotdict())+ thread_local_overrides.overrides = dotdict(+ {**copy.deepcopy(DEFAULT_CONFIG), **main_thread_config, **overrides, **kwargs}+ )# Update main_thread_config, in the main thread onlyif threading.current_thread() is threading.main_thread():- main_thread_config = new_overrides-- if return_token:- return token+ main_thread_config = thread_local_overrides.overrides@contextmanagerdef context(self, **kwargs):"""Context manager for temporary configuration changes."""- token = self.configure(return_token=True, **kwargs)+ global main_thread_config+ original_overrides = getattr(thread_local_overrides, 'overrides', dotdict()).copy()+ original_main_thread_config = main_thread_config.copy()++ self.configure(**kwargs)try:yieldfinally:- dspy_ctx_overrides.reset(token)+ thread_local_overrides.overrides = original_overridesif threading.current_thread() is threading.main_thread():- global main_thread_config- main_thread_config = dotdict({**copy.deepcopy(DEFAULT_CONFIG), **dspy_ctx_overrides.get()})+ main_thread_config = original_main_thread_configdef __repr__(self):- overrides = dspy_ctx_overrides.get()+ overrides = getattr(thread_local_overrides, 'overrides', dotdict())combined_config = {**main_thread_config, **overrides}return repr(combined_config)diff --git a/dspy/utils/parallelizer.py b/dspy/utils/parallelizer.pyindex c6b5f3d5f..f40ee98d4 100644--- a/dspy/utils/parallelizer.py+++ b/dspy/utils/parallelizer.py@@ -5,14 +5,11 @@ import loggingimport threadingimport tracebackimport contextlib--from contextvars import copy_contextfrom tqdm.contrib.logging import logging_redirect_tqdmfrom concurrent.futures import ThreadPoolExecutor, as_completedlogger = logging.getLogger(__name__)-class ParallelExecutor:def __init__(self,@@ -80,10 +77,16 @@ class ParallelExecutor:if self.cancel_jobs.is_set():break- # Create an isolated context for each task- task_ctx = copy_context()- result = task_ctx.run(function, item)- results.append(result)+ # Create an isolated context for each task using thread-local overrides+ from dsp.utils.settings import thread_local_overrides+ original_overrides = thread_local_overrides.overrides+ thread_local_overrides.overrides = thread_local_overrides.overrides.copy()++ try:+ result = function(item)+ results.append(result)+ finally:+ thread_local_overrides.overrides = original_overridesif self.compare_results:# Assumes score is the last element of the result tuple@@ -137,18 +140,30 @@ class ParallelExecutor:# If not in the main thread, skip setting signal handlersyield- def cancellable_function(index_item):+ def cancellable_function(parent_overrides, index_item):index, item = index_itemif self.cancel_jobs.is_set():return index, job_cancelled- return index, function(item)++ # Create an isolated context for each task using thread-local overrides+ from dsp.utils.settings import thread_local_overrides+ original_overrides = thread_local_overrides.overrides+ thread_local_overrides.overrides = parent_overrides.copy()++ try:+ return index, function(item)+ finally:+ thread_local_overrides.overrides = original_overrideswith ThreadPoolExecutor(max_workers=self.num_threads) as executor, interrupt_handler_manager():+ # Capture the parent thread's overrides+ from dsp.utils.settings import thread_local_overrides+ parent_overrides = thread_local_overrides.overrides.copy()+futures = {}for pair in enumerate(data):- # Capture the context for each task- task_ctx = copy_context()- future = executor.submit(task_ctx.run, cancellable_function, pair)+ # Pass the parent thread's overrides to each thread+ future = executor.submit(cancellable_function, parent_overrides, pair)futures[future] = pairpbar = tqdm.tqdm(