DSPy: The framework for programming—not prompting—language models
Python
Merge branch 'dev_finetune' into anyscale_dev_finetune
dilarabee6bfe6199b
diff --cc dspy/adapters/base.pyindex 914e31bd1,ddb0ee3e8..3467ca31f--- a/dspy/adapters/base.py+++ b/dspy/adapters/base.py@@@ -7,12 -7,8 +7,8 @@@ class Adaptervalues = []for output in outputs:- try:- value = self.parse(signature, output, _parse_values=_parse_values)- assert set(value.keys()) == set(signature.output_fields.keys()), f"Expected {signature.output_fields.keys()} but got {value.keys()}"- values.append(value)- except Exception as e:- # print(f"Error parsing output: {output} for input: {inputs}")- raise e-+ value = self.parse(signature, output, _parse_values=_parse_values)+ assert set(value.keys()) == set(signature.output_fields.keys()), f"Expected {signature.output_fields.keys()} but got {value.keys()}"+ values.append(value)-++return valuesdiff --cc dspy/clients/anyscale.pyindex 6ec76c082,dea3ca4c5..5844abe55--- a/dspy/clients/anyscale.py+++ b/dspy/clients/anyscale.py@@@ -1,23 -1,13 +1,27 @@@-import time-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Union+import json+import yaml+import os+from concurrent.futures import ThreadPoolExecutor+from collections import defaultdict+import functools- from dspy import logger+ from dspy.utils.logging import loggerfrom dspy.clients.finetune import (FinetuneJob,- TrainingMethod+ TrainingMethod,- get_finetune_directory,- validate_finetune_data,++ save_data,)++from dspy.clients.openai import openai_data_validation, check_message_lengths+import asyncio++try:++ # Importing the AnyScale library for users in the AnyScale workspace, where++ # the library is already installed.+ from anyscale.job import JobConfig+ import anyscale+except ImportError:+ anyscale = None#-------------------------------------------------------------------------------# Variables@@@ -28,6 -18,6 +32,9 @@@ TRAINING_METHODS_ANYSCALE =TrainingMethod.SFT,]++PROVIDER_ANYSCALE = "anyscale"++++#-------------------------------------------------------------------------------# Launching and killing LMs#-------------------------------------------------------------------------------@@@ -48,24 -38,7 +55,19 @@@ def anyscale_model_kill(model: str, lau# Function and classes required for the fine-tune interface#-------------------------------------------------------------------------------++++def is_anyscale_model(model: str) -> bool:++ """Check if the model is an AnyScale model."""++ # TODO: This needs to be implemented to support fine-tuning++ logger.info("Is AnyScale model is not implemented, returning False as a default to not break lm.py")++ return False++++class FinetuneJobAnyScale(FinetuneJob):- def __init__(self,- model: str,- # message_completion_pairs: List[Dict[str, str]],- train_path: str,- eval_path: Optional[str],- train_kwargs: Optional[Dict[str, Any]]=None,- serve_config_path: str = "serve_1B.yaml"- ):- super().__init__(model, train_path, eval_path, train_kwargs)- self.model = model- # self.message_completion_pairs = message_completion_pairs- self.train_path = train_path- self.train_kwargs: Dict[str, Any] = train_kwargs or {}- if "model" not in self.train_kwargs:- self.train_kwargs["model"] = model++++ def __init__(self, *args, **kwargs):+ self.job_id = None- self.serve_config_path = serve_config_path++ super().__init__(*args, **kwargs)def cancel(self):"""Cancel the finetune job."""@@@ -78,507 -51,57 +80,305 @@@"""Get the status of the finetune job."""raise NotImplementedError("Method `status` is not implemented.")- async def run_finetune(self):- """Start the finetune job."""- try:- logger.info("[Finetune] Starting training process...")- if TrainingMethod.SFT not in TRAINING_METHODS_ANYSCALE:- raise NotImplementedError(f"AnyScale can only support {TRAINING_METHODS_ANYSCALE} for the time being")-- logger.info("[Finetune] Reading and validating datasets...")- # Convert the data from prompt completion to OAI compatible messages- train_dataset = read_jsonl(self.train_path)- val_dataset = read_jsonl(self.eval_path) if self.eval_path else None-- if not verify_datasets(train_dataset, val_dataset):- logger.error("[Finetune] Error: Unable to verify arguments")- raise RuntimeError("Unable to verify argument")-- logger.info("[Finetune] Converting data to JSONL format...")- for path, dataset in [(self.train_path, train_dataset), (self.eval_path, val_dataset)]:- if not (path and dataset):- continue- write_jsonl(path, dataset)-- logger.info("[Finetune] Submitting data to remote storage...")- remote_train_path, remote_eval_path = submit_data(train_path=self.train_path, eval_path=self.eval_path)- logger.info(f"[Finetune] Data submitted. Remote train path: {remote_train_path}, Remote eval path: {remote_eval_path}")-- logger.info("[Finetune] Generating configuration files...")- _, compute_config = generate_config_files(train_path=remote_train_path, eval_path=remote_eval_path, **self.train_kwargs)-- logger.info("[Finetune] Starting remote training...")- job_id = start_remote_training(compute_config=compute_config, **self.train_kwargs)- self.job_id = job_id- logger.info(f"[Finetune] Remote training started. Job ID: {job_id}")-- logger.info("[Finetune] Waiting for training to complete...")- await self.wait_for_training()- logger.info("[Finetune] Training completed.")-- logger.info("[Finetune] Retrieving model information...")- model_info = get_model_info(job_id)- logger.info(f"[Finetune] Model info retrieved: {model_info}")-- storage_uri = model_info["storage_uri"]- logger.info(f"[Finetune] Copying LoRA weights from {storage_uri}...")- model_names, lora_dynamic_path = copy_lora_weights(storage_uri, model_info, job_id)- logger.info(f"[Finetune] LoRA weights copied. Model names: {model_names}")-- logger.info("[Finetune] Setting result in future object...")- for model_name in model_names:- yield model_name- logger.info("[Finetune] Training process completed successfully.")-- logger.info("[Finetune] Updating model config with the proper dynamic path")- update_model_config(lora_dynamic_path, self.serve_config_path)-- except Exception as e:- logger.error(f"[Finetune] Error occurred during training: {str(e)}")- raise e-- # executor = ThreadPoolExecutor(max_workers=1)- # executor.submit(- # execute_finetune_job,- # finetune_job,- # launch_kwargs=launch_kwargs,- # cache_finetune=cache_finetune- # )- # executor.shutdown(wait=False)-- async def wait_for_training(self):- """Wait for the training to complete in a non-blocking manner."""- loop = asyncio.get_running_loop()+-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]],++ train_data: List[Dict[str, Any]],+ train_kwargs: Optional[Dict[str, Any]]=None,- ) -> str:- """Fine-tune with AnyScale."""- # Fake fine-tuning- logger.info("[Finetune] Fake fine-tuning")- train_kwargs = train_kwargs or {}++ ) -> Union[str, Exception]:++ """Start the finetune job."""++ try:++ train_kwargs = train_kwargs or {}++ assert "model" not in train_kwargs, "Model should not be in the train_kwargs"++ train_kwargs["model"] = model++ train_method = TrainingMethod.SFT # Note: This could be an argument++++ logger.info("[Finetune] Starting training process...")++ if train_method not in TRAINING_METHODS_ANYSCALE:++ raise NotImplementedError(f"AnyScale can only support {TRAINING_METHODS_ANYSCALE} for the time being")+- # Run the blocking `anyscale.job.wait` in a separate thread++ logger.info("[Finetune] Retrieving the `serve_config_path` if provided, otherwise defaulting to `serve_1B.yaml`...")++ serve_config_path = train_kwargs.pop("serve_config_path", "serve_1B.yaml")++++ logger.info("[Finetune] Validating the dataset format...")++ if not verify_dataset(train_data):++ # TODO: Does AnyScale support text completion models?++ err = "[Finetune] Error: Unable to verify that the dataset is in the correct format."++ logger.error(err)++ raise RuntimeError(err)++++ logger.info("[Finetune] Converting data to JSONL format...")++ data_path = save_data(train_data, provider_name=PROVIDER_ANYSCALE)++++ logger.info("[Finetune] Submitting data to remote storage...")++ remote_train_path, _ = submit_data(train_path=data_path, eval_path=None)++ logger.info(f"[Finetune] Data submitted. Remote train path: {remote_train_path}")++++ logger.info("[Finetune] Generating configuration files...")++ _, compute_config = generate_config_files(train_path=remote_train_path, eval_path=None, **train_kwargs)+- with ThreadPoolExecutor() as pool:- await loop.run_in_executor(pool, functools.partial(anyscale.job.wait, id=self.job_id, timeout_s=18000))++ logger.info("[Finetune] Starting remote training...")++ job_id = start_remote_training(compute_config=compute_config, **train_kwargs)++ job.job_id = job_id++ logger.info(f"[Finetune] Remote training started. Job ID: {job.job_id}")+-++ logger.info("[Finetune] Waiting for training to complete...")++ wait_for_training(job.job_id)++ logger.info("[Finetune] Training completed.")+++ logger.info("[Finetune] Retrieving model information...")++ model_info = get_model_info(job.job_id)++ logger.info(f"[Finetune] Model info retrieved: {model_info}")+- 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++ storage_uri = model_info["storage_uri"]++ logger.info(f"[Finetune] Copying LoRA weights from {storage_uri}...")++ model_names, lora_dynamic_path = copy_lora_weights(storage_uri, model_info, job.job_id)++ logger.info(f"[Finetune] LoRA weights copied. Model names: {model_names}")+- # async def _run_finetune(job: FinetuneJobAnyScale):- # try:- # logger.info("[Finetune] Starting training process...")- # if TrainingMethod.SFT not in TRAINING_METHODS_ANYSCALE:- # raise NotImplementedError(f"AnyScale can only support {TRAINING_METHODS_ANYSCALE} for the time being")-- # logger.info("[Finetune] Reading and validating datasets...")- # # Convert the data from prompt completion to OAI compatible messages- # train_dataset = read_jsonl(train_path)- # val_dataset = read_jsonl(eval_path) if eval_path else None-- # if not verify_datasets(train_dataset, val_dataset):- # logger.error("[Finetune] Error: Unable to verify arguments")- # raise RuntimeError("Unable to verify argument")-- # logger.info("[Finetune] Converting data to JSONL format...")- # for path, dataset in [(train_path, train_dataset), (eval_path, val_dataset)]:- # if not (path and dataset):- # continue- # write_jsonl(path, dataset)-- # logger.info("[Finetune] Submitting data to remote storage...")- # remote_train_path, remote_eval_path = submit_data(train_path=train_path, eval_path=eval_path)- # logger.info(f"[Finetune] Data submitted. Remote train path: {remote_train_path}, Remote eval path: {remote_eval_path}")-- # logger.info("[Finetune] Generating configuration files...")- # _, compute_config = generate_config_files(train_path=remote_train_path, eval_path=remote_eval_path, **train_kwargs)-- # logger.info("[Finetune] Starting remote training...")- # job_id = start_remote_training(compute_config=compute_config, **train_kwargs)- # job.job_id = job_id- # logger.info(f"[Finetune] Remote training started. Job ID: {job_id}")-- # logger.info("[Finetune] Waiting for training to complete...")- # wait_for_training(job)- # logger.info("[Finetune] Training completed.")-- # logger.info("[Finetune] Retrieving model information...")- # model_info = get_model_info(job_id)- # logger.info(f"[Finetune] Model info retrieved: {model_info}")-- # storage_uri = model_info["storage_uri"]- # logger.info(f"[Finetune] Copying LoRA weights from {storage_uri}...")- # model_names = copy_lora_weights(storage_uri, model_info, job_id)- # logger.info(f"[Finetune] LoRA weights copied. Model names: {model_names}")-- # logger.info("[Finetune] Setting result in future object...")- # job.set_result(model_names)- # logger.info("[Finetune] Training process completed successfully.")-- # except Exception as e:- # logger.error(f"[Finetune] Error occurred during training: {str(e)}")- # job.set_exception(e)--- # async def finetune_anyscale(- # model: str,- # train_path: str,- # eval_path: Optional[str],- # train_kwargs: Optional[Dict[str, Any]] = None,- # ) -> FinetuneJobAnyScale:- # """- # Initiate fine-tuning process for an Anyscale model.-- # Args:- # model (str): The name of the Anyscale model to fine-tune.- # message_completion_pairs (List[Dict[str, str]]): List of prompt-completion pairs for training.- # train_kwargs (Optional[Dict[str, Any]]): Additional training parameters.-- # Returns:- # FinetuneJobAnyScale: A job object representing the fine-tuning process.- # """- # train_kwargs = train_kwargs or {}--++ logger.info("[Finetune] Setting result in future object...")++ last_model_checkpoint = model_names[-1] # TODO: Is this correct?++ logger.info("[Finetune] Training process completed successfully.")++++ # TODO: Is this the right place to call update_model_config?++ logger.info("[Finetune] Updating model config with the proper dynamic path")++ update_model_config(lora_dynamic_path, serve_config_path)++++ return last_model_checkpoint++++ except Exception as e:++ logger.error(f"[Finetune] Error occurred during training: {str(e)}")++ raise e++++++#-------------------------------------------------------------------------------++# Custom functions to support the finetune_* function++#-------------------------------------------------------------------------------++++def wait_for_training(job_id):++ """Wait for the training to complete."""++ anyscale.job.wait(id=job_id, timeout_s=18000)+- # executor = ThreadPoolExecutor(max_workers=1)- # executor.submit(_run_finetune)-- # return job++def update_model_config(lora_dynamic_path: str, serve_config_path: str):+ """Update the model config storage location with the job_id."""+ with open(serve_config_path, "r") as f:+ serve_config = yaml.safe_load(f)++ model_config_location = serve_config["applications"][0]["args"]["llm_configs"][0]++ with open(model_config_location, "r") as f:+ model_config = yaml.safe_load(f)++ model_config["lora_config"]["dynamic_lora_loading_path"] = lora_dynamic_path++ with open(model_config_location, "w") as f:+ yaml.safe_dump(model_config, f)+- def verify_datasets(dataset: List[dict[str, Any]], valset: Optional[List[dict[str, Any]]]) -> bool:++def verify_dataset(dataset: List[dict[str, Any]]) -> bool:+ """Verify the training arguments before starting training."""- def validate_dataset(name, data: dict[str, Any]) -> bool:- dataset_validation = openai_data_validation(data)-- if dataset_validation:- logger.error(f"Dataset validation failed: {dataset_validation}")- return False-- if name == "train":- convo_lens = check_message_lengths(data)- estimate_cost(data, convo_lens=convo_lens)- return True++ dataset_validation = openai_data_validation(dataset)+- datasets = {"train": dataset}- if valset:- datasets["val"] = valset++ if dataset_validation:++ logger.error(f"Dataset validation failed: {dataset_validation}")++ return False+- for name, data in datasets.items():- if not validate_dataset(name, data):- return False++ # TODO: Is this still useful?++ convo_lens = check_message_lengths(dataset)+ return True++++def submit_data(train_path: str, eval_path: Optional[str]):+ """Upload the data to the Workspace cloud storage."""+ storage = os.environ['ANYSCALE_ARTIFACT_STORAGE']++ datasets = {"train": train_path}+ if eval_path:+ datasets["val"] = eval_path++ fine_tuning_file_ids = {}+ for name, path in datasets.items():+ num_items = len(read_jsonl(path))+ logger.info(f"Number of items in {name} data: {num_items}")++ remote_path = os.path.join(storage, path.split("/")[-1])+ logger.info(f"Uploading {name} data to S3 at {remote_path}")+ if remote_path[:2] == "s3":+ os.system(f"aws s3 cp {path} {remote_path}")+ elif remote_path[:2] == "gs":+ os.system(f"gcloud storage cp {path} {remote_path}")+ else:+ os.system(f"cp {path} {remote_path}")+ logger.info(f"Copied {path} to {remote_path}")+ fine_tuning_file_ids[name] = remote_path++ return fine_tuning_file_ids["train"], fine_tuning_file_ids.get("val", None)++++def generate_config_files(train_path: str, eval_path: Optional[str], **kwargs):+ base_model_yaml_path = kwargs.get("train_config_yaml", None)+ assert kwargs["model"] is not None, "Model is required to generate the config files"++ use_lora = kwargs.get("use_lora", False)+ example_dir = ""+ lora_path = "configs/training/lora" if use_lora else "configs/training/full_param"+++ if not base_model_yaml_path:+ def get_yaml_config(model_name):+ if "llama" in model_name.lower():+ if "70b" in model_name:+ return "llama-3-70b.yaml"+ elif "13b" in model_name:+ return "llama-3-70b.yaml"+ else:+ return "llama-3-8b.yaml"+ elif "mistral" in model_name.lower():+ if "mixtral" in model_name.lower():+ return "mixtral-8x7b.yaml"+ else:+ return "mistral-7b.yaml"+ else:+ raise RuntimeError("No default yaml found for the model")++ default_model_yaml_path = get_yaml_config(kwargs["model"])+ base_model_yaml_path = os.path.join(example_dir, lora_path, default_model_yaml_path)+ logger.info(f"Using default yaml template for model: {base_model_yaml_path}")++ model_config_data = yaml.safe_load(open(base_model_yaml_path, "r"))+ model_config_data.update(kwargs.get("hyperparameters", {}))++ model_config_data["model_id"] = kwargs["model"]++ custom_modifications = {+ "model_id": kwargs["model"],+ "train_path": train_path,+ "valid_path": eval_path,+ "logger": {+ "provider": "wandb",+ },+ "num_checkpoints_to_keep": 10+ }+ if kwargs.get("output_dir", None):+ custom_modifications["output_dir"] = kwargs["output_dir"]++ model_config_data.update(custom_modifications)+ model_config_data = {k: v for k, v in model_config_data.items() if v is not None}++ def freeze(d):+ if isinstance(d, dict):+ return tuple(sorted((key, freeze(value)) for key, value in d.items()))+ elif isinstance(d, list):+ return tuple(freeze(value) for value in sorted(d))+ elif isinstance(d, set):+ return tuple(freeze(value) for value in sorted(d))+ return d++ def hash_dict(d):+ return hash(freeze(d))+ dict_sorted_hash = hash_dict(model_config_data)+ if dict_sorted_hash < 0:+ dict_sorted_hash = -dict_sorted_hash+ filename = f"model_config_dspy_{dict_sorted_hash}.yaml"+ logger.info(f"Model config data: {model_config_data}")+ yaml.safe_dump(model_config_data, open(filename, "w"))++ ft_path = os.path.join("utils", "ft.py")++ compute_config_dict = {+ "name": "dspy-llmforge-fine-tuning-job",+ "entrypoint": f"llmforge anyscale finetune {filename}",+ "working_dir": ".",+ "image_uri": "localhost:5555/anyscale/llm-forge:0.5.6",+ "requirements": [+ "wandb",+ ],+ "env_vars": {+ "WANDB_API_KEY": os.environ.get("WANDB_API_KEY", ""),+ "HF_TOKEN": os.environ.get("HF_TOKEN", ""),+ "HF_HOME": os.environ.get("HF_HOME", ""),+ }+ }+ compute_config_kwargs = kwargs.get("compute_config", {})+ compute_config_dict.update(compute_config_kwargs)+ compute_config = JobConfig(**compute_config_dict)++ job_runner_config_path = kwargs.get("compute_yaml_path", "job_runner_config.yaml")++ return job_runner_config_path, compute_config++++def start_remote_training(compute_config, **kwargs) -> str:+ job_id: str = anyscale.job.submit(compute_config)+ return job_id++++def wait_for_training(job):+ logger.info("Waiting for training to complete")+ anyscale.job.wait(id=job.job_id, timeout_s=18000)++++def get_model_info(job_id):+ return anyscale.llm.model.get(job_id=job_id).to_dict()++++def copy_lora_weights(storage_uri, model_info, job_id):try:- logger.info("[Finetune] Validate the formatting of the fine-tuning data")- training_method = TrainingMethod.SFT # Hardcoded- validate_finetune_data(message_completion_pairs, training_method)- time.sleep(5)- logger.info("[Finetune] Done!")-- logger.info("[Finetune] Saving the data to a file")- finetune_parent_dir = get_finetune_directory()- # 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 = "anyscale_model" # Hardcoded- time.sleep(1)- logger.info("[Finetune] Done!")-- return model+ from google.cloud import storage++ storage_client = storage.Client()++ bucket_name = storage_uri.split('/')[2]+ source_folder = '/'.join(storage_uri.split('/')[3:-1])+ logger.info(f"Source folder: {source_folder}")+ bucket = storage_client.bucket(bucket_name)++ blobs = bucket.list_blobs(prefix=source_folder)++ subfolders = set()+ for blob in blobs:+ if '/' in blob.name[len(source_folder):]:+ subfolder = blob.name.split('/')[:-1]+ subfolders.add('/'.join(subfolder))++ base_model_id = model_info["base_model_id"]+ lora_dynamic_path = f"dspy/lora_weights/{job_id}/{base_model_id}"++ model_names = []+ for subfolder in subfolders:+ subfolder_name = subfolder.split('/')[-1]+ destination_folder = f"{lora_dynamic_path}:{subfolder_name}"+ if subfolder_name.startswith("epoch"):+ model_names.append("/".join(destination_folder.split("/")[-2:]))+ else:+ continue++ subfolder_blobs = bucket.list_blobs(prefix=subfolder)++ for blob in subfolder_blobs:+ source_blob = bucket.blob(blob.name)+ destination_blob_name = f"{destination_folder}/{blob.name.split('/')[-1]}"+ bucket.copy_blob(source_blob, bucket, destination_blob_name)+ logger.info(f"Copied {source_blob.name} to {destination_blob_name}")++ logger.info(f"All subfolders copied to: gs://{bucket_name}/{lora_dynamic_path}")+ completed_path = f"gs://{bucket_name}/{lora_dynamic_path}"+ return model_names, completed_path+except Exception as e:- logger.error(f"[Finetune] Error: {e}")- raise e+ logger.error(f"An error occurred: {str(e)}")+ raise e++++def read_jsonl(filename):+ with open(filename, "r") as f:+ return [json.loads(line) for line in f]+++++# TODO: Is it true that we don't need this function anymore?+def write_jsonl(filename, data):+ with open(filename, "w") as f:+ for item in data:+ f.write(json.dumps(item) + "\n")-- # Fine tuning utils- def openai_data_validation(dataset: List[dict[str, Any]]) -> Union[dict[str, Any], AssertionError]:- format_errors = defaultdict(int)- for ex in dataset:- if not isinstance(ex, dict):- format_errors["data_type"] += 1- continue-- messages = ex.get("messages", None)- if not messages:- format_errors["missing_messages_list"] += 1- continue-- for message in messages:- if "role" not in message or "content" not in message:- format_errors["message_missing_key"] += 1-- if any(k not in ("role", "content", "name", "function_call", "weight") for k in message):- format_errors["message_unrecognized_key"] += 1-- if message.get("role", None) not in ("system", "user", "assistant", "function"):- format_errors["unrecognized_role"] += 1-- content = message.get("content", None)- function_call = message.get("function_call", None)-- if (not content and not function_call) or not isinstance(content, str):- format_errors["missing_content"] += 1-- if not any(message.get("role", None) == "assistant" for message in messages):- format_errors["example_missing_assistant_message"] += 1-- if format_errors:- return format_errors- return None-- def num_tokens_from_messages(messages, tokens_per_message=3, tokens_per_name=1):- import tiktoken- encoding = tiktoken.get_encoding("cl100k_base")-- num_tokens = 0- for message in messages:- num_tokens += tokens_per_message- for key, value in message.items():- num_tokens += len(encoding.encode(value))- if key == "name":- num_tokens += tokens_per_name- num_tokens += 3- return num_tokens-- def num_assistant_tokens_from_messages(messages):- import tiktoken- encoding = tiktoken.get_encoding("cl100k_base")-- num_tokens = 0- for message in messages:- if message["role"] == "assistant":- num_tokens += len(encoding.encode(message["content"]))- return num_tokens-- def check_message_lengths(dataset: List[dict[str, Any]]) -> list[int]:- n_missing_system = 0- n_missing_user = 0- n_messages = []- convo_lens = []- assistant_message_lens = []-- for ex in dataset:- messages = ex["messages"]- if not any(message["role"] == "system" for message in messages):- n_missing_system += 1- if not any(message["role"] == "user" for message in messages):- n_missing_user += 1- n_messages.append(len(messages))- convo_lens.append(num_tokens_from_messages(messages))- assistant_message_lens.append(num_assistant_tokens_from_messages(messages))- n_too_long = sum([length > 16385 for length in convo_lens])-- if n_too_long > 0:- logger.info(f"There are {n_too_long} examples that may be over the 16,385 token limit, they will be truncated during fine-tuning.")-- if n_missing_system > 0:- logger.info(f"There are {n_missing_system} examples that are missing a system message.")-- if n_missing_user > 0:- logger.info(f"There are {n_missing_user} examples that are missing a user message.")-- return convo_lens-- def estimate_cost(dataset: dict[str, Any], tokens_per_message=3, tokens_per_name=1, convo_lens=None):- MAX_TOKENS_PER_EXAMPLE = 16385- TARGET_EPOCHS = 3- MIN_TARGET_EXAMPLES = 100- MAX_TARGET_EXAMPLES = 25000- MIN_DEFAULT_EPOCHS = 1- MAX_DEFAULT_EPOCHS = 25-- n_epochs = TARGET_EPOCHS- n_train_examples = len(dataset)- if n_train_examples * TARGET_EPOCHS < MIN_TARGET_EXAMPLES:- n_epochs = min(MAX_DEFAULT_EPOCHS, MIN_TARGET_EXAMPLES // n_train_examples)- elif n_train_examples * TARGET_EPOCHS > MAX_TARGET_EXAMPLES:- n_epochs = max(MIN_DEFAULT_EPOCHS, MAX_TARGET_EXAMPLES // n_train_examples)-- if convo_lens is None:- convo_lens = check_message_lengths(dataset)-- n_billing_tokens_in_dataset = sum(min(MAX_TOKENS_PER_EXAMPLE, length) for length in convo_lens)-- logger.info(f"""The charge for finetuning is determined by the number of epochs multiplied by the number of billing tokens in the dataset. Here are the stats for this training dataset:- num_billing_tokens: {n_billing_tokens_in_dataset}- n_epochs: {n_epochs}- num_total_charge_tokens: {n_epochs * n_billing_tokens_in_dataset}""")diff --cc dspy/clients/finetune.pyindex 8082eb6f6,3c14be363..c4464fbf3--- a/dspy/clients/finetune.py+++ b/dspy/clients/finetune.py@@@ -1,7 -1,7 +1,8 @@@from abc import abstractmethod+ from concurrent.futures import Futurefrom enum import Enumimport os+from pathlib import Pathfrom typing import List, Dict, Any, Optionalimport ujson@@@ -11,10 -12,8 +13,12 @@@ from datasets.fingerprint import Hashe# Set the directory to save the fine-tuned modelsdef 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- alternative_path = os.path.join(os.getcwd(), '.dspy_finetune')-- return os.environ.get('DSPY_FINETUNEDIR') or alternative_path++ # TODO: Move to a centralized location with all the other env variables++ dspy_cachedir = os.environ.get("DSPY_CACHEDIR")++ dspy_cachedir = dspy_cachedir or os.path.join(Path.home(), ".dspy_cache")++ finetune_dir = os.path.join(dspy_cachedir, 'finetune')++ finetune_dir = os.path.abspath(finetune_dir)++ return finetune_dirFINETUNE_DIRECTORY = get_finetune_directory()@@@ -42,24 -51,18 +56,18 @@@ class FinetuneJob(Future)def __init__(self,model: str,- # message_completion_pairs: List[Dict[str, str]],- train_path: str,- eval_path: Optional[str],- message_completion_pairs: List[Dict[str, str]],++ train_data: List[Dict[str, Any]],train_kwargs: Optional[Dict[str, Any]]=None,):self.model = model- # self.message_completion_pairs = message_completion_pairs- self.train_path = train_path- self.eval_path = eval_path- self.message_completion_pairs = message_completion_pairs++ self.train_data = train_dataself.train_kwargs: Dict[str, Any] = train_kwargs or {}super().__init__()def get_kwargs(self):return dict(model=self.model,- # message_completion_pairs=self.message_completion_pairs,- train_path=self.train_path,- eval_path=self.eval_path,- message_completion_pairs=self.message_completion_pairs,++ train_data=self.train_data,train_kwargs=self.train_kwargs,)diff --cc dspy/clients/lm.pyindex 10a7615dc,014025efc..e6cfcff3d--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@@ -21,16 -22,21 +22,17 @@@ from dspy.clients.anyscale import)import litellm- import ujsonfrom 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")+++ 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 = Falseif "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,@@@ -102,16 -123,13 +119,13 @@@self_hosted_model_kill(self.model, self.launch_kwargs)elif is_anyscale_model(self.model):anyscale_model_kill(self.model, self.launch_kwargs)- logger.debug(f"`LM.kill()` is called for the auto-launched model {self.model} -- no action is taken.")-- async def finetune(self,- # message_completion_pairs: List[Dict[str, str]],- method: TrainingMethod,- train_path: str,- eval_path: Optional[str],- provider: str = "openai",+ msg = f"`kill()` is called for the auto-launched model {self.model}"+ msg += " -- no action is taken!"+ logger.info(msg)++ def finetune(self,- message_completion_pairs: List[Dict[str, str]],++ train_data: List[Dict[str, Any]],train_kwargs: Optional[Dict[str, Any]]=None,- launch_kwargs: Optional[Dict[str, Any]]=None,cache_finetune: bool = True,) -> FinetuneJob:"""Start model fine-tuning, if supported."""@@@ -124,22 -149,21 +145,29 @@@FinetuneJobClass = get_provider_finetune_job_class(provider=provider)finetune_job = FinetuneJobClass(model=self.model,- train_path=train_path,- eval_path=eval_path,- message_completion_pairs=message_completion_pairs,++ train_data=train_data,train_kwargs=train_kwargs,)- job = finetune_job.run_finetune()+ # Start asyncronous training+ executor = ThreadPoolExecutor(max_workers=1)+ executor.submit(+ execute_finetune_job,+ finetune_job,+ lm=self,+ cache_finetune=cache_finetune+ )+ executor.shutdown(wait=False)- return job+ return finetune_job++ def copy(self, **kwargs):+ """Returns a copy of the language model with the same parameters."""+ kwargs = {**self.kwargs, **kwargs}+ # model = kwargs.pop("model") or self.model+ init_kwargs = dict(model=self.model, model_type=self.model_type, cache=self.cache, temperature=self.kwargs["temperature"], max_tokens=self.kwargs["max_tokens"])+ init_kwargs = {**init_kwargs, **kwargs}+ return self.__class__(**init_kwargs)@functools.lru_cache(maxsize=None)@@@ -223,12 -247,13 +251,13 @@@ def _inspect_history(lm, n: int = 1)from dspy.clients.openai import (FinetuneJobOpenAI,- is_openai_model+ is_openai_model,- finetune_openai++ finetune_openai,)from dspy.clients.anyscale import (FinetuneJobAnyScale,- # is_anyscale_model,- # finetune_anyscale+ is_anyscale_model,- finetune_anyscale++ finetune_anyscale,)@@@ -318,13 -333,13 +337,13 @@@ def execute_finetune_jobdef cached_finetune(job,model: str,-- message_completion_pairs: List[Dict[str, str]],++ train_data: List[Dict[str, Any]],train_kwargs: Optional[Dict[str, Any]]=None,) -> Union[str, ValueError]:return finetune(job=job,model=model,-- message_completion_pairs=message_completion_pairs,++ train_data=train_data,train_kwargs=train_kwargs,)@@@ -332,25 -347,25 +351,25 @@@def finetune(job,model: str,-- message_completion_pairs: List[Dict[str, str]],++ train_data: List[Dict[str, Any]],train_kwargs: Optional[Dict[str, Any]]=None,- ) -> Union[str, ValueError]:+ ) -> Union[str, Exception]:"""Fine-tune a new model based on the given model."""# Get the fine-tuning providertry:provider = _get_supported_finetune_provider(model)- except ValueError as err:- raise err- # Get the finetune function- provider_finetune_function = get_provider_finetune_function(provider)+ # 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,- )+ # 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_data=train_data,+ train_kwargs=train_kwargs,+ )+ except Exception as err:+ raise errreturn modeldiff --cc dspy/clients/openai.pyindex 3eee3a934,f7feb961a..dae20b9d0--- a/dspy/clients/openai.py+++ b/dspy/clients/openai.py@@@ -114,59 -132,236 +132,291 @@@ class FinetuneJobOpenAI(FinetuneJob)def finetune_openai(job: FinetuneJobOpenAI,model: str,-- message_completion_pairs: List[Dict[str, str]],++ train_data: List[Dict[str, Any]],train_kwargs: Optional[Dict[str, Any]]=None,- ) -> str:- """Fine-tune an OpenAI model."""- # Fake fine-tuning+ ) -> Union[str, Exception]:train_kwargs = train_kwargs or {}- train_data = message_completion_pairs+ train_method = TrainingMethod.SFT # Note: This could be an argument++ # Validate train data and method+ logger.info("[Finetune] Validating the formatting of the data")+ _validate_data(train_data, train_method)+ logger.info("[Finetune] Done!")++ # Convert to the OpenAI format+ logger.info("[Finetune] Converting the data to the OpenAI format")+ # TODO: Should we use the system prompt?+ train_data = _convert_data(train_data)+ logger.info("[Finetune] Done!")++ # Save to a file+ logger.info("[Finetune] Saving the data to a file")+ data_path = save_data(train_data, provider_name=PROVIDER_OPENAI)+ logger.info("[Finetune] Done!")++ # Upload the data to the cloud+ logger.info("[Finetune] Uploading the data to the provider")+ provider_file_id = _upload_data(data_path)+ job.provider_file_id = provider_file_id+ logger.info("[Finetune] Done!")++ logger.info("[Finetune] Start remote training")+ # We utilize model and train_kwargs here+ provider_job_id = _start_remote_training(+ train_file_id=job.provider_file_id,+ model=model,+ train_kwargs=train_kwargs,+ )+ job.provider_job_id = provider_job_id+ # job.provider_job_id = "ftjob-ZdEL1mUDk0dwdDuZJQOng8Vv"+ logger.info("[Finetune] Done!")++ logger.info("[Finetune] Wait for training to complete")+ # TODO: Would it be possible to stream the logs?+ _wait_for_job(job)+ logger.info("[Finetune] Done!")++ logger.info("[Finetune] Get trained model if the run was a success")+ model = _get_trained_model(job)+ logger.info("[Finetune] Done!")++ return model+++ #-------------------------------------------------------------------------------+ # Custom functions to support the finetune_* function+ #-------------------------------------------------------------------------------++ _SUPPORTED_TRAINING_METHODS = [+ TrainingMethod.SFT,+ ]++ def _get_training_status(job_id: str) -> Union[TrainingStatus, Exception]:+ # TODO: Should this type be shared across all fine-tune clients?+ provider_status_to_training_status = {+ "validating_files": TrainingStatus.pending,+ "queued": TrainingStatus.pending,+ "running": TrainingStatus.running,+ "succeeded": TrainingStatus.succeeded,+ "failed": TrainingStatus.failed,+ "cancelled": TrainingStatus.cancelled,+ }+ # Check if there is an active job+ if job_id is None:+ logger.info("There is no active job.")+ return TrainingStatus.not_started++ err_msg = f"Job with ID {job_id} does not exist."+ assert _does_job_exist(job_id), err_msg++ # Retrieve the provider's job and report the status+ provider_job = openai.fine_tuning.jobs.retrieve(job_id)+ provider_status = provider_job.status+ status = provider_status_to_training_status[provider_status]++ return status+++ def _does_job_exist(job_id: str) -> bool:+ try:+ # TODO: Error handling is vague+ openai.fine_tuning.jobs.retrieve(job_id)+ return True+ except Exception as e:+ return False+++ def _does_file_exist(file_id: str) -> bool:try:- # 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!")+ # TODO: Error handling is vague+ openai.files.retrieve(file_id)+ return True+ except Exception as e:+ return False+++ def _is_terminal_training_status(status: TrainingStatus) -> bool:+ return status in [+ TrainingStatus.succeeded,+ TrainingStatus.failed,+ TrainingStatus.cancelled,+ ]+++ def _validate_data(+ data: Dict[str, str],+ train_method: TrainingMethod+ ) -> Optional[Exception]:+ # Check if this train method is supported+ if train_method not in _SUPPORTED_TRAINING_METHODS:+ err_msg = f"OpenAI does not support the training method {train_method}."+ raise ValueError(err_msg)++ validate_finetune_data(data, train_method)+++ def _convert_data(+ data: List[Dict[str, str]],+ system_prompt: Optional[str]=None,+ ) -> Union[List[Dict[str, Any]], Exception]:+ # Item-wise conversion function+ def _row_converter(d):+ messages = [+ {"role": "user", "content": d["prompt"]},+ {"role": "assistant", "content": d["completion"]}+ ]+ if system_prompt:+ messages.insert(0, {"role": "system", "content": system_prompt})+ messages_dict = {"messages": messages}+ return messages_dict- logger.error("[Finetune] Uploading the data to the cloud")- time.sleep(1)- logger.error("[Finetune] Done!")+ # Convert the data to the OpenAI format; validate the converted data+ converted_data = list(map(_row_converter, data))+ openai_data_validation(converted_data)+ return converted_data+++ def _upload_data(data_path: str) -> str:+ # Upload the data to the provider+ provider_file = openai.files.create(+ file=open(data_path, "rb"),+ purpose="fine-tune",+ )+ return provider_file.id- 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!")+ def _start_remote_training(+ train_file_id: str,+ model: id,+ train_kwargs: Optional[Dict[str, Any]]=None+ ) -> str:+ train_kwargs = train_kwargs or {}+ provider_job = openai.fine_tuning.jobs.create(+ model=model,+ training_file=train_file_id,+ hyperparameters=train_kwargs,+ )+ return provider_job.id- 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")+ def _wait_for_job(+ job: FinetuneJobOpenAI,+ poll_frequency: int=60,+ ):+ while not _is_terminal_training_status(job.status()):+ time.sleep(poll_frequency)- return model- except Exception as e:- logger.error(f"[Finetune] Error: {e}")- raise e+ def _get_trained_model(job):+ status = job.status()+ if status != TrainingStatus.succeeded:+ err_msg = f"Job status is {status}."+ err_msg += f" Must be {TrainingStatus.succeeded} to retrieve the model."+ logger.error(err_msg)+ raise Exception(err_msg)++ provider_job = openai.fine_tuning.jobs.retrieve(job.provider_job_id)+ finetuned_model = provider_job.fine_tuned_model+ return finetuned_model#-------------------------------------------------------------------------------- # Custom functions+ # OpenAI utility function(s)#-------------------------------------------------------------------------------- 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)++ # Adapted from https://cookbook.openai.com/examples/chat_finetuning_data_prep+ def openai_data_validation(dataset: List[dict[str, Any]]):+ format_errors = defaultdict(int)+ for ex in dataset:+ if not isinstance(ex, dict):+ format_errors["data_type"] += 1+ continue++ messages = ex.get("messages", None)+ if not messages:+ format_errors["missing_messages_list"] += 1+ continue++ for message in messages:+ if "role" not in message or "content" not in message:+ format_errors["message_missing_key"] += 1++ if any(k not in ("role", "content", "name", "function_call", "weight") for k in message):+ format_errors["message_unrecognized_key"] += 1++ if message.get("role", None) not in ("system", "user", "assistant", "function"):+ format_errors["unrecognized_role"] += 1++ content = message.get("content", None)+ function_call = message.get("function_call", None)++ if (not content and not function_call) or not isinstance(content, str):+ format_errors["missing_content"] += 1++ if not any(message.get("role", None) == "assistant" for message in messages):+ format_errors["example_missing_assistant_message"] += 1++ # Raise an error if there are any format errors+ if format_errors:+ err_msg = "Found errors in the dataset format using the OpenAI API."+ err_msg += " Here are the number of datapoints for each error type:"+ for k, v in format_errors.items():+ err_msg += "\n {k}: {v}"+ raise ValueError(err_msg)++++++def check_message_lengths(dataset: List[dict[str, Any]]) -> list[int]:++ n_missing_system = 0++ n_missing_user = 0++ n_messages = []++ convo_lens = []++ assistant_message_lens = []++++ for ex in dataset:++ messages = ex["messages"]++ if not any(message["role"] == "system" for message in messages):++ n_missing_system += 1++ if not any(message["role"] == "user" for message in messages):++ n_missing_user += 1++ n_messages.append(len(messages))++ convo_lens.append(num_tokens_from_messages(messages))++ assistant_message_lens.append(num_assistant_tokens_from_messages(messages))++ n_too_long = sum([length > 16385 for length in convo_lens])++++ if n_too_long > 0:++ logger.info(f"There are {n_too_long} examples that may be over the 16,385 token limit, they will be truncated during fine-tuning.")++++ if n_missing_system > 0:++ logger.info(f"There are {n_missing_system} examples that are missing a system message.")++++ if n_missing_user > 0:++ logger.info(f"There are {n_missing_user} examples that are missing a user message.")++++ return convo_lens++++++def num_tokens_from_messages(messages, tokens_per_message=3, tokens_per_name=1):++ import tiktoken++ encoding = tiktoken.get_encoding("cl100k_base")++++ num_tokens = 0++ for message in messages:++ num_tokens += tokens_per_message++ for key, value in message.items():++ num_tokens += len(encoding.encode(value))++ if key == "name":++ num_tokens += tokens_per_name++ num_tokens += 3++ return num_tokens++++++def num_assistant_tokens_from_messages(messages):++ import tiktoken++ encoding = tiktoken.get_encoding("cl100k_base")++++ num_tokens = 0++ for message in messages:++ if message["role"] == "assistant":++ num_tokens += len(encoding.encode(message["content"]))++ return num_tokensdiff --cc dspy/teleprompt/finetune_teleprompter.pyindex 4fcdf3237,d5c5f563a..4bddd815c--- a/dspy/teleprompt/finetune_teleprompter.py+++ b/dspy/teleprompt/finetune_teleprompter.py@@@ -78,8 -78,102 +78,9 @@@ def prepare_teacherreturn teacher+-def build_prompt_completion_data_from_trace(- trace: List[Dict],- exclude_demos: bool=False,- try_to_record_lm_kwargs: bool = False,- program: Program = None,- ) -> Dict[str, List[Dict[str, Any]]]:- """Build prompt completion data from a given trace.-- Args:- trace: The trace from which the prompt-completion data will be built.- exclude_demos: Exclude the demos from the prompts even if they are- present in the trace. Defaults to `False`.- try_to_record_lm_kwargs: Whether to record the LM kwargs in the data.- Defaults to `False`. If set, the `lm_kwargs` field of the LM used to- generate the prompt-completion pair is included in the data. To- find the LM, we first check if the predictor that generated the- prompt-completion pair has an LM field set (`predictor.lm`). If it- does, we record it's kwargs. If it doesn't, we get the kwargs from- `dspy.settings.lm`. If `dspy.settings.lm` is not set either, this- function will not record the LM kwargs.- program: Optional argument used to infer the name of the predictor that- generated the prompt-completion pair. If provided, the returned data- will include the `predictor_name` field. If not provided, the- `predictor_name` field is not included in the data, but the caller- of this function can recover this information by using the- `predictor_ind` field that' included in the data by default, by- building the following dictionary:-- {ind: n for ind, (n, _) in enumerate(program.named_predictors())}-- where `ind` is the index of the predictor in the list returned by- the `named_predictors()` method of the program. Defaults to `None`.-- Returns:- Data as a list of dictionaries with the keys `prompt`, `completion` and- optionally with the keys `predictor_name` and `lm_kwargs`. For a given- prompt-completion pair:- - The `prompt` field corresponds to the prompt.- - The `completion` field corresponds to the completion.- - The `predictor_ind` field corresponds to the index of the predictor- in the predictor list- - The `predictor_name` field corresponds to the index of the predictor- in the list returned by the the named_predictor() method of the- program used to generate the trace. This field is included only if- the `pred_ind_to_name` argument is provided.- - The `lm_kwargs` field corresponds to the LM kwargs that generated the- prompt-completion pair. Included only if the `record_lm_kwargs` is- set and there is an active LM.- """- # If the program is provided, build the predictor index to name mapping- if program:- pred_ind_to_name = {- ind: name for ind, (name, _) in enumerate(program.named_predictors())- }-- # Build the prompt-completion data- data = []- for pred_ind, (pred, inputs, outputs) in enumerate(trace):- # Get the demos from the predictor if exclude_demos is False- demos = [] if exclude_demos else pred.demos-- # Build prompt and completion strings- template = signature_to_template(pred.signature)- prompt = template(Example(demos=demos, **inputs))- completion = template.query(Example(**outputs))-- # TODO: This part of the code could be improved.- # The method we use to build the completion (template.query) is meant to- # be used for creating, well, queries, and hence contains field prefixes- # (e.g. "Reasoning: Let's think step by step in order to"), which are- # also contained in the last piece of the prompt (separated with a new- # line) We remove this piece from the completion. This is a hacky- # solution since it assumes a particular template format.- prompt_last = prompt.split("\n")[-1]- completion = completion[len(prompt_last):]-- # Create prompt-completion dictionary and add it to the data; optionally- # add the predictor_name key as well as the lm_kwargs.- data_dict = dict(prompt=prompt, completion=completion)-- # Record the predictor index and optionally, name- data_dict['predictor_ind'] = pred_ind- if program:- data_dict['predictor_name'] = pred_ind_to_name[pred_ind]-- # Optionally, record the LM kwargs- lm = pred.lm or dspy.settings.lm- if try_to_record_lm_kwargs and lm:- data_dict['lm_kwargs'] = lm.kwargs- data.append(data_dict)-- return data---def convert_to_module_level_prompt_completion_data(+# TODO: fix docstring+def convert_to_module_level_message_data(data: List[Dict],keep_data_keys: bool = False,exclude_demos: bool = False,@@@ -130,43 -224,7 +131,44 @@@prompt_completion_data.append(prompt_completion_dict)return prompt_completion_data++# TODO: fix docstring+def build_messages_from_trace(+ trace: List[Dict],+ exclude_demos: bool=False,+ try_to_record_lm_kwargs: bool = False,+ program: Program = None,+ ) -> Dict[str, List[Dict[str, Any]]]:+ """Build messages from a given trace.+ """+ messages = []+ # If the program is provided, build the predictor index to name mapping+ if program:+ pred_ind_to_name = {+ ind: name for ind, (name, _) in enumerate(program.named_predictors())+ }++ # Build the prompt-completion data++ adapter = dspy.settings.adapter or dspy.ChatAdapter()+ data = []++ # TODO: Make sure that this works for multi-stage pipelines+ for pred_ind, (pred, inputs, outputs) in enumerate(trace):+ # Get the demos from the predictor if exclude_demos is False+ demos = [] if exclude_demos else pred.demos++ messages = adapter.format(pred.signature, demos, inputs)++ formatted_completion = adapter.format_completion(pred.signature, outputs)+ messages.append({"role": "assistant", "content": formatted_completion})+ data.append(messages)++ return data++def dummy_metric(example, pred, trace=None, frac=1.0):+ return 1+def bootstrap_data(program: Program,dataset: List[Example],@@@ -209,61 -266,29 +211,44 @@@info = _INFO_BOOTSTRAP_DATA.format(len(dataset), cname, num_threads)logger.info(info)evaluator = Evaluate(- devset=dataset, num_threads=num_threads, display_progress=True+ devset=dataset, num_threads=num_threads, display_progress=True, max_errors=max_errors, provide_traceback=True)- x = evaluator(program, metric=metric)- # print(x)- # data = process_dataset_threaded(dataset, program, metric, num_threads, max_errors)+ evaluator(program, metric=metric)+- # Re-iterate over the dataset to build the cached prompt-completion data- for example_ind, example in enumerate(dataset):-- # Run the program on the example- with dspy.context(trace=[]):- prediction = program(**example.inputs())- trace = dspy.settings.trace- score = metric(example, prediction, trace) if metric else None-- # Build the data dictionary and extend the data list- data_dict = dict(example=example, prediction=prediction, trace=trace)- data_dict['example_ind'] = example_ind- if metric:- data_dict['score'] = score- data.append(data_dict)+ data = []+ for example in dataset:+ data_dict = process_example(example, 0, program, metric)+ if data_dict is not None:+ data.append(data_dict)return data- def process_dataset_threaded(dataset: List[Any], program: Callable, metric: Optional[Callable] = None, max_workers: int = None, max_errors: int = 0) -> List[Dict[str, Any]]:- data = []- num_threads = max_workers if max_workers else 10- with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:- future_to_example = {executor.submit(process_example, example, i, program, metric): i- for i, example in enumerate(dataset)}-- for future in concurrent.futures.as_completed(future_to_example):- data_dict = future.result()- if data_dict is not None:- data.append(data_dict)-- # Sort the results based on example_ind to maintain original order- data.sort(key=lambda x: x['example_ind'])-- return data+def process_example(example: Any, example_ind: int, program: Callable, metric: Optional[Callable] = None) -> Dict[str, Any]:+ # print("Processing example:", example_ind)+ with dspy.context(trace=[]):+ # print("Running program...", example_ind)+ try:+ prediction = program(**example.inputs())+ except Exception as e:+ print(f"Error processing example {example_ind}: {e}")+ return None+ # print("Getting trace...", example_ind)+ trace = dspy.settings.trace+ # print("Getting score...", example_ind)+ score = metric(example, prediction, trace) if metric else None++ data_dict = {+ 'example': example,+ 'prediction': prediction,+ 'trace': trace,+ 'example_ind': example_ind+ }+ if metric:+ data_dict['score'] = score++ return data_dict+# TODO: If we can ensure to pass the "round" information every time a call is# issued to an LM, we can make repetitive un-cached calls to the same LM without# modifying it's temperature. This function can be removed then.