Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Finetune fix (#7629)

Dilara Soylub109e72fb1d5
diff --git a/dspy/clients/databricks.py b/dspy/clients/databricks.py
index e310cf99c..4b854d2b2 100644
--- a/dspy/clients/databricks.py
+++ b/dspy/clients/databricks.py
@@ -8,7 +8,7 @@ import requests
import ujson
from dspy.clients.provider import Provider, TrainingJob
-from dspy.clients.utils_finetune import DataFormat, get_finetune_directory
+from dspy.clients.utils_finetune import TrainDataFormat, get_finetune_directory
if TYPE_CHECKING:
from databricks.sdk import WorkspaceClient
@@ -50,7 +50,7 @@ class DatabricksProvider(Provider):
@staticmethod
def deploy_finetuned_model(
model: str,
- data_format: Optional[DataFormat] = None,
+ data_format: Optional[TrainDataFormat] = None,
databricks_host: Optional[str] = None,
databricks_token: Optional[str] = None,
deploy_timeout: int = 900,
@@ -148,11 +148,11 @@ class DatabricksProvider(Provider):
num_retries = deploy_timeout // 60
for _ in range(num_retries):
try:
- if data_format == DataFormat.chat:
+ if data_format == TrainDataFormat.CHAT:
client.chat.completions.create(
messages=[{"role": "user", "content": "hi"}], model=model_name, max_tokens=1
)
- elif data_format == DataFormat.completion:
+ elif data_format == TrainDataFormat.COMPLETION:
client.completions.create(prompt="hi", model=model_name, max_tokens=1)
logger.info(f"Databricks model serving endpoint {model_name} is ready!")
return
@@ -169,17 +169,17 @@ class DatabricksProvider(Provider):
job: TrainingJobDatabricks,
model: str,
train_data: List[Dict[str, Any]],
+ train_data_format: Optional[Union[TrainDataFormat, str]] = "chat",
train_kwargs: Optional[Dict[str, Any]] = None,
- data_format: Optional[Union[DataFormat, str]] = "chat",
) -> str:
if isinstance(data_format, str):
if data_format == "chat":
- data_format = DataFormat.chat
+ data_format = TrainDataFormat.CHAT
elif data_format == "completion":
- data_format = DataFormat.completion
+ data_format = TrainDataFormat.COMPLETION
else:
raise ValueError(
- f"String `data_format` must be one of 'chat' or 'completion', but received: {data_format}."
+ f"String `train_data_format` must be one of 'chat' or 'completion', but received: {data_format}."
)
if "train_data_path" not in train_kwargs:
@@ -243,7 +243,7 @@ class DatabricksProvider(Provider):
return f"databricks/{job.endpoint_name}"
@staticmethod
- def upload_data(train_data: List[Dict[str, Any]], databricks_unity_catalog_path: str, data_format: DataFormat):
+ def upload_data(train_data: List[Dict[str, Any]], databricks_unity_catalog_path: str, data_format: TrainDataFormat):
logger.info("Uploading finetuning data to Databricks Unity Catalog...")
file_path = _save_data_to_local_file(train_data, data_format)
@@ -303,7 +303,7 @@ def _create_directory_in_databricks_unity_catalog(w: "WorkspaceClient", databric
logger.info(f"Successfully created directory {databricks_unity_catalog_path} in Databricks Unity Catalog!")
-def _save_data_to_local_file(train_data: List[Dict[str, Any]], data_format: DataFormat):
+def _save_data_to_local_file(train_data: List[Dict[str, Any]], data_format: TrainDataFormat):
import uuid
file_name = f"finetuning_{uuid.uuid4()}.jsonl"
@@ -313,9 +313,9 @@ def _save_data_to_local_file(train_data: List[Dict[str, Any]], data_format: Data
file_path = os.path.abspath(file_path)
with open(file_path, "w") as f:
for item in train_data:
- if data_format == DataFormat.chat:
+ if data_format == TrainDataFormat.CHAT:
_validate_chat_data(item)
- elif data_format == DataFormat.completion:
+ elif data_format == TrainDataFormat.COMPLETION:
_validate_completion_data(item)
f.write(ujson.dumps(item) + "\n")
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.py
index 549029d50..6f5468b84 100644
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@ -20,7 +20,7 @@ import dspy
from dspy.adapters.base import Adapter
from dspy.clients.openai import OpenAIProvider
from dspy.clients.provider import Provider, TrainingJob
-from dspy.clients.utils_finetune import DataFormat, infer_data_format, validate_data_format
+from dspy.clients.utils_finetune import TrainDataFormat
from dspy.utils.callback import BaseCallback, with_callbacks
from .base_lm import BaseLM
@@ -46,6 +46,7 @@ class LM(BaseLM):
provider=None,
finetuning_model: Optional[str] = None,
launch_kwargs: Optional[dict[str, Any]] = None,
+ train_kwargs: Optional[dict[str, Any]] = None,
**kwargs,
):
"""
@@ -79,7 +80,8 @@ class LM(BaseLM):
self.callbacks = callbacks or []
self.num_retries = num_retries
self.finetuning_model = finetuning_model
- self.launch_kwargs = launch_kwargs
+ self.launch_kwargs = launch_kwargs or {}
+ self.train_kwargs = train_kwargs or {}
# Handle model-specific configuration for different model families
model_family = model.split("/")[-1].lower() if "/" in model else model.lower()
@@ -156,18 +158,16 @@ class LM(BaseLM):
return outputs
def launch(self, launch_kwargs: Optional[Dict[str, Any]] = None):
- launch_kwargs = launch_kwargs or self.launch_kwargs
self.provider.launch(self, launch_kwargs)
def kill(self, launch_kwargs: Optional[Dict[str, Any]] = None):
- launch_kwargs = launch_kwargs or self.launch_kwargs
self.provider.kill(self, launch_kwargs)
def finetune(
self,
train_data: List[Dict[str, Any]],
+ train_data_format: Optional[TrainDataFormat],
train_kwargs: Optional[Dict[str, Any]] = None,
- data_format: Optional[DataFormat] = None,
) -> TrainingJob:
from dspy import settings as settings
@@ -178,27 +178,18 @@ class LM(BaseLM):
err = f"Provider {self.provider} does not support fine-tuning."
assert self.provider.finetunable, err
- # Perform data validation before starting the thread to fail early
- train_kwargs = train_kwargs or {}
- if not data_format:
- adapter = self.infer_adapter()
- data_format = infer_data_format(adapter)
- validate_data_format(data=train_data, data_format=data_format)
-
- # TODO(PR): We can quickly add caching, but doing so requires
- # adding functions that just call other functions as we had in the last
- # iteration, unless people have other ideas.
def thread_function_wrapper():
return self._run_finetune_job(job)
thread = threading.Thread(target=thread_function_wrapper)
- model_to_finetune = self.finetuning_model or self.model
+ train_kwargs = train_kwargs or self.train_kwargs
+ model_to_finetune = self.finetuning_model or self.model
job = self.provider.TrainingJob(
thread=thread,
model=model_to_finetune,
train_data=train_data,
+ train_data_format=train_data_format,
train_kwargs=train_kwargs,
- data_format=data_format,
)
thread.start()
@@ -212,8 +203,8 @@ class LM(BaseLM):
job=job,
model=job.model,
train_data=job.train_data,
+ train_data_format=job.train_data_format,
train_kwargs=job.train_kwargs,
- data_format=job.data_format,
)
lm = self.copy(model=model)
job.set_result(lm)
diff --git a/dspy/clients/lm_local.py b/dspy/clients/lm_local.py
index c494a0fec..3aa2465f9 100644
--- a/dspy/clients/lm_local.py
+++ b/dspy/clients/lm_local.py
@@ -1,32 +1,26 @@
-import time
-import socket
+import datetime
+import logging
+import random
import requests
-import threading
+import socket
+import string
import subprocess
+import time
+import threading
from datasets import Dataset
from typing import Any, Dict, List, Optional
from dspy.clients.provider import TrainingJob, Provider
-from dspy.clients.utils_finetune import DataFormat, TrainingStatus, save_data
-
-
-class LocalTrainingJob(TrainingJob):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.data_path = None
+from dspy.clients.utils_finetune import TrainDataFormat, save_data
- def cancel(self):
- raise NotImplementedError
-
- def status(self) -> TrainingStatus:
- raise NotImplementedError
+logger = logging.getLogger(__name__)
class LocalProvider(Provider):
def __init__(self):
super().__init__()
self.finetunable = True
- self.TrainingJob = LocalTrainingJob
+ self.TrainingJob = TrainingJob
@staticmethod
def launch(lm: "LM", launch_kwargs: Optional[Dict[str, Any]] = None):
@@ -38,8 +32,11 @@ class LocalProvider(Provider):
'`pip install "sglang[all]"; pip install flashinfer -i https://flashinfer.ai/whl/cu121/torch2.4/`'
)
- if launch_kwargs is None:
- launch_kwargs = {}
+ if hasattr(lm, "process"):
+ logger.info("Server is already launched.")
+ return
+
+ launch_kwargs = launch_kwargs or lm.launch_kwargs
import os
@@ -49,8 +46,8 @@ class LocalProvider(Provider):
if model.startswith("local:"):
model = model[6:]
- print(f"Grabbing a free port to launch an SGLang server for model {model}")
- print(
+ logger.info(f"Grabbing a free port to launch an SGLang server for model {model}")
+ logger.info(
f"We see that CUDA_VISIBLE_DEVICES is {os.environ.get('CUDA_VISIBLE_DEVICES', 'unset')}"
)
port = get_free_port()
@@ -67,7 +64,7 @@ class LocalProvider(Provider):
# A threading.Event to control printing after the server is ready.
# This will store *all* lines (both before and after readiness).
- print(f"SGLang server process started with PID {process.pid}.")
+ logger.info(f"SGLang server process started with PID {process.pid}.")
stop_printing_event = threading.Event()
logs_buffer = []
@@ -109,38 +106,49 @@ class LocalProvider(Provider):
return "".join(logs_buffer)
# Let the user know server is up
- print(
+ logger.info(
f"Server ready on random port {port}! Logs are available via lm.get_logs() method on returned lm."
)
lm.kwargs["api_base"] = f"http://localhost:{port}/v1"
lm.kwargs["api_key"] = "local"
- lm.process = process
lm.get_logs = get_logs
+ lm.process = process
+ lm.thread = thread
+
@staticmethod
- def kill(model, kill_kwargs: Optional[Dict[str, Any]] = None):
+ def kill(lm: 'LM', launch_kwargs: Optional[Dict[str, Any]] = None):
from sglang.utils import terminate_process
-
- terminate_process(model.process)
+ if not hasattr(lm, "process"):
+ logger.info("No running server to kill.")
+ return
+ # Ideally, the following happens atomically
+ terminate_process(lm.process)
+ lm.thread.join()
+ del lm.process
+ del lm.thread
+ del lm.get_logs
+ logger.info("Server killed.")
@staticmethod
def finetune(
- job: LocalTrainingJob,
+ job: TrainingJob,
model: str,
train_data: List[Dict[str, Any]],
+ train_data_format: Optional[TrainDataFormat],
train_kwargs: Optional[Dict[str, Any]] = None,
- data_format: Optional[DataFormat] = None,
) -> str:
- data_path = save_data(train_data)
-
if model.startswith("openai/"):
model = model[7:]
if model.startswith("local:"):
model = model[6:]
- model_path = data_path.replace(".jsonl", f"__{model.replace('/', '__')}")
- print(f"[Local Provider] Data saved to {data_path}")
+ if train_data_format != TrainDataFormat.CHAT:
+ raise ValueError("Only chat models are supported for local finetuning.")
+
+ data_path = save_data(train_data)
+ output_dir = create_output_dir(model, data_path)
default_train_kwargs = {
"device": None,
@@ -152,18 +160,29 @@ class LocalProvider(Provider):
"max_seq_length": None,
"packing": True,
"bf16": True,
- "output_dir": model_path,
+ "output_dir": output_dir,
}
+ train_kwargs={**default_train_kwargs, **(train_kwargs or {})}
+ output_dir = train_kwargs["output_dir"] # user might have changed the output_dir
- print(f"[Local Provider] Starting local training, will save to {model_path}")
+ logger.info(f"Starting local training, will save to {output_dir}")
train_sft_locally(
model_name=model,
train_data=train_data,
- train_kwargs={**default_train_kwargs, **(train_kwargs or {})},
+ train_kwargs=train_kwargs,
)
- print("[Local Provider] Training complete")
- return f"openai/local:{model_path}"
+ logger.info("Training complete")
+ return f"openai/local:{output_dir}"
+
+
+def create_output_dir(model_name, data_path):
+ model_str = model_name.replace("/", "-")
+ time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
+ rnd_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
+ model_identifier = f"{rnd_str}_{model_str}_{time_str}"
+ output_dir = data_path.replace(".jsonl", "_" + model_identifier)
+ return output_dir
def train_sft_locally(model_name, train_data, train_kwargs):
@@ -171,7 +190,6 @@ def train_sft_locally(model_name, train_data, train_kwargs):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import SFTConfig, SFTTrainer, setup_chat_format
- from trl import apply_chat_template
except ImportError:
raise ImportError(
"For local finetuning, please install torch, transformers, and trl "
@@ -185,7 +203,7 @@ def train_sft_locally(model_name, train_data, train_kwargs):
if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available() else "cpu"
)
- print(f"Using device: {device}")
+ logger.info(f"Using device: {device}")
model = AutoModelForCausalLM.from_pretrained(
pretrained_model_name_or_path=model_name
@@ -199,17 +217,20 @@ def train_sft_locally(model_name, train_data, train_kwargs):
pass
if tokenizer.pad_token_id is None:
- print("Adding pad token to tokenizer")
+ logger.info("Adding pad token to tokenizer")
tokenizer.add_special_tokens({"pad_token": "[!#PAD#!]"})
- print("Creating dataset")
- trainset_dict = {
- "prompt": [entry["messages"][:-1] for entry in train_data],
- "completion": [[entry["messages"][-1]] for entry in train_data],
- }
+ logger.info("Creating dataset")
+ if "max_seq_length" not in train_kwargs:
+ train_kwargs["max_seq_length"] = 4096
+ logger.info(f"The 'train_kwargs' parameter didn't include a 'max_seq_length', defaulting to {train_kwargs['max_seq_length']}")
- trainset = Dataset.from_dict(trainset_dict)
- trainset = trainset.map(apply_chat_template, fn_kwargs={"tokenizer": tokenizer})
+ hf_dataset = Dataset.from_list(train_data)
+ def tokenize_function(example):
+ return encode_sft_example(example, tokenizer, max_seq_length)
+ tokenized_dataset = hf_dataset.map(tokenize_function, batched=False)
+ tokenized_dataset.set_format(type="torch")
+ tokenized_dataset = tokenized_dataset.filter(lambda example: (example["labels"] != -100).any())
USE_PEFT = train_kwargs.get("use_peft", False)
peft_config = None
@@ -231,12 +252,12 @@ def train_sft_locally(model_name, train_data, train_kwargs):
)
sft_config = SFTConfig(
- output_dir=output_dir,
+ output_dir=train_kwargs["output_dir"],
num_train_epochs=train_kwargs["num_train_epochs"],
per_device_train_batch_size=train_kwargs["per_device_train_batch_size"],
gradient_accumulation_steps=train_kwargs["gradient_accumulation_steps"],
learning_rate=train_kwargs["learning_rate"],
- max_grad_norm=2.0,
+ max_grad_norm=2.0, # note that the current SFTConfig default is 1.0
logging_steps=20,
warmup_ratio=0.03,
lr_scheduler_type="constant",
@@ -244,20 +265,18 @@ def train_sft_locally(model_name, train_data, train_kwargs):
bf16=train_kwargs["bf16"],
max_seq_length=train_kwargs["max_seq_length"],
packing=train_kwargs["packing"],
- dataset_kwargs={
+ dataset_kwargs={ # We need to pass dataset_kwargs because we are processing the dataset ourselves
"add_special_tokens": False, # Special tokens handled by template
"append_concat_token": False, # No additional separator needed
},
)
- print("Starting training")
-
+ logger.info("Starting training")
trainer = SFTTrainer(
model=model,
args=sft_config,
- train_dataset=trainset,
+ train_dataset=tokenized_dataset,
peft_config=peft_config,
- processing_class=tokenizer,
)
# Train!
@@ -291,7 +310,7 @@ def train_sft_locally(model_name, train_data, train_kwargs):
gc.collect()
torch.cuda.empty_cache()
- return output_dir
+ return sft_config.output_dir
def get_free_port() -> int:
@@ -328,3 +347,80 @@ def wait_for_server(base_url: str, timeout: int = None) -> None:
except requests.exceptions.RequestException:
# Server not up yet, wait and retry
time.sleep(1)
+
+
+def encode_sft_example(example, tokenizer, max_seq_length):
+ """
+ This function encodes a single example into a format that can be used for sft training.
+ Here, we assume each example has a 'messages' field. Each message in it is a dict with 'role' and 'content' fields.
+ We use the `apply_chat_template` function from the tokenizer to tokenize the messages and prepare the input and label tensors.
+
+ Code obtained from the allenai/open-instruct repository: https://github.com/allenai/open-instruct/blob/4365dea3d1a6111e8b2712af06b22a4512a0df88/open_instruct/finetune.py
+ """
+ import torch
+
+ messages = example["messages"]
+ if len(messages) == 0:
+ raise ValueError("messages field is empty.")
+ input_ids = tokenizer.apply_chat_template(
+ conversation=messages,
+ tokenize=True,
+ return_tensors="pt",
+ padding=False,
+ truncation=True,
+ max_length=max_seq_length,
+ add_generation_prompt=False,
+ )
+ labels = input_ids.clone()
+ # mask the non-assistant part for avoiding loss
+ for message_idx, message in enumerate(messages):
+ if message["role"] != "assistant":
+ # we calculate the start index of this non-assistant message
+ if message_idx == 0:
+ message_start_idx = 0
+ else:
+ message_start_idx = tokenizer.apply_chat_template(
+ conversation=messages[:message_idx], # here marks the end of the previous messages
+ tokenize=True,
+ return_tensors="pt",
+ padding=False,
+ truncation=True,
+ max_length=max_seq_length,
+ add_generation_prompt=False,
+ ).shape[1]
+ # next, we calculate the end index of this non-assistant message
+ if message_idx < len(messages) - 1 and messages[message_idx + 1]["role"] == "assistant":
+ # for intermediate messages that follow with an assistant message, we need to
+ # set `add_generation_prompt=True` to avoid the assistant generation prefix being included in the loss
+ # (e.g., `<|assistant|>`)
+ message_end_idx = tokenizer.apply_chat_template(
+ conversation=messages[: message_idx + 1],
+ tokenize=True,
+ return_tensors="pt",
+ padding=False,
+ truncation=True,
+ max_length=max_seq_length,
+ add_generation_prompt=True,
+ ).shape[1]
+ else:
+ # for the last message or the message that doesn't follow with an assistant message,
+ # we don't need to add the assistant generation prefix
+ message_end_idx = tokenizer.apply_chat_template(
+ conversation=messages[: message_idx + 1],
+ tokenize=True,
+ return_tensors="pt",
+ padding=False,
+ truncation=True,
+ max_length=max_seq_length,
+ add_generation_prompt=False,
+ ).shape[1]
+ # set the label to -100 for the non-assistant part
+ labels[:, message_start_idx:message_end_idx] = -100
+ if max_seq_length and message_end_idx >= max_seq_length:
+ break
+ attention_mask = torch.ones_like(input_ids)
+ return {
+ "input_ids": input_ids.flatten(),
+ "labels": labels.flatten(),
+ "attention_mask": attention_mask.flatten(),
+ }
diff --git a/dspy/clients/openai.py b/dspy/clients/openai.py
index da9700faf..0d391070a 100644
--- a/dspy/clients/openai.py
+++ b/dspy/clients/openai.py
@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Optional
import openai
from dspy.clients.provider import TrainingJob, Provider
-from dspy.clients.utils_finetune import DataFormat, TrainingStatus, save_data
+from dspy.clients.utils_finetune import TrainDataFormat, TrainingStatus, save_data
_OPENAI_MODELS = [
@@ -123,11 +123,11 @@ class OpenAIProvider(Provider):
job: TrainingJobOpenAI,
model: str,
train_data: List[Dict[str, Any]],
+ train_data_format: Optional[TrainDataFormat],
train_kwargs: Optional[Dict[str, Any]] = None,
- data_format: Optional[DataFormat] = None,
) -> str:
print("[OpenAI Provider] Validating the data format")
- OpenAIProvider.validate_data_format(data_format)
+ OpenAIProvider.validate_data_format(train_data_format)
print("[OpenAI Provider] Saving the data to a file")
data_path = save_data(train_data)
@@ -212,10 +212,10 @@ class OpenAIProvider(Provider):
return status
@staticmethod
- def validate_data_format(data_format: DataFormat):
+ def validate_data_format(data_format: TrainDataFormat):
supported_data_formats = [
- DataFormat.chat,
- DataFormat.completion,
+ TrainDataFormat.CHAT,
+ TrainDataFormat.COMPLETION,
]
if data_format not in supported_data_formats:
err_msg = f"OpenAI does not support the data format {data_format}."
diff --git a/dspy/clients/provider.py b/dspy/clients/provider.py
index 4fbe11684..bd7a860ff 100644
--- a/dspy/clients/provider.py
+++ b/dspy/clients/provider.py
@@ -3,7 +3,7 @@ from concurrent.futures import Future
from threading import Thread
from typing import Any, Dict, List, Optional, Union
-from dspy.clients.utils_finetune import DataFormat
+from dspy.clients.utils_finetune import TrainDataFormat
class TrainingJob(Future):
@@ -12,14 +12,14 @@ class TrainingJob(Future):
thread: Optional[Thread] = None,
model: Optional[str] = None,
train_data: Optional[List[Dict[str, Any]]] = None,
+ train_data_format: Optional[TrainDataFormat] = None,
train_kwargs: Optional[Dict[str, Any]] = None,
- data_format: Optional[DataFormat] = None,
):
self.thread = thread
self.model = model
self.train_data = train_data
+ self.train_data_format = train_data_format
self.train_kwargs = train_kwargs or {}
- self.data_format = data_format
super().__init__()
# Subclasses should override the cancel method to cancel the job; then call
@@ -44,11 +44,18 @@ class Provider:
return False
@staticmethod
- def launch(model: str, launch_kwargs: Optional[Dict[str, Any]] = None):
+ def launch(lm: 'LM', launch_kwargs: Optional[Dict[str, Any]] = None):
+ # Note that "launch" and "kill" methods might be called even if there
+ # is a launched LM or no launched LM to kill. These methods should be
+ # resillient to such cases.
pass
@staticmethod
- def kill(model: str, kill_kwargs: Optional[Dict[str, Any]] = None):
+ def kill(lm: 'LM', launch_kwargs: Optional[Dict[str, Any]] = None):
+ # We assume that LM.launch_kwargs dictionary will contain the necessary
+ # information for a provider to launch and/or kill an LM. This is the
+ # reeason why the argument here is named launch_kwargs and not
+ # kill_kwargs.
pass
@staticmethod
@@ -56,7 +63,7 @@ class Provider:
job: TrainingJob,
model: str,
train_data: List[Dict[str, Any]],
+ train_data_format: Optional[Union[TrainDataFormat, str]],
train_kwargs: Optional[Dict[str, Any]] = None,
- data_format: Optional[Union[DataFormat, str]] = None,
) -> str:
raise NotImplementedError
diff --git a/dspy/clients/utils_finetune.py b/dspy/clients/utils_finetune.py
index 7a8b6b4d2..b77320011 100644
--- a/dspy/clients/utils_finetune.py
+++ b/dspy/clients/utils_finetune.py
@@ -7,12 +7,12 @@ from datasets.fingerprint import Hasher
import dspy
from dspy.adapters.base import Adapter
-from dspy.utils.caching import create_subdir_in_cachedir
+from dspy.utils.caching import DSPY_CACHEDIR
-class DataFormat(str, Enum):
- chat = "chat"
- completion = "completion"
+class TrainDataFormat(str, Enum):
+ CHAT = "chat"
+ COMPLETION = "completion"
class TrainingStatus(str, Enum):
@@ -24,16 +24,20 @@ class TrainingStatus(str, Enum):
cancelled = "cancelled"
-def get_finetune_directory() -> str:
- return create_subdir_in_cachedir(subdir="finetune")
-
-
def infer_data_format(adapter: Adapter) -> str:
if isinstance(adapter, dspy.ChatAdapter):
- return DataFormat.chat
+ return TrainDataFormat.CHAT
raise ValueError(f"Could not infer the data format for: {adapter}")
+def get_finetune_directory() -> str:
+ default_finetunedir = os.path.join(DSPY_CACHEDIR, "finetune")
+ finetune_dir = os.environ.get("DSPY_FINETUNEDIR") or default_finetunedir
+ finetune_dir = os.path.abspath(finetune_dir)
+ os.makedirs(finetune_dir, exist_ok=True)
+ return finetune_dir
+
+
def write_lines(file_path, data):
with open(file_path, "w") as f:
for item in data:
@@ -58,11 +62,11 @@ def save_data(
def validate_data_format(
data: List[Dict[str, Any]],
- data_format: DataFormat,
+ data_format: TrainDataFormat,
):
find_err_funcs = {
- DataFormat.chat: find_data_error_chat,
- DataFormat.completion: find_data_errors_completion
+ TrainDataFormat.CHAT: find_data_error_chat,
+ TrainDataFormat.COMPLETION: find_data_errors_completion
}
err = f"Data format {data_format} is not supported."
assert data_format in find_err_funcs, err
diff --git a/dspy/teleprompt/bettertogether.py b/dspy/teleprompt/bettertogether.py
index f17dee43a..bad685880 100644
--- a/dspy/teleprompt/bettertogether.py
+++ b/dspy/teleprompt/bettertogether.py
@@ -3,10 +3,9 @@ import random
from typing import Callable, List, Optional
import dspy
-from dspy.clients.lm import LM
from dspy.primitives.example import Example
from dspy.primitives.program import Program
-from dspy.teleprompt.bootstrap_finetune import BootstrapFinetune, prepare_student, set_missing_predictor_lms
+from dspy.teleprompt.bootstrap_finetune import BootstrapFinetune, prepare_student, set_missing_predictor_lms, launch_lms, kill_lms
from dspy.teleprompt.random_search import BootstrapFewShotWithRandomSearch
from dspy.teleprompt.teleprompt import Teleprompter
@@ -54,7 +53,7 @@ class BetterTogether(Teleprompter):
) -> Program:
# TODO: We could record acc on a different valset to pick the best
# strategy within the provided strategy
- logger.info("[BetterTogether] Validating the strategy")
+ logger.info("Validating the strategy")
parsed_strategy = strategy.lower().split(self.STRAT_SEP)
if not all([s in ["p", "w"] for s in parsed_strategy]):
@@ -63,7 +62,7 @@ class BetterTogether(Teleprompter):
f"found: {strategy}"
)
- logger.info("[BetterTogether] Preparing the student program...")
+ logger.info("Preparing the student program...")
# TODO: Prepare student returns student.reset_copy(), which is what gets
# optimized. We should make this clear in the doc comments.
student = prepare_student(student)
@@ -72,10 +71,10 @@ class BetterTogether(Teleprompter):
# Make a shallow copy of the trainset, so that we don't change the order
# of the examples in the original trainset
trainset = trainset[:]
- logger.info("[BetterTogether] Compiling the student program...")
+ logger.info("Compiling the student program...")
student = self._run_strategies(parsed_strategy, student, trainset, valset_ratio)
- logger.info("[BetterTogether] BetterTogether has finished compiling the student program")
+ logger.info("BetterTogether has finished compiling the student program")
return student
def _run_strategies(self, parsed_strategy, student, trainset, valset_ratio) -> Program:
@@ -83,16 +82,20 @@ class BetterTogether(Teleprompter):
# "" corresponds to the initial student program
candidate_programs = []
candidate_programs.append(("", student))
+ launched_flag = False
for ind, step_code in enumerate(parsed_strategy):
current_strategy = self.STRAT_SEP.join(parsed_strategy[:ind + 1])
logger.info(
- f"\n[BetterTogether] ########## Step {ind + 1} of {len(parsed_strategy)} - Strategy "
+ f"\n########## Step {ind + 1} of {len(parsed_strategy)} - Strategy "
f"'{current_strategy}' ##########"
)
- logger.info("[BetterTogether] Shuffling the trainset...")
+ logger.info("Shuffling the trainset...")
self.rng.shuffle(trainset)
+ if not launched_flag:
+ launch_lms(student)
+ launched_flag = True
# TODO: Should we reset or just deepcopy? How does resetting affect
# the predictor LMs?
@@ -102,15 +105,19 @@ class BetterTogether(Teleprompter):
student = self._compile_prompt_optimizer(student, trainset, valset_ratio)
elif step_code == "w":
student = self._compile_weight_optimizer(student, trainset)
+ launched_flag = False
# Record the program corresponding to the current strategy
candidate_programs.append((current_strategy, student))
+ if launched_flag:
+ kill_lms(student)
+
student.candidate_programs = candidate_programs
return student
def _compile_prompt_optimizer(self, student, trainset, valset_ratio) -> Program:
- logger.info("[BetterTogether] Preparing for prompt optimization...")
+ logger.info("Preparing for prompt optimization...")
# Sampling a validation set from the trainset for the prompt optimizer
# We drop the hints for prompt optimization
@@ -119,9 +126,6 @@ class BetterTogether(Teleprompter):
prompt_valset = trainset[:num_val]
prompt_trainset = trainset[num_val:]
- logger.info("[BetterTogether] Launching the program LMs for sampling...")
- self._launch_lms(student)
-
# TODO: To make this optimizer general, we need to ensure that all the
# prompt optimizers are accepting a valset or encode a way to check if
# a valset should be passed to an optimizer's compile method.
@@ -130,19 +134,16 @@ class BetterTogether(Teleprompter):
# BootstrapFewShotWithRandomSearch seems to be resetting these. We are
# manually re-setting the LMs here to circumvent this issue, but we
# should consider adressing it in BFRS.
- logger.info("[BetterTogether] Compiling the prompt optimizer...")
+ logger.info("Compiling the prompt optimizer...")
pred_lms = [pred.lm for pred in student.predictors()]
student = self.prompt_optimizer.compile(student, trainset=prompt_trainset, valset=prompt_valset)
for pred, lm in zip(student.predictors(), pred_lms):
pred.lm = lm
- logger.info("[BetterTogether] Killing the LMs used for sampling...")
- self._kill_lms(student)
-
return student
def _compile_weight_optimizer(self, student, trainset) -> Program:
- logger.info("[BetterTogether] Preparing for weight optimization...")
+ logger.info("Preparing for weight optimization...")
# Saving the LMs before compiling the weight optimizer
original_lms = [pred.lm for pred in student.predictors()]
@@ -150,7 +151,7 @@ class BetterTogether(Teleprompter):
# TODO: To make this optimizer general, we need to ensure that all the
# prompt optimizers are accepting a valset or encode a way to check if
# a valset should be passed to an optimizer's compile.
- logger.info("[BetterTogether] Compiling the weight optimizer...")
+ logger.info("Compiling the weight optimizer...")
student = self.weight_optimizer.compile(student, trainset=trainset)
# Updating the train kwargs for the new LMs. This is needed because the
@@ -161,21 +162,3 @@ class BetterTogether(Teleprompter):
self.weight_optimizer.train_kwargs[new_lm] = original_params
return student
-
- @staticmethod
- def _get_unique_lms(program: Program) -> List[LM]:
- lms = [pred.lm for pred in program.predictors()]
- lms = list(set(lms))
- return lms
-
- @staticmethod
- def _launch_lms(program: Program):
- lms = BetterTogether._get_unique_lms(program)
- for lm in lms:
- lm.launch()
-
- @staticmethod
- def _kill_lms(program: Program):
- lms = BetterTogether._get_unique_lms(program)
- for lm in lms:
- lm.kill()
diff --git a/dspy/teleprompt/bootstrap_finetune.py b/dspy/teleprompt/bootstrap_finetune.py
index d0d0bd7c0..aa5169e90 100644
--- a/dspy/teleprompt/bootstrap_finetune.py
+++ b/dspy/teleprompt/bootstrap_finetune.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+import logging
from typing import Any, Callable, Dict, List, Optional, Union
import dspy
@@ -12,6 +13,9 @@ from dspy.primitives.program import Program
from dspy.teleprompt.teleprompt import Teleprompter
+logger = logging.getLogger(__name__)
+
+
class FinetuneTeleprompter(Teleprompter):
def __init__(
@@ -37,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: int = 6
):
# TODO(feature): Inputs train_kwargs (a dict with string keys) and
# adapter (Adapter) can depend on the LM they are used with. We are
@@ -53,43 +57,42 @@ class BootstrapFinetune(FinetuneTeleprompter):
self.exclude_demos = exclude_demos
self.num_threads = num_threads
- def compile(self, student: Program, trainset: List[Example], teacher: Optional[Program] = None) -> Program:
+ def compile(self, student: Program, trainset: List[Example], teacher: Optional[Union[Program, List[Program]]] = None) -> Program:
# TODO: Print statements can be converted to logger.info if we ensure
# that the default DSPy logger logs info level messages in notebook
# environments.
- print("[BootstrapFinetune] Preparing the student and teacher programs...")
- student = prepare_student(student)
- teachers = teacher if isinstance(teacher, list) else [teacher]
- teachers = [prepare_teacher(student, teacher) for teacher in teachers]
+ logger.info("Preparing the student and teacher programs...")
set_missing_predictor_lms(student)
- print("[BootstrapFinetune] Bootstrapping data...")
+ logger.info("Bootstrapping data...")
trace_data = []
- for teacher in teachers:
- set_missing_predictor_lms(teacher)
- trace_data += bootstrap_trace_data(program=teacher, dataset=trainset, metric=self.metric, num_threads=self.num_threads)
+ teachers = teacher if isinstance(teacher, list) else [teacher]
+ teachers = [prepare_teacher(student, t) for t in teachers]
+ 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)
- print("[BootstrapFinetune] Preparing the train data...")
+ logger.info("Preparing the train data...")
key_to_data = {}
for pred_ind, pred in enumerate(student.predictors()):
data_pred_ind = None if self.multitask else pred_ind
training_key = (pred.lm, data_pred_ind)
if training_key not in key_to_data:
train_data, data_format = self._prepare_finetune_data(trace_data=trace_data, lm=pred.lm, pred_ind=data_pred_ind)
- print(f"[BootstrapFinetune] Using {len(train_data)} data points for fine-tuning the model: {pred.lm.model}")
- finetune_kwargs = dict(lm=pred.lm, train_data=train_data, train_kwargs=self.train_kwargs[pred.lm], data_format=data_format)
+ logger.info(f"Using {len(train_data)} data points for fine-tuning the model: {pred.lm.model}")
+ finetune_kwargs = dict(lm=pred.lm, train_data=train_data, train_data_format=data_format, train_kwargs=self.train_kwargs[pred.lm])
key_to_data[training_key] = finetune_kwargs
- print("[BootstrapFinetune] Starting LM fine-tuning...")
+ 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.
err = f"BootstrapFinetune requires `num_threads` to be bigger than or equal to the number of fine-tuning jobs. There are {len(key_to_data)} fine-tuning jobs to start, but the number of threads is: {self.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 jobs will be less than or equal to the number of predictors."
assert len(key_to_data) <= self.num_threads, err
- print(f"[BootstrapFinetune] {len(key_to_data)} fine-tuning job(s) to start")
+ logger.info(f"{len(key_to_data)} fine-tuning job(s) to start")
key_to_lm = self.finetune_lms(key_to_data)
- print("[BootstrapFinetune] Updating the student program with the fine-tuned LMs...")
+ logger.info("Updating the student program with the fine-tuned LMs...")
for pred_ind, pred in enumerate(student.predictors()):
data_pred_ind = None if self.multitask else pred_ind
training_key = (pred.lm, data_pred_ind)
@@ -99,36 +102,42 @@ class BootstrapFinetune(FinetuneTeleprompter):
# train data?
pred.demos = [] if self.exclude_demos else pred.demos
- print("[BootstrapFinetune] BootstrapFinetune has finished compiling the student program")
+ logger.info("BootstrapFinetune has finished compiling the student program")
student._compiled = True
return student
@staticmethod
def finetune_lms(finetune_dict) -> Dict[Any, LM]:
num_jobs = len(finetune_dict)
- print(f"[BootstrapFinetune] Starting {num_jobs} fine-tuning job(s)...")
+ logger.info(f"Starting {num_jobs} fine-tuning job(s)...")
# TODO(nit) Pass an identifier to the job so that we can tell the logs
# coming from different fine-tune threads.
key_to_job = {}
for key, finetune_kwargs in finetune_dict.items():
lm = finetune_kwargs.pop("lm")
+ # TODO: The following line is a hack. We should re-think how to free
+ # up resources for fine-tuning. This might mean introducing a new
+ # provider method (e.g. prepare_for_finetune) that can be called
+ # before fine-tuning is started.
+ logger.info("Calling lm.kill() on the LM to be fine-tuned to free up resources. This won't have any effect if the LM is not running.")
+ lm.kill()
key_to_job[key] = lm.finetune(**finetune_kwargs)
key_to_lm = {}
for ind, (key, job) in enumerate(key_to_job.items()):
key_to_lm[key] = job.result()
job.thread.join()
- print(f"[BootstrapFinetune] Job {ind + 1}/{num_jobs} is done")
+ logger.info(f"Job {ind + 1}/{num_jobs} is done")
return key_to_lm
def _prepare_finetune_data(self, trace_data: List[Dict[str, Any]], lm: LM, pred_ind: Optional[int] = None):
# TODO(nit) Log dataset details/size; make logs nicer
if self.metric:
- print(f"[BootstrapFinetune] Collected data for {len(trace_data)} examples")
+ logger.info(f"Collected data for {len(trace_data)} examples")
trace_data = [d for d in trace_data if d["score"]]
- print(f"[BootstrapFinetune] After filtering with the metric, {len(trace_data)} examples remain")
+ logger.info(f"After filtering with the metric, {len(trace_data)} examples remain")
data = []
adapter = self.adapter[lm] or lm.infer_adapter()
@@ -292,3 +301,19 @@ def assert_no_shared_predictor(program1: Program, program2: Program):
pred_names = ", ".join(id_to_name1[id] for id in shared_ids)
err = f"The programs share the following predictor(s) with each other: {pred_names}"
assert not shared_ids, err
+
+
+def get_unique_lms(program: Program) -> List[LM]:
+ lms = [pred.lm for pred in program.predictors()]
+ lms = list(set(lms))
+ return lms
+
+def launch_lms(program: Program):
+ lms = get_unique_lms(program)
+ for lm in lms:
+ lm.launch()
+
+def kill_lms(program: Program):
+ lms = get_unique_lms(program)
+ for lm in lms:
+ lm.kill()