Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

merging updates to signature_opt together

Krista Opsahl-Ong9b960f0ad0e6
diff --cc dspy/teleprompt/signature_opt.py
index 20aa1a1a9,f96e60fab..296df7be3
--- a/dspy/teleprompt/signature_opt.py
+++ b/dspy/teleprompt/signature_opt.py
@@@ -16,13 -17,18 +17,18 @@@ eval_score = evaluate(compiled_prompt_o
Note that this teleprompter takes in the following parameters:
++* prompt_model: The model used for prompt generation.
* metric: The task metric used for optimization.
* breadth: The number of new prompts to generate at each iteration. Default=10.
* depth: The number of times we should ask our prompt model to genereate new prompts, with the history of the past prompts as input. Default=3.
* init_temperature: The temperature used to generate new prompts. Higher roughly equals more creative. Default=1.4.
--* prompt_model: The model used for prompt generation.
* verbose: Tells the method whether or not to print intermediate steps.
-
+ * track_stats: Tells the method whether or not to track statistics about the optimization process.
+ If True, the method will track the following statistics:
+ * results_best: The min,max,avg,stddev of top 10 scores for each predictor at each depth.
+ * results_latest: The min,max,avg,stddev of newest prompt scores for each predictor at each depth.
+ * total_calls: The total number of calls to the task metric.
+ These statistics will be returned as attributes of the best program.
"""
class BasicGenerateInstruction(Signature):
"""You are an instruction optimizer for large language models. I will give you a ``signature`` of fields (inputs and outputs) in English. Your task is to propose an instruction that will lead a good language model to perform the task well. Don't be afraid to be creative."""
@@@ -39,7 -47,7 +47,7 @@@ Your task is to propose a new instructi
proposed_prefix_for_output_field = dspy.OutputField(desc="The string at the end of the prompt, which will help the model start solving the task")
class SignatureOptimizer(Teleprompter):
- def __init__(self, prompt_model, metric=None, breadth=10, depth=3, init_temperature=1.4, verbose=False):
- def __init__(self, metric=None, breadth=10, depth=3, init_temperature=1.4, prompt_model="gpt-3.5-turbo-1106", verbose=False, track_stats=False):
++ def __init__(self, prompt_model, metric=None, breadth=10, depth=3, init_temperature=1.4, verbose=False, track_stats=False):
self.metric = metric
self.breadth = breadth
self.depth = depth
@@@ -103,48 -125,77 +125,76 @@@
module_clone = module.deepcopy()
# For each iteration in depth...
- for d in range(self.depth):
- if (self.verbose):
- print(f"Starting iteration {d}/{self.depth}.")
+ for d in range(self.depth): # TODO: fix this so that we eval the new batch of predictors with the new best followoing predictors
+ if self.verbose: print(f"Starting iteration {d}/{self.depth}.")
+
+ latest_scores = []
# Go through our module's predictors
- for p_old, p_new in zip(module.predictors(), module_clone.predictors()):
-
+ for p_i, (p_old, p_new) in enumerate(zip(module.predictors(), module_clone.predictors())):
candidates_ = latest_candidates[id(p_old)] # Use the most recently generated candidates for evaluation
if len(module.predictors()) > 1:
candidates_ = all_candidates[id(p_old)] # Unless our program has multiple predictors, in which case we need to reevaluate all prompts with the new prompt(s) for the other predictor(s)
# For each candidate
- for c_i, c in enumerate(candidates_):
- for c_num, c in enumerate(candidates_):
--
++ for c_i, c in enumerate(candidates_):
# Get the candidate instruction and prefix
instruction, prefix = c.proposed_instruction.strip('"').strip(), c.proposed_prefix_for_output_field.strip('"').strip()
# Set this new module with our instruction / prefix
- p_new.extended_signature.instructions = instruction
- p_new.extended_signature.fields[-1] = p_new.extended_signature.fields[-1]._replace(name=prefix)
+ if (hasattr(p_new, 'extended_signature')):
+ p_new.extended_signature.instructions = instruction
+ p_new.extended_signature.fields[-1] = p_new.extended_signature.fields[-1]._replace(name=prefix)
+ else:
+ p_new.extended_signature1.instructions = instruction
+ p_new.extended_signature1.fields[-1] = p_new.extended_signature1.fields[-1]._replace(name=prefix)
+ p_new.extended_signature2.instructions = instruction
+ p_new.extended_signature2.fields[-1] = p_new.extended_signature2.fields[-1]._replace(name=prefix)
# Score the instruction / prefix
- if (self.verbose):
- print(f"----------------")
- for i,predictor in enumerate(module_clone.predictors()):
- print(f"Predictor {i}")
- print(f"i: {predictor.extended_signature.instructions}")
- print(f"p: {predictor.extended_signature.fields[-1].name}")
- print()
- print(f"At Depth {d}/{self.depth}, Evaluating Prompt Candidate #{c_i}/{len(candidates_)} for Predictor {p_i} of {len(module.predictors())}.")
+ if self.verbose: print(f"----------------")
+ for i,predictor in enumerate(module_clone.predictors()):
+ if self.verbose: print(f"Predictor {i}")
+ if (hasattr(predictor, 'extended_signature')):
+ if self.verbose: print(f"i: {predictor.extended_signature.instructions}")
+ if self.verbose: print(f"p: {predictor.extended_signature.fields[-1].name}")
+ else:
+ if self.verbose: print(f"i: {predictor.extended_signature1.instructions}")
+ if self.verbose: print(f"p: {predictor.extended_signature1.fields[-1].name}")
+ if self.verbose: print()
++ if self.verbose: print(f"At Depth {d}/{self.depth}, Evaluating Prompt Candidate #{c_i}/{len(candidates_)} for Predictor {p_i} of {len(module.predictors())}.")
score = evaluate(module_clone, devset=devset, **eval_kwargs)
+ print(f"prompt_model.inspect_history(n=1) {self.prompt_model.inspect_history(n=1)}")
total_calls += 1
- if (self.verbose):
- print(f"----------------")
-
- # Add it to our evaluated candidates list
- evaluated_candidates[id(p_old)].append({
- "score": score,
- "program": module_clone.deepcopy(),
- "instruction": instruction,
- "prefix": prefix,
- "depth": d
- })
+ if self.verbose: print(f"----------------")
+
+ replace_entry = True
+ if self.verbose: print(f"(instruction, prefix) {(instruction, prefix)}")
+ # if verbose: print(f"evaluated_candidates[id(p_old)] {evaluated_candidates[id(p_old)]}")
+ if ((instruction, prefix) in evaluated_candidates[id(p_old)]):
+ # if verbose: print(f"if evaluated_candidates[id(p_old)][(instruction, prefix)] {evaluated_candidates[id(p_old)][(instruction, prefix)]}")
+ if evaluated_candidates[id(p_old)][(instruction, prefix)]["score"] >= score:
+ replace_entry = False
+
+ if replace_entry:
+ # Add it to our evaluated candidates list
+ evaluated_candidates[id(p_old)][(instruction, prefix)] = {
+ "score": score,
+ "program": module_clone.deepcopy(),
+ "instruction": instruction,
+ "prefix": prefix,
+ "depth": d
+ }
+
- if (len(candidates_)-self.breadth <= c_num):
++ if (len(candidates_)-self.breadth <= c_i):
+ latest_scores.append(score)
+
+ if self.track_stats:
+ results_latest[id(p_old)]["depth"].append(d)
+ results_latest[id(p_old)]["max"].append(max(latest_scores))
+ results_latest[id(p_old)]["average"].append(sum(latest_scores)/len(latest_scores))
+ results_latest[id(p_old)]["min"].append(min(latest_scores))
+ results_latest[id(p_old)]["std"].append(np.std(latest_scores))
# Now that we've evaluated the candidates, set this predictor to the best performing version
# to ensure the next round of scores reflect the best possible version