DSPy: The framework for programming—not prompting—language models
Python
Update data functions
dilara6275c54ac45a
diff --git a/dspy/teleprompt/finetune_teleprompter.py b/dspy/teleprompt/finetune_teleprompter.pyindex f2553b60e..9d9fbb48a 100644--- a/dspy/teleprompt/finetune_teleprompter.py+++ b/dspy/teleprompt/finetune_teleprompter.py@@ -1,8 +1,7 @@-from collections import Counter, OrderedDictfrom typing import Any, Callable, Dict, List, Optional, Unionimport dspy-from dspy.utils.logging import logger+from dspy import loggerfrom dspy.evaluate.evaluate import Evaluatefrom dspy.primitives.example import Examplefrom dspy.primitives.program import Program@@ -62,11 +61,11 @@ def prepare_teacher(# Ensure that the student and teacher programs have the same structurelogger.info(_INFO_STRUCTURAL_EQUIVALENCY)- assert student._assert_structural_equivalency(teacher)+ student._assert_structural_equivalency(teacher)# Ensure that the predictors of the programs point to different objectslogger.info(_INFO_SHARED_PREDICTOR)- assert not student._assert_no_shared_predictor(teacher)+ student._assert_no_shared_predictor(teacher)# Ensure that the LM consistency property is satisfiedlogger.info(_INFO_LM_CONSISTENCY)@@ -82,21 +81,36 @@ def prepare_teacher(def build_prompt_completion_data_from_trace(trace: List[Dict],- program: Optional[Program] = None,exclude_demos: bool=False,- record_lm_kwargs: 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.- program: Optional argument corresponding to the program that generated- the trace, used to augment the prompt-completion pairs with the- names of the predictors that generated them. Defaults to `None`.exclude_demos: Exclude the demos from the prompts even if they arepresent in the trace. Defaults to `False`.- record_lm_kwargs: Whether to record the LM kwargs in the data. 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@@ -104,21 +118,25 @@ def build_prompt_completion_data_from_trace(prompt-completion pair:- The `prompt` field corresponds to the prompt.- The `completion` field corresponds to the completion.- - The `predictor_name` field corresponds to the name of the predictor- that generated the prompt-completion pair.+ - 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.+ prompt-completion pair. Included only if the `record_lm_kwargs` is+ set and there is an active LM."""- # If program is provided, build a mapping from predictor ids to names- pred_id_to_name = None+ # If the program is provided, build the predictor index to name mappingif program:- pred_id_to_name = OrderedDict(- (id(pred), name) for name, pred in program.named_predictors()- )+ pred_ind_to_name = {+ ind: name for ind, (name, _) in enumerate(program.named_predictors())+ }# Build the prompt-completion datadata = []- for pred, inputs, outputs in trace:+ for pred_ind, (pred, inputs, outputs) in enumerate(trace):# Get the demos from the predictor if exclude_demos is Falsedemos = [] if exclude_demos else pred.demos@@ -141,16 +159,72 @@ def build_prompt_completion_data_from_trace(# add the predictor_name key as well as the lm_kwargs.data_dict = dict(prompt=prompt, completion=completion)- if program and id(pred) in pred_id_to_name:- pred_name = pred_id_to_name[id(pred)]- data_dict['predictor_name'] = pred_name- if record_lm_kwargs:- data_dict['lm_kwargs'] = pred.lm.kwargs+ # 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.kwargsdata.append(data_dict)return data+def convert_to_prompt_completion_data(+ data: List[Dict],+ keep_data_keys: bool = False,+ exclude_demos: bool = False,+ 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+ of 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.++ 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"]+ trace_prompt_comletion_data = build_prompt_completion_data_from_trace(+ trace=trace, exclude_demos=exclude_demos,+ try_to_record_lm_kwargs=try_to_record_lm_kwargs, program=program+ )+ for prompt_completion_dict in trace_prompt_comletion_data:+ if keep_data_keys:+ prompt_completion_dict = {**data_dict, **prompt_completion_dict}+ prompt_completion_data.append(prompt_completion_dict)+ return prompt_completion_data++def bootstrap_data(program: Program,dataset: List[Example],@@ -214,24 +288,63 @@ def bootstrap_data(# 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. The `temperature_delta` argument can be removed-# then.-def bootstrap_data_multiple_rounds(+# modifying it's temperature. This function can be removed then.+def bootstrap_data_for_round(program: Program,dataset: List[Example],metric: Optional[Callable[[Example, Prediction, Optional[List]], Union[bool, int, float]]] = None,num_threads = 1,- num_rounds: int = 1,- sampling_temperature_base: Optional[float] = 0.9,+ sampling_round: int = 0,+ sampling_temperature: Optional[float] = 0.9,sampling_temperature_delta: float = 0.001,- next_round_dataset_callback: Optional[Callable[- [List[Example], List[Dict[str, Any]]], List[Example]- ]] = lambda x, y: x,- ) -> List[Dict]:- """ Bootstrap multiple rounds of data using the dataset and program.+ ) -> Union[List[Dict], AssertionError]:+ """ Bootstrap data for the given sampling round.++ This is a wrapper function around the `bootstrap_data` function that allows+ for collecting data for the given `sampling_round`. Due to the way caching+ works, 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 datacollection.@@ -242,32 +355,16 @@ def bootstrap_data_multiple_rounds(`None`.num_threads: The number of threads to be used for data collection.Defaults to `1`.- num_rounds: The number of rounds of data collection to be performed.- Defaults to `1`.- sampling_temperature_base: The sampling temperature to be used in the- first round. If a value of `None` is passed, the already set- temperature of the LM is used as the base sampling temperature- instead. Defaults to a high temperature of `0.9`.- sampling_temperature_delta: The small temperature difference utilized to- generate different bootstrapped traces for the different rounds to- circummvent caching. Defaults to `0.001`.- next_round_dataset_callback: The callback function to be used to- generate the dataset for the next round of data collection. The- function should take the current dataset and the data from the- current round as arguments and return the dataset for the next- round, an example signature for which provided below. Defaults to a- function that returns the current dataset, meaning that the default- behavior of this function is to sample `num_rounds` bootstrapped- examples for each example in the original dataset.-- ```- def next_round_dataset_callback(- dataset: List[Example],- data: List[Dict[str, Any]]- ) -> List[Example]:- # Your code modifying the dataset here- return dataset- ```+ 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 `example`, `prediction`,@@ -280,60 +377,41 @@ def bootstrap_data_multiple_rounds(the example.- The `score` field corresponds to the metric score of the example, ifthe metric is provided. Otherwise, it is not included in the data.- - The `round` field corresponds to the index of the round the particular- data dictionary is collected in.- """- # Create a copy of the program and dataset so that they are not modified+ - The `round` field corresponds to the `sampling_round` argument.+ """+ # Helper function to adjust the temperature of the LM. If a None temperature+ # is passed, keep the LM's temperature as is as the base temperature, then+ # adjust the temperature for the given round.+ def copy_model_with_updated_temp(lm):+ temp = sampling_temperature+ temp = lm.kwargs["temperature"] if temp is None else temp+ temp = temp + sampling_temperature_delta * sampling_round+ return lm.copy(temperature=temp)++ # Ensure that the LM consistency is satisfied, which ensures that either (1)+ # the global LM is set or (2) all the predictors have an LM set.+ program._assert_lm_consistency()++ # Deepcopy the program and copy the dataset to avoid modifying the originalprogram = program.deepcopy()dataset = dataset.copy()- # Ensure that the LM consistency is satisfied, push the global LM to the- # predictors if dspy.settings.lm is set- # print(program(**dataset[0].inputs()))- program._assert_lm_consistency()+ # Update the temperature of the LM for the given round+ context_lm = Noneif dspy.settings.lm:- # This line is breaking everything- program._set_all_predictor_lms(dspy.settings.lm)-- # Collect rounds of data collection with different sampling temperatures- data = []- for round_ind in range(num_rounds):- # Adjust the LM temperatures of the program predictors+ context_lm = copy_model_with_updated_temp(dspy.settings.lm)+ else:for pred in program.predictors():- # If a None temperature is passed, keep the predictor's temperature- # as is for the first round- temp = sampling_temperature_base- temp = pred.lm.kwargs["temperature"] if temp is None else temp- temp += sampling_temperature_delta * round_ind- pred.lm = pred.lm.copy(temperature=temp)-- # Collect the data for the round, add the round index to the data- # dictionaries, and extend the data list- info = f"Round {round_ind + 1}/{num_rounds}"- logger.info(info)- round_data = bootstrap_data(+ pred.lm = copy_model_with_updated_temp(pred.lm)++ # Collect the data for the given round+ with dspy.context(lm=context_lm):+ data = bootstrap_data(program, dataset, metric=metric, num_threads=num_threads)- for data_dict in round_data:- data_dict["round"] = round_ind- data += round_data-- # Update the dataset for the next round- dataset = next_round_dataset_callback(dataset, round_data)++ # Add the round information to the data+ for data_dict in data:+ data_dict["round"] = sampling_roundreturn data--class DataCollectionCallback:- def __init__(self, num_attempts=0, num_correct=1, max_attempts=1):- self.num_attempts = num_attempts- self.num_correct = num_correct- self.max_attempts = max_attempts-- def move_on_callback_correct_with_max(self, dataset_copy, data):- correct_counts = Counter(list(map(lambda x: x["example"], data)))- # examples_from_data = map(lambda x: x["example"], data)- examples_still_incorrect = [x for x in dataset_copy if correct_counts.get(x, 0) < self.num_correct]- self.num_attempts += 1- if self.num_attempts >= self.max_attempts:- return []- return examples_still_incorrect