Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Merge remote-tracking branch 'upstream/main' into dev_finetune

Isaac Millerd6bbb0941602
diff --cc dspy/adapters/chat_adapter.py
index df5be77b0,5a20dcff3..87d25b404
--- a/dspy/adapters/chat_adapter.py
+++ b/dspy/adapters/chat_adapter.py
@@@ -52,37 -58,21 +58,39 @@@ class ChatAdapter(Adapter)
try:
fields[k] = parse_value(v, signature.output_fields[k].annotation) if _parse_values else v
except Exception as e:
- raise ValueError(f"Error parsing field {k}: {e}.\n\n\t\tOn attempting to parse the value\n```\n{v}\n```")
+ raise ValueError(
+ f"Error parsing field {k}: {e}.\n\n\t\tOn attempting to parse the value\n```\n{v}\n```"
+ )
- if fields.keys() != signature.output_fields.keys():
- raise ValueError(f"Expected {signature.output_fields.keys()} but got {fields.keys()}")
+ if list(fields.keys()) != list(signature.output_fields.keys()):
+ # print("Expected", list(signature.output_fields.keys()), "but got", fields.keys(), "from", completion)
+ raise ValueError(f"Expected {list(signature.output_fields.keys())} but got {fields.keys()}")
return fields
+ def format_completion(self, signature, outputs):
+ reconstructed = []
+
+ fields_dict = signature.output_fields
+
+ field_name_output_map = {field: outputs[field] for field in fields_dict.keys()}
+
+ for field, value in field_name_output_map.items():
+ reconstructed.append(f"[[ ## {field} ## ]]")
+ reconstructed.append(str(value))
+ reconstructed.append("") # Add an empty line for separation
+
+ reconstructed.append("[[ ## completed ## ]]")
+
+ result = "\n".join(reconstructed).strip()
+
+ return result
-
def format_blob(blob):
- if '\n' not in blob and "«" not in blob and "»" not in blob: return f"«{blob}»"
+ if "\n" not in blob and "«" not in blob and "»" not in blob:
+ return f"«{blob}»"
- modified_blob = blob.replace('\n', '\n ')
+ modified_blob = blob.replace("\n", "\n ")
return f"«««\n {modified_blob}\n»»»"
@@@ -130,12 -135,13 +153,12 @@@ def format_turn(signature, values, role
content.append(format_fields({k: values.get(k, "Not supplied for this particular example.") for k in field_names}))
if role == "user":
- content.append(
- "Respond with the corresponding output fields, starting with the field "
- + ", then ".join(f"`{f}`" for f in signature.output_fields)
- + ", and then ending with the marker for `completed`."
- )
+ content.append(f"Respond with the corresponding output fields using the proper format of "
+ f"[[ ## <field_name> ## ]] followed by the field value. Start with the field "
+ f"{', then '.join(f'`[[ ## {f} ## ]]`' for f in signature.output_fields)}, "
+ f"and then ending with the marker for `completed`.")
- return {"role": role, "content": '\n\n'.join(content).strip()}
+ return {"role": role, "content": "\n\n".join(content).strip()}
def get_annotation_name(annotation):
diff --cc dspy/clients/lm.py
index 4b1157195,994c8bc41..10a7615dc
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@@ -1,71 -1,33 +1,58 @@@
import functools
import os
+ import uuid
+ from datetime import datetime
from pathlib import Path
+from typing import Any, Dict, List, Optional, Type, Union
+import ujson
+
+
+from dspy import logger
+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,
+)
+from dspy.clients.anyscale import (
+ is_anyscale_model,
+ anyscale_model_launch,
+ anyscale_model_kill,
+)
+ import litellm
+ import ujson
+ from litellm.caching import Cache
- DISK_CACHE_DIR = os.environ.get('DSPY_CACHEDIR') or os.path.join(Path.home(), '.dspy_cache')
-
-
- try:
- import warnings
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=UserWarning)
- if "LITELLM_LOCAL_MODEL_COST_MAP" not in os.environ:
- os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
- import litellm
- litellm.telemetry = False
-
- from litellm.caching import Cache
- litellm.cache = Cache(disk_cache_dir=DISK_CACHE_DIR, type="disk")
-
- except ImportError:
- class LitellmPlaceholder:
- def __getattr__(self, _): raise ImportError("The LiteLLM package is not installed. Run `pip install litellm`.")
-
- litellm = LitellmPlaceholder()
+ 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.telemetry = False
+ if "LITELLM_LOCAL_MODEL_COST_MAP" not in os.environ:
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
- #-------------------------------------------------------------------------------
- # 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 = model
self.model_type = model_type
self.cache = cache
self.kwargs = dict(temperature=temperature, max_tokens=max_tokens, **kwargs)
+ self.launch_kwargs = kwargs.pop("launch_kwargs", launch_kwargs or {})
self.history = []
+ # 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(...)`"
+ 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.
@@@ -202,145 -133,5 +212,145 @@@ def _inspect_history(lm, n: int = 1)
if len(outputs) > 1:
choices_text = f" \t (and {len(outputs)-1} other completions)"
print(_red(choices_text, end=""))
-
+
print("\n\n\n")
+
+
+#-------------------------------------------------------------------------------
+# Fine-tune support
+#-------------------------------------------------------------------------------
+# TODO: This part can be moved to a separate module
+
+from dspy.clients.openai import (
+ FinetuneJobOpenAI,
+ is_openai_model
+)
+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 model
diff --cc dspy/predict/predict.py
index 88a74861a,a029a1171..dc8ae3437
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@@ -1,6 -1,6 +1,8 @@@
-import logging
+from __future__ import annotations # Used for self type hints
import random
+from typing import Optional
++import logging
+ from functools import lru_cache
from pydantic import BaseModel
diff --cc dspy/primitives/module.py
index 4fe9ea692,1dee9cbb1..87ce8b1aa
--- a/dspy/primitives/module.py
+++ b/dspy/primitives/module.py
@@@ -149,11 -149,12 +149,11 @@@ class BaseModule
return new_instance
def dump_state(self, save_verbose):
- print(self.named_parameters())
return {name: param.dump_state(save_verbose) for name, param in self.named_parameters()}
- def load_state(self, state):
+ def load_state(self, state, use_legacy_loading=False):
for name, param in self.named_parameters():
- param.load_state(state[name])
+ param.load_state(state[name], use_legacy_loading=use_legacy_loading)
def save(self, path, save_field_meta=False):
with open(path, "w") as f: