DSPy: The framework for programming—not prompting—language models
Python
Update LM
dilara8f0314196c40
diff --git a/dspy/clients/anyscale.py b/dspy/clients/anyscale.pyindex 02a399259..e124f601d 100644--- a/dspy/clients/anyscale.py+++ b/dspy/clients/anyscale.py@@ -7,9 +7,22 @@ from dspy import loggerfrom dspy.clients.finetune import (FinetuneJob,TrainingMethod,+ get_finetune_directory,validate_training_data)+#-------------------------------------------------------------------------------+# Variables+#-------------------------------------------------------------------------------++# List of training methods supported by AnyScale+TRAINING_METHODS_ANYSCALE = [+ TrainingMethod.SFT,+]++#-------------------------------------------------------------------------------+# Function and classes required for the fine-tune interface+#-------------------------------------------------------------------------------class FinetuneJobAnyScale(FinetuneJob):@@ -36,12 +49,11 @@ def finetune_anyscale(model: str,message_completion_pairs: List[Dict[str, str]],train_kwargs: Optional[Dict[str, Any]]=None,- launch_kwargs: Optional[Dict[str, Any]]=None,- ) -> FinetuneJob:+ ) -> str:"""Fine-tune with AnyScale."""-# Fake fine-tuninglogger.info("[Finetune] Fake fine-tuning")+ train_kwargs = train_kwargs or {}try:logger.info("[Finetune] Validate the formatting of the fine-tuning data")@@ -50,7 +62,8 @@ def finetune_anyscale(time.sleep(5)logger.info("[Finetune] Done!")- logger.info("[Finetune] Saving the data to a file") # TODO: Get parent path, keep same across all finetuning jobs+ logger.info("[Finetune] Saving the data to a file")+ finetune_parent_dir = get_finetune_directory()# We utilize message_completion_pairs heretime.sleep(1)logger.info("[Finetune] Done!")@@ -72,16 +85,8 @@ def finetune_anyscale(model = "anyscale_model" # Hardcodedtime.sleep(1)logger.info("[Finetune] Done!")-- logger.info("[Finetune] Create a DSPy LM object for the trained model")- # We utilize launch_kwargs here- lm = dspy.LM(model=model, **launch_kwargs)- time.sleep(1)- logger.info("[Finetune] Done!")- logger.info("Set the result of the FinetuningJob to the new lM")- job.set_result(lm)- logger.info("[Finetune] Done!")+ return modelexcept Exception as e:logger.error(f"[Finetune] Error: {e}")diff --git a/dspy/clients/finetune.py b/dspy/clients/finetune.pyindex f79f92356..7fa5b95af 100644--- a/dspy/clients/finetune.py+++ b/dspy/clients/finetune.py@@ -1,7 +1,25 @@from abc import ABC, abstractmethodfrom concurrent.futures import ThreadPoolExecutor, Futurefrom enum import Enum+import os+from pathlib import Pathfrom typing import List, Dict, Any, Optional+import ujson++from dspy import logger+++# TODO: Move to a centralized location with all the other environment variables+# Set the directory to save the fine-tuned models+def get_finetune_directory() -> str:+ """Get the directory to save the fine-tuned models."""+ alternative_path = os.path.join(Path.home(), '.dspy_finetune')+ # TODO: Should the parent directory be different than those used for+ # inference+ return os.environ.get('DSPY_FINETUNEDIR') or alternative_path+++FINETUNE_DIRECTORY = get_finetune_directory()class TrainingMethod(str, Enum):@@ -22,43 +40,27 @@ TRAINING_METHOD_TO_DATA_KEYS = {}-def validate_training_data(- data: List[Dict[str, Any]],- training_method: TrainingMethod- ) -> Optional[AssertionError]:- """Validate the training data based on the training method."""- # Get the required data keys for the training method- required_keys = TRAINING_METHOD_TO_DATA_KEYS[training_method]-- # Check if the training data has the required keys- for ind, data_dict in enumerate(data):- err_msg = f"The datapoint at index {ind} is missing the keys required for {training_method} training."- err_msg = f"\n Expected: {required_keys}"- err_msg = f"\n Found: {data_dict.keys()}"- assert all([key in data_dict for key in required_keys]), err_msg--class FinetuneJob(Future):def __init__(self,model: str,message_completion_pairs: List[Dict[str, str]],train_kwargs: Optional[Dict[str, Any]]=None,- launch_kwargs: Optional[Dict[str, Any]]=None,):self.model = modelself.message_completion_pairs = message_completion_pairs- self.train_kwargs = train_kwargs- self.launch_kwargs = launch_kwargs+ self.train_kwargs: Dict[str, Any] = train_kwargs or {}super().__init__()-- def __str__(self):- config = dict(++ def get_kwargs(self):+ return dict(model=self.model,+ message_completion_pairs=self.message_completion_pairs,train_kwargs=self.train_kwargs,- launch_kwargs=self.launch_kwargs,)- return f"FinetuningJob({config})"++ def __str__(self):+ return f"FinetuningJob({self.to_dict()})"def __repr__(self):return str(self)@@ -73,3 +75,29 @@ class FinetuneJob(Future):def status(self):"""Get the status of the finetune job."""raise NotImplementedError("Method `status` is not implemented.")+++def validate_training_data(+ data: List[Dict[str, Any]],+ training_method: TrainingMethod+ ) -> Optional[AssertionError]:+ """Validate the training data based on the training method."""+ # Get the required data keys for the training method+ required_keys = TRAINING_METHOD_TO_DATA_KEYS[training_method]++ # Check if the training data has the required keys+ for ind, data_dict in enumerate(data):+ err_msg = f"The datapoint at index {ind} is missing the keys required for {training_method} training."+ err_msg = f"\n Expected: {required_keys}"+ err_msg = f"\n Found: {data_dict.keys()}"+ assert all([key in data_dict for key in required_keys]), err_msg+++def save_data(data: Dict[str, str]) -> str:+ # TODO: Assign different names based on the data hash+ finetune_parent_dir = get_finetune_directory()+ data_path = os.path.join(finetune_parent_dir, "openai", "train.json")+ with open(data_path, "w") as f:+ for item in data:+ f.write(ujson.dumps(item) + "\n")+ return data_pathdiff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 8da34cc0d..280f8589a 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -3,17 +3,22 @@ import functoolsimport osfrom pathlib import Pathimport re-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Type, Unionimport ujsonfrom dspy import logger-from dspy.clients.finetune import FinetuneJob-from dspy.clients.self_hosted import is_self_hosted_model-from dspy.clients.openai import is_openai_model, finetune_openai, FinetuneJobOpenAI-from dspy.clients.anyscale import is_anyscale_model, finetune_anyscale, FinetuneJobAnyScale+from dspy.clients.finetune import FinetuneJob, TrainingMethod+from dspy.clients.self_hosted import (+ is_self_hosted_model,+ self_hosted_model_launch,+ self_hosted_model_kill,+)+DISK_CACHE_DIR = os.environ.get('DSPY_CACHEDIR') or os.path.join(Path.home(), '.dspy_cache')++try:import warningswith warnings.catch_warnings():@@ -24,8 +29,7 @@ try:litellm.telemetry = Falsefrom litellm.caching import Cache- disk_cache_dir = os.environ.get('DSPY_CACHEDIR') or os.path.join(Path.home(), '.dspy_cache')- litellm.cache = Cache(disk_cache_dir=disk_cache_dir, type="disk")+ litellm.cache = Cache(disk_cache_dir=DISK_CACHE_DIR, type="disk")except ImportError:class LitellmPlaceholder:@@ -37,19 +41,29 @@ except ImportError:#-------------------------------------------------------------------------------# LiteLLM Client#-------------------------------------------------------------------------------+class LM:- def __init__(self, model, model_type='chat', temperature=0.0, max_tokens=1000, cache=True, **kwargs):+ def __init__(self,+ model,+ model_type='chat',+ temperature=0.0,+ max_tokens=1000,+ cache=True,+ launch_kwargs=None,+ **kwargs+ ):self.model = modelself.model_type = model_typeself.cache = cacheself.kwargs = dict(temperature=temperature, max_tokens=max_tokens, **kwargs)+ self.launch_kwargs = kwargs.pop("launch_kwargs", launch_kwargs or {})self.history = []- if "o1-" in model: # TODO: This is error prone!+ # TODO: This is error prone!+ if "o1-" in model:assert max_tokens >= 5000 and temperature == 1.0, \"OpenAI's o1-* models require passing temperature=1.0 and max_tokens >= 5000 to `dspy.LM(...)`"--+def __call__(self, prompt=None, messages=None, **kwargs):# Build the request.cache = kwargs.pop("cache", self.cache)@@ -78,58 +92,48 @@ class LM:def launch(self):"""Send a request to the provider to launch the model, if needed."""if is_self_hosted_model(self.model):- self_hosted_model_launch(self)+ self_hosted_model_launch(model, self.launch_kwargs)logger.debug(f"`LM.launch()` is called for the auto-launched model {self.model} -- no action is taken.")def kill(self):"""Send a request to the provider to kill the model, if needed."""if is_self_hosted_model(self.model):- self_hosted_model_kill(self)+ self_hosted_model_kill(model, self.launch_kwargs)logger.debug(f"`LM.kill()` is called for the auto-launched model {self.model} -- no action is taken.")def finetune(self,message_completion_pairs: List[Dict[str, str]],train_kwargs: Optional[Dict[str, Any]]=None,launch_kwargs: Optional[Dict[str, Any]]=None,+ cache_finetune: bool = True,) -> FinetuneJob:- """Send a request to the provider to launch the model, if supported."""+ """Start model fine-tuning, if supported."""# Fine-tuning is experimental and requires the experimental flagfrom dspy import settings as settingserr = "Fine-tuning is an experimental feature and requires `dspy.settings.experimental = True`."assert settings.experimental, err- # Pack the configuration into a dictionary- config = dict(+ # Get the fine-tuning provider, if it is supported+ try:+ provider = _get_supported_finetune_provider(self.model)+ except ValueError as err:+ raise err++ # Initialize the finetune job+ FinetuneJobClass = get_provider_finetune_job_class(provider=provider)+ finetune_job = FinetuneJobClass(model=self.model,message_completion_pairs=message_completion_pairs,train_kwargs=train_kwargs,- launch_kwargs=launch_kwargs,)- # Find the respective finetuning functions and job classes- finetune_function = None- finetune_job_class = None- if is_openai_model(self.model):- finetune_function = finetune_openai- finetune_job_class = FinetuneJobOpenAI- elif is_anyscale_model(self.model):- finetune_function = finetune_anyscale- finetune_job_class = FinetuneJobAnyScale-- # Ensure that the model supports fine-tuning- if not finetune_function or not finetune_job_class:- err = f"Fine-tuning is not supported for the model {self.model}."- raise ValueError(err)-- # Initialize the finetune job- finetune_job = finetune_job_class(**config)-# Start asyncronous trainingexecutor = ThreadPoolExecutor(max_workers=1)executor.submit(- finetune_function,+ execute_finetune_job,finetune_job,- **config+ launch_kwargs=launch_kwargs,+ cache_finetune=cache_finetune)executor.shutdown(wait=False)@@ -152,6 +156,7 @@ def litellm_text_completion(request, cache={"no-cache": True, "no-store": True})kwargs = ujson.loads(request)# Extract the provider and model from the model string.+ # TODO: Not all the models are in the format of "provider/model"model = kwargs.pop("model").split("/", 1)provider, model = model[0] if len(model) > 1 else "openai", model[-1]@@ -196,19 +201,141 @@ def _inspect_history(lm, n: int = 1):#--------------------------------------------------------------------------------# Functions for supporting self-hosted models+# Fine-tune support#----------------------------------------------------------------------------------# TODO: It would be nice to move these to a separate file-def self_hosted_model_launch(lm: LM):- """Launch a self-hosted model."""- # TODO: Hardcode logic that starts a local server of choice using a selected- # server (e.g. VLLM, TGI, SGLang)- pass---def self_hosted_model_kill(lm: LM):- """Kill a self-hosted model."""- # Harcode the logic that kills the local server of choice- pass+# TODO: This part can be moved to a separate module++from dspy.clients.openai import (+ FinetuneJobOpenAI,+ is_openai_model,+ finetune_openai+)+from dspy.clients.anyscale import (+ FinetuneJobAnyScale,+ is_anyscale_model,+ finetune_anyscale+)+++_PROVIDER_ANYSCALE = "anyscale"+_PROVIDER_OPENAI = "openai"+_SUPPORTED_FINETUNE_PROVIDERS = [+ _PROVIDER_ANYSCALE,+ _PROVIDER_OPENAI,+]+++def _get_supported_finetune_provider(model: str) -> Union[str, ValueError]:+ """Return the finetuning provider for the given model.++ The provider must be in _SUPPORTED_FINETUNE_PROVIDERS. This function is not+ named `_get_provider` because it does not attempt to find the provider of a+ model if there is no DSPy fine-tuning support for it.+ """+ if is_self_hosted_model(model):+ return _PROVIDER_SELF_HOSTED++ if is_openai_model(model):+ return _PROVIDER_OPENAI++ if is_anyscale_model(model):+ return _PROVIDER_ANYSCALE++ return ValueError(f"DSPy does not have fine-tuning support for {model}")+++def get_provider_finetune_job_class(provider: str) -> Type[FinetuneJob]:+ """Get the FinetuneJob class for the provider."""+ # Mapping from provider to finetune job type+ _PROVIDER_TO_FINETUNE_JOB_CLASS = {+ _PROVIDER_ANYSCALE: FinetuneJobAnyScale,+ _PROVIDER_OPENAI: FinetuneJobOpenAI,+ }++ # Get the FinetuneJob class for the provider+ _CLS = _PROVIDER_TO_FINETUNE_JOB_CLASS[provider]++ return _CLS+++def get_provider_finetune_function(provider: str) -> callable:+ """Return the finetune function for the given model."""+ # Mapping from provider to finetune function+ _PROVIDER_TO_FINETUNE_FUNCTION = {+ _PROVIDER_ANYSCALE: finetune_anyscale,+ _PROVIDER_OPENAI: finetune_openai,+ }++ # Get the finetuning provider+ finetune_function = _PROVIDER_TO_FINETUNE_FUNCTION[provider]++ return finetune_function+++def execute_finetune_job(+ job: FinetuneJob[Type[LM]],+ launch_kwargs: Optional[Dict[str, Any]]=None,+ cache_finetune: bool=True+):+ """Execute the finetune job in a blocking manner."""+ # Input validation+ launch_kwargs = launch_kwargs or {}++ # Execute finetune job+ job_kwargs = job.get_kwargs()+ if cache_finetune:+ try:+ model = cached_finetune(job=job, **job_kwargs)+ except ValueError as err:+ raise err+ else:+ model = finetune(job=job, **job_kwargs)++ # Launch the LM+ lm = LM(model=model, **launch_kwargs)++ # Set the result of the finetuning job to the fine-tuned LM+ job.set_result(lm)+++# TODO: Perhaps we shouldn't directly cache the data+# TODO: Add DiskCache, ignore job+def cached_finetune(+ job,+ model: str,+ message_completion_pairs: List[Dict[str, str]],+ train_kwargs: Optional[Dict[str, Any]]=None,+) -> Union[str, ValueError]:+ return finetune(+ job=job,+ model=model,+ message_completion_pairs=message_completion_pairs,+ train_kwargs=train_kwargs,+ )+++def finetune(+ job,+ model: str,+ message_completion_pairs: List[Dict[str, str]],+ train_kwargs: Optional[Dict[str, Any]]=None,+) -> Union[str, ValueError]:+ """Fine-tune a new model based on the given model."""+ # Get the fine-tuning provider+ try:+ provider = _get_supported_finetune_provider(model)+ except ValueError as err:+ raise err++ # Get the finetune function+ provider_finetune_function = get_provider_finetune_function(provider)++ # Fine-tune a new model based on the given model+ model = provider_finetune_function(+ job=job,+ model=model,+ message_completion_pairs=message_completion_pairs,+ train_kwargs=train_kwargs,+ )++ return modeldiff --git a/dspy/clients/openai.py b/dspy/clients/openai.pyindex 420de85e0..d17d0efc7 100644--- a/dspy/clients/openai.py+++ b/dspy/clients/openai.py@@ -2,15 +2,24 @@ import reimport timefrom typing import Any, Dict, List, Optional-import dspyfrom dspy import loggerfrom dspy.clients.finetune import (FinetuneJob,TrainingMethod,- validate_training_data+ validate_training_data,+ save_data,)+#-------------------------------------------------------------------------------+# Variables+#-------------------------------------------------------------------------------++# List of training methods supported by OpenAI+TRAINING_METHODS_OPENAI = [+ TrainingMethod.SFT,+]+# TODO: Should we include the TTS/Dall-E models on this list?# List of OpenAI model IDsOPENAI_MODEL_IDS = model_ids = [@@ -55,6 +64,10 @@ OPENAI_MODEL_IDS = model_ids = []+#-------------------------------------------------------------------------------+# Function and classes required for the fine-tune interface+#-------------------------------------------------------------------------------+class FinetuneJobOpenAI(FinetuneJob):def cancel(self):@@ -104,54 +117,57 @@ def finetune_openai(model: str,message_completion_pairs: List[Dict[str, str]],train_kwargs: Optional[Dict[str, Any]]=None,- launch_kwargs: Optional[Dict[str, Any]]=None,- ) -> FinetuneJob:+ ) -> str:"""Fine-tune an OpenAI model."""# Fake fine-tuning- logger.info("[Finetune] Fake fine-tuning")train_kwargs = train_kwargs or {}- launch_kwargs = launch_kwargs or {}try:- logger.info("[Finetune] Validate the formatting of the fine-tuning data")- training_method = TrainingMethod.SFT # Hardcoded- validate_training_data(message_completion_pairs, training_method)- time.sleep(5)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Saving the data to a file") # TODO: Get parent path, keep same across all finetuning jobs- # We utilize message_completion_pairs here- time.sleep(1)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Uploading the data to the cloud")- time.sleep(1)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Launch training")- # We utilize model and train_kwargs here- time.sleep(1)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Wait for training to complete")- time.sleep(1)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Get trained model client")- model = "ft:gpt-4o:2024-08-06:THIS_IS_A_REAL_MODEL!!!" # Hardcoded- time.sleep(1)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Create a DSPy LM object for the trained model")- # We utilize launch_kwargs here- lm = dspy.LM(model=model, **launch_kwargs)- time.sleep(1)- logger.info("[Finetune] Done!")-- logger.info("Set the result of the FinetuningJob to the new lM")- job.set_result(lm)- logger.info("[Finetune] Done!")+ # Validate the formatting of the fine-tuning data+ logger.info("[Finetune] Validating the formatting of the data")+ _validate_data(message_completion_pairs)+ logger.info("[Finetune] Done!")++ # Validate the formatting of the fine-tuning data+ logger.error("[Finetune] Saving the data to a file")+ # data_path = save_data(message_completion_pairs)+ time.sleep(1)+ logger.info("[Finetune] Done!")++ logger.error("[Finetune] Uploading the data to the cloud")+ time.sleep(1)+ logger.error("[Finetune] Done!")++ logger.error("[Finetune] Launch training")+ # We utilize model and train_kwargs here+ time.sleep(1)+ logger.error("[Finetune] Done!")++ logger.error("[Finetune] Wait for training to complete")+ time.sleep(1)+ logger.error("[Finetune] Done!")++ logger.error("[Finetune] Get trained model client")+ model = "ft:gpt-4o:2024-08-06:THIS_IS_A_REAL_MODEL!!!" # Hardcoded+ time.sleep(1)+ logger.error("[Finetune] Done!")++ logger.error("[Finetune] Exiting finetune_openai")++ return modelexcept Exception as e:logger.error(f"[Finetune] Error: {e}")raise e+++#-------------------------------------------------------------------------------+# Custom functions+#-------------------------------------------------------------------------------+def _validate_data(data: Dict[str, str]) -> Optional[Exception]:+ """Validate the formatting of the fine-tuning data."""+ # TODO: Hardcoded train method+ # TODO: Should we skip this validation since the server might have custom+ # requirements?+ training_method = TrainingMethod.SFT+ validate_training_data(data, training_method)diff --git a/dspy/clients/self_hosted.py b/dspy/clients/self_hosted.pyindex 603d6b3ee..90c850e7e 100644--- a/dspy/clients/self_hosted.py+++ b/dspy/clients/self_hosted.py@@ -1,6 +1,15 @@+from typing import Dict, Any++from dspy import LM+from dspy import loggerfrom dspy.clients.openai import is_openai_model+#-------------------------------------------------------------------------------+# Function and classes required for the fine-tune interface+#-------------------------------------------------------------------------------++# TODO: Missing FinetuneJobSelfHosted class and finetune_self_hosted functiondef is_self_hosted_model(model: str) -> bool:"""Check if the model is self-hosted."""@@ -10,3 +19,18 @@ def is_self_hosted_model(model: str) -> bool:return Falsereturn not is_openai_model(model)+++#-------------------------------------------------------------------------------+# Launching and killing self hosted LMs+#-------------------------------------------------------------------------------++def self_hosted_model_launch(model: str, launch_kwargs: Dict[str, Any]):+ """Launch a self-hosted model."""+ # TODO: Hardcode resources for launching a select server through docker+ raise NotImplementedError("Method `self_hosted_model_launch` is not implemented.")++def self_hosted_model_kill(model: str, launch_kwargs: Dict[str, Any]):+ # TODO: Hardcode resources for killing a select server through docker+ """Kill a self-hosted model."""+ raise NotImplementedError("Method `self_hosted_model_kill` is not implemented.")