Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Add LM.finetune()

dilara2c931547dd61
diff --git a/dspy/clients/anyscale.py b/dspy/clients/anyscale.py
new file mode 100644
index 000000000..c307695a6
--- /dev/null
+++ b/dspy/clients/anyscale.py
@@ -0,0 +1,75 @@
+import re
+import time
+from typing import List, Dict, Any
+
+from dspy import logger
+from dspy import LM
+from dspy.clients.finetune import (
+ FinetuneJob,
+ TrainingMethod,
+ validate_training_data
+)
+
+
+class FinetuneJobAnyScale(FinetuneJob):
+
+ def cancel(self):
+ """Cancel the finetuning job."""
+ raise NotImplementedError("Method `cancel` is not implemented.")
+
+ def get_status(self):
+ """Return the status of the finetuning job."""
+ raise NotImplementedError("Method `get_status` is not implemented.")
+
+
+def is_anyscale_model(model: str) -> bool:
+ """Check if the model is an AnyScale model."""
+ logger.info("Is AnyScale model is not implemented, returning False as a default to not break lm.py")
+ return False
+
+
+def finetune_anyscale(job: FinetuneJobAnyScale, model: str, message_completion_pairs: List[Dict[str, str]], config: Dict[str, Any]):
+ """Fine-tune an AnyScale model."""
+
+ # Fake fine-tuning
+ logger.info("[Finetune] Fake fine-tuning of an AnyScale model")
+
+ try:
+ logger.info("[Finetune] Verifying the formatting of the fine-tuning data")
+ training_method = TrainingMethod.SFT # Hardcoded
+ logger.info("[Finetune] Validate the formatting of the fine-tuning data")
+ 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
+ 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] Wait for training to complete")
+ time.sleep(1)
+ logger.info("[Finetune] Done!")
+
+ logger.info("[Finetune] Get trained model client")
+ time.sleep(1)
+ logger.info("[Finetune] Done!")
+
+ logger.info("[Finetune] Create a DSPy LM object for the trained model") # Will cause a circular import
+ model_id = "SOME_LOCAL_LM" # Hardcoded
+ lm = LM(model_id)
+ 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!")
+
+ except Exception as e:
+ logger.error(f"[Finetune] Error: {e}")
+ raise e
+
+ print()
+ time.sleep(20)
diff --git a/dspy/clients/finetune.py b/dspy/clients/finetune.py
new file mode 100644
index 000000000..f7283c4fb
--- /dev/null
+++ b/dspy/clients/finetune.py
@@ -0,0 +1,55 @@
+from concurrent.futures import ThreadPoolExecutor, Future
+from enum import Enum
+from typing import List, Dict, Any, Optional
+
+
+class TrainingMethod(str, Enum):
+ """Enum class for training methods.
+
+ When comparing enums, Python checks for object IDs, which means that the
+ enums can't be compared directly. Subclassing the Enum class along with the
+ str class allows for direct comparison of the enums.
+ """
+ SFT = "SFT"
+ Preference = "Preference"
+
+
+"""Dictionary mapping training methods to the data keys they require."""
+TRAINING_METHOD_TO_DATA_KEYS = {
+ TrainingMethod.SFT: ["prompt", "completion"],
+ TrainingMethod.Preference: ["prompt", "chosen", "rejected"],
+}
+
+
+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 __str__(self):
+ return f"FinetuningJob(model={self.model}, config={self.config})"
+
+ def __repr__(self):
+ return str(self)
+
+ # Subclasses should implement the following methods
+ def cancel(self):
+ """Cancel the finetuning job."""
+ raise NotImplementedError("Method `get_status` is not implemented.")
+
+ def get_status(self):
+ """Cancel the finetuning job."""
+ raise NotImplementedError("Method `get_status` is not implemented.")
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.py
index 1c611ca34..5e2c77422 100644
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@ -1,7 +1,18 @@
-import os
-import ujson
+from concurrent.futures import ThreadPoolExecutor
import functools
+import os
from pathlib import Path
+import re
+from typing import Any, Dict, List
+import ujson
+
+
+from 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
+
try:
import warnings
@@ -22,6 +33,10 @@ except ImportError:
litellm = LitellmPlaceholder()
+
+#-------------------------------------------------------------------------------
+# LiteLLM Client
+#-------------------------------------------------------------------------------
class LM:
def __init__(self, model, model_type='chat', temperature=0.0, max_tokens=1000, cache=True, **kwargs):
self.model = model
@@ -30,7 +45,7 @@ class LM:
self.kwargs = dict(temperature=temperature, max_tokens=max_tokens, **kwargs)
self.history = []
- if "o1-" in model:
+ if "o1-" in model: # TODO: This is error prone!
assert max_tokens >= 5000 and temperature == 1.0, \
"OpenAI's o1-* models require passing temperature=1.0 and max_tokens >= 5000 to `dspy.LM(...)`"
@@ -60,6 +75,54 @@ class LM:
def inspect_history(self, n: int = 1):
_inspect_history(self, n)
+ 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)
+ 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)
+ 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]], config: Dict[str, Any]) -> FinetuneJob:
+ """Send a request to the provider to launch the model, if supported."""
+ # Fine-tuning is experimental and requires the experimental flag
+ from dspy import settings as settings
+ err = "Fine-tuning is an experimental feature and requires `dspy.settings.experimental = True`."
+ assert settings.experimental, err
+
+ # Find the respective finetuning functions and job classes
+ finetune_function = None
+ finetune_job = None
+ if is_openai_model(self.model):
+ finetune_function = finetune_openai
+ finetune_job = FinetuneJobOpenAI()
+ elif is_anyscale_model(self.model):
+ finetune_function = finetune_anyscale
+ finetune_function = finetune_anyscale
+ finetune_job = FinetuneJobAnyScale()
+
+ # Ensure that the model supports fine-tuning
+ if not finetune_function or not finetune_job:
+ err = f"Fine-tuning is not supported for the model {self.model}."
+ raise ValueError(err)
+
+ # Start asyncronous training
+ executor = ThreadPoolExecutor(max_workers=1)
+ executor.submit(
+ finetune_function,
+ finetune_job,
+ model=self.model,
+ message_completion_pairs=message_completion_pairs,
+ config=config
+ )
+ executor.shutdown(wait=False)
+
+ return finetune_job
+
@functools.lru_cache(maxsize=None)
def cached_litellm_completion(request):
@@ -118,3 +181,22 @@ def _inspect_history(lm, n: int = 1):
print(_red(choices_text, end=""))
print("\n\n\n")
+
+
+#-------------------------------------------------------------------------------
+# Functions for supporting self-hosted models
+#-------------------------------------------------------------------------------
+
+
+# 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
diff --git a/dspy/clients/openai.py b/dspy/clients/openai.py
new file mode 100644
index 000000000..2812f4e82
--- /dev/null
+++ b/dspy/clients/openai.py
@@ -0,0 +1,146 @@
+import re
+import time
+from typing import List, Dict, Any
+
+from dspy import logger
+from dspy import LM
+from dspy.clients.finetune import (
+ FinetuneJob,
+ TrainingMethod,
+ validate_training_data
+)
+
+
+# TODO: Should we include the TTS/Dall-E models on this list?
+# List of OpenAI model IDs
+OPENAI_MODEL_IDS = model_ids = [
+ "gpt-4o",
+ "gpt-4o-2024-08-06",
+ "gpt-4o-2024-05-13",
+ "chatgpt-4o-latest",
+ "gpt-4o-mini",
+ "gpt-4o-mini-2024-07-18",
+ "gpt-4o-realtime-preview",
+ "gpt-4o-realtime-preview-2024-10-01",
+ "o1-preview",
+ "o1-preview-2024-09-12",
+ "o1-mini",
+ "o1-mini-2024-09-12",
+ "gpt-4-turbo",
+ "gpt-4-turbo-2024-04-09",
+ "gpt-4-turbo-preview",
+ "gpt-4-0125-preview",
+ "gpt-4-1106-preview",
+ "gpt-4",
+ "gpt-4-0613",
+ "gpt-4-0314",
+ "gpt-3.5-turbo-0125",
+ "gpt-3.5-turbo",
+ "gpt-3.5-turbo-1106",
+ "gpt-3.5-turbo-instruct",
+ "dall-e-3",
+ "dall-e-2",
+ "tts-1",
+ "tts-1-hd",
+ "text-embedding-3-large",
+ "text-embedding-3-small",
+ "text-embedding-ada-002",
+ "omni-moderation-latest",
+ "omni-moderation-2024-09-26",
+ "text-moderation-latest",
+ "text-moderation-stable",
+ "text-moderation-007",
+ "babbage-002",
+ "davinci-002"
+]
+
+
+class FinetuneJobOpenAI(FinetuneJob):
+
+ def cancel(self):
+ """Cancel the finetuning job."""
+ logger.info("[Finetune] Canceling the OpenAI finetuning job")
+ time.sleep(3)
+ logger.info("[Finetune] Done")
+ super().cancel()
+
+ def get_status(self):
+ """Get the status of the finetuning job."""
+ logger.info("[Finetune] Getting the status of the OpenAI finetuning job")
+ time.sleep(3)
+ status = "Running"
+ logger.info("[Finetune] Done")
+ return status
+
+
+def is_openai_model(model: str) -> bool:
+ """Check if the model is an OpenAI model."""
+ # Filter the "openai/" prefix, if exists
+ if model.startswith("openai/"):
+ model = model[len("openai/"):]
+
+ # Check if the model is a base OpenAI model
+ if model in OPENAI_MODEL_IDS:
+ return True
+
+ # Check if the model is a fine-tuned OpneAI model. Fine-tuned OpenAI models
+ # have the prefix "ft:<BASE_MODEL_NAME>:", followed by a string specifying
+ # the fine-tuned model. The following RegEx pattern is used to match the
+ # base model name.
+ # TODO: This part can be updated to match the actual fine-tuned model names
+ # by making a call to the OpenAI API to be more exact, but this might
+ # require an API key with the right permissions.
+ match = re.match(r"ft:([^:]+):", model)
+ if match and match.group(1) in OPENAI_MODEL_IDS:
+ return True
+
+ # If the model is not a base OpenAI model or a fine-tuned OpenAI model, then
+ # it is not an OpenAI model.
+ return False
+
+
+def finetune_openai(job: FinetuneJobOpenAI, model: str, message_completion_pairs: List[Dict[str, str]], config: Dict[str, Any]):
+ """Fine-tune an OpenAI model."""
+
+ # Fake fine-tuning
+ logger.info("[Finetune] Fake fine-tuning of an OpenAI model")
+
+ 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
+ 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] Wait for training to complete")
+ time.sleep(1)
+ logger.info("[Finetune] Done!")
+
+ logger.info("[Finetune] Get trained model client")
+ time.sleep(1)
+ logger.info("[Finetune] Done!")
+
+ logger.info("[Finetune] Create a DSPy LM object for the trained model") # Will cause a circular import
+ model_id = "ft:gpt-4o:2024-08-06:THIS_IS_A_REAL_MODEL!!!" # Hardcoded
+ lm = "FakeLM" # Create an LM client
+ 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!")
+
+ except Exception as e:
+ logger.error(f"[Finetune] Error: {e}")
+ raise e
+
+ print()
+ time.sleep(20)
diff --git a/dspy/clients/self_hosted.py b/dspy/clients/self_hosted.py
new file mode 100644
index 000000000..3bad38df6
--- /dev/null
+++ b/dspy/clients/self_hosted.py
@@ -0,0 +1,14 @@
+from typing import List, Dict, Any
+
+from dspy.clients.openai import is_openai_model
+
+
+def is_self_hosted_model(model: str) -> bool:
+ """Check if the model is self-hosted."""
+
+ # Filter the models names that don't start with the prefix "openai/", since
+ # all the self-hosted models have this prefix.
+ if not model.startswith("openai/"):
+ return False
+
+ return not is_openai_model(model)
diff --git a/examples/finetuning/finetune_test.ipynb b/examples/finetuning/finetune_test.ipynb
new file mode 100644
index 000000000..f74fd4a91
--- /dev/null
+++ b/examples/finetuning/finetune_test.ipynb
@@ -0,0 +1,164 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "The autoreload extension is already loaded. To reload it, use:\n",
+ " %reload_ext autoreload\n"
+ ]
+ }
+ ],
+ "source": [
+ "%load_ext autoreload\n",
+ "%autoreload 2\n",
+ "\n",
+ "import tqdm\n",
+ "import os\n",
+ "\n",
+ "os.environ[\"DSPY_CACHEDIR\"] = \"\"\n",
+ "os.environ[\"DSP_CACHEDIR\"] = \"\"\n",
+ "os.environ[\"OPENAI_API_KEY\"] = \"\"\n",
+ "\n",
+ "import dspy\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['Hello! I’m here and ready to help you with whatever you need. What’s on your mind?']"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# Ensure that we can use the LM interface\n",
+ "lm = dspy.LM('openai/gpt-4o-mini')\n",
+ "lm(\"What's up GPT?\", temperature=1.5)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "dspy.clients.openai.FinetuneJobOpenAI"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# Example call to the finetune method for OpenAI\n",
+ "# Doesn't call the real functions for the time being\n",
+ "dspy.settings.experimental = True\n",
+ "\n",
+ "training_data = [\n",
+ " dict(prompt=\"What is the capital of France?\", completion=\"Paris\"),\n",
+ " dict(prompt=\"What is the capital of Germany?\", completion=\"Berlin\"),\n",
+ " dict(prompt=\"What is the capital of Italy?\", completion=\"Rome\"),\n",
+ " dict(prompt=\"What is the capital of Spain?\", completion=\"Madrid\"),\n",
+ " dict(prompt=\"What is the capital of Portugal?\", completion=\"Lisbon\"),\n",
+ " dict(prompt=\"What is the capital of the United States?\", completion=\"Washington, D.C.\"),\n",
+ "]\n",
+ "\n",
+ "config = {\n",
+ " \"quantized\": True,\n",
+ " \"learning_rate\": \"whatever\",\n",
+ "}\n",
+ "\n",
+ "job = lm.finetune(message_completion_pairs=training_data, config=config)\n",
+ "type(job)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# This will return False until the job is complete\n",
+ "job.done()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'FakeLM'"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# Once the hjob is complete, this will return the new language model\n",
+ "finetuned_lm = job.result()\n",
+ "finetuned_lm"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "dspy25",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.9.19"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}