DSPy: The framework for programming—not prompting—language models
Python
Clean up ft_teleprompter
Isaac Miller2c1ee9f5a140
diff --git a/dspy/teleprompt/finetune_teleprompter.py b/dspy/teleprompt/finetune_teleprompter.pyindex 5bbe8ca5b..7a8c519ec 100644--- a/dspy/teleprompt/finetune_teleprompter.py+++ b/dspy/teleprompt/finetune_teleprompter.py@@ -28,19 +28,12 @@ _INFO_BOOTSTRAP_DATA = """Bootstrapping data on {} examples with the program \def prepare_teacher(student: Program,teacher: Program = None- ) -> Union[Program, AssertionError]:+ ) -> Program:"""Prepare the teacher program with respect to the student program.-Args:student: The student program.teacher: The teacher program. If `None`, a copy of the student programis used as the teacher. Defaults to `None`.-- Returns:- The copied teacher program.-- Raises:- AssertionError: If the teacher is not an instance of the Program class."""# If teacher is None, use a copy of the student program as the teacherif teacher is None:@@ -77,37 +70,11 @@ def convert_to_module_level_message_data(try_to_record_lm_kwargs: bool = False,program: Program = None) -> List[Dict]:- """Convert the data to prompt-completion data using the "trace" field.-- This function is a wrapper around the function- `build_prompt_completion_data_from_trace`, calling it on the "trace" field+ """Wrapper around the function+ `build_messages_from_trace`, calling it on the "trace" fieldof each dictionary in the input data list and combiningin the results into- a list of prompt-completion data dictionaries. If the `keep_data_keys`- is set, the original data keys are also copied over to in the- prompt-completion dictionaries.-- For example, if the input data includes 10 dictionaries, each containing a- "trace" field generated by a program with 3 predictors, the returned data- will have 30 prompt-completion data dictionaries.+ a list of prompt-completion data dictionaries."""- Args:- data: List of data dictionaries to be converted to prompt-completion- data. Each dictionary in the list should contain a "trace" field,- which is passed to the `build_prompt_completion_data_from_trace`- function to generate the prompt-completion data.- keep_data_keys: Whether to keep the original data keys in the- prompt-completion data. Note that if there are keys that are common- between the original data and the prompt-completion data returned by- `build_prompt_completion_data_from_trace`, the values from the- prompt-completion data will overwrite the values from the original- data. Defaults to `False`.- exclude_demos: Passed to `build_prompt_completion_data_from_trace`.- Defaults to `False`.- try_to_record_lm_kwargs: Passed to- `build_prompt_completion_data_from_trace`. Defaults to `False`.- program: Passed to `build_prompt_completion_data_from_trace`.- Defaults to `None`.- """prompt_completion_data = []for data_dict in data:trace = data_dict["trace"]@@ -121,16 +88,12 @@ def convert_to_module_level_message_data(prompt_completion_data.append(prompt_completion_dict)return prompt_completion_data--# TODO: fix docstringdef 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 mappingif program:@@ -165,32 +128,7 @@ def bootstrap_data(num_threads = 1,max_errors: int = 0) -> List[Dict[str, Any]]:- """Bootstrap prediction and trace data for the program using the dataset.-- Args:- program: The program that will be used to generate the traces for data- collection.- dataset: The dataset to be used for data collection.- metric: The optional metric to be used to get a score for the example,- recorded in a `score` field in the data. If the metric is not- provided, the `score` field is not included in the data. Defaults- to `None`.- num_threads: The number of threads to be used for data collection.- Defaults to `1`.-- Returns:- Data as a list of dictionaries with the keys `example`, `prediction`,- `trace`, and optionally, `score` fields. For a given example:- - The `example` field corresponds to the example itself.- - The `example_ind` field corresponds to the index of the example in the- `dataset`.- - The `prediction` field corresponds to the prediction made by the- program on the example.- - The `trace` field corresponds to the trace generated by the program- on the example.- - The `score` field corresponds to the metric score of the example, if- the metric is provided. Otherwise, it is not included in the data.- """+ """Bootstrap example, prediction, trace, example_ind, score data for the program using the dataset."""data = []# Use Evaluate to call the program have the responses cached@@ -250,79 +188,13 @@ def bootstrap_data_for_round(sampling_temperature: Optional[float] = 0.9,sampling_temperature_delta: float = 0.001,max_errors: int = 0- ) -> Union[List[Dict], AssertionError]:+ ) -> List[Dict]:""" Bootstrap data for the given sampling round.This is a wrapper function around the `bootstrap_data` function that allowsfor collecting data for the given `sampling_round`. Due to the way cachingworks, one cannot get different completions for the same prompt just by- querying an LM again, despite using a high sampling temperature. This- function is a workaround to get different completions for the same prompt- by modifying the sampling temperature of the LM for the specified- `sampling_round`. The temperature of an LM is set to the following value- for the given `sampling_round`:-- sampling_temperature + sampling_temperature_delta * sampling_round-- If a `sampling_temperature` of `None` is passed, the already set temperature- of the LM is used as the sampling temperature instead.-- To sample different completions for the same prompt, this sampling can be- called multiple times with different `sampling_round` values. For example:- ```- num_rounds = 5- data = []- for round in range(num_rounds):- data += bootstrap_data_for_round(- program, dataset, metric=metric, sampling_round=round- )- # Any dataset filtering for the next round can be done here, if needed- ```-- The dataset filtering can become a powerful tool. For example, it can be- used to filter out the examples that have already had enough high scoring- completions generated for them. Here is an illustration:- ```- num_correct_target = 3- correct_score = 1- num_rounds = 5- data = []- for round in range(num_rounds):- data += bootstrap_data_for_round(- program, dataset, metric=metric, sampling_round=round- )- correct_bootstraps = [d for d in data if d['score'] == correct_score]- correct_counts = Counter([d['example'] for d in correct_bootstraps])- dataset = [d for d in dataset if correct_counts[d] < num_correct_target]- ```-- Args:- program: The program that will be used to generate the traces for data- collection.- dataset: The dataset to be used for data collection.- metric: The optional metric to be used to get a score for the example,- recorded in a `score` field in the data. If the metric is not- provided, the `score` field is not included in the data. Defaults to- `None`.- num_threads: The number of threads to be used for data collection.- Defaults to `1`.- sampling_round: The round index for which the data is being collected.- Defaults to `0`.- sampling_temperature: The sampling temperature to be used for round- `0`. If a value of `None` is passed, the temperature of the LM is- used as the sampling temperature instead. Defaults to a high- temperature of `0.9`.- sampling_temperature_delta: The small temperature delta that's added to- the sampling temperature every increment of the round index to- generate different completions for the same prompt. Defaults to- `0.001`.-- Returns:- Data as a list of dictionaries with the keys returned by- the `bootstrap_data` function, descriptions for which are shared in the- function documentation. This function adds the following extra field- to the dictionaries:- - The `round` field corresponds to the `sampling_round` argument.+ querying an LM again."""# TODO: [DSPy 2.5] Migrate to using "seed" for sampling# Helper function to adjust the temperature of the LM. If a None temperature