DSPy: The framework for programming—not prompting—language models
Python
updating LangProbe benchmark + small change to hackercup utils
klopsahlongb090ed094c80
diff --git a/examples/coding/hackercup_utils.py b/examples/coding/hackercup_utils.pyindex ec443dfd7..881c7e911 100644--- a/examples/coding/hackercup_utils.py+++ b/examples/coding/hackercup_utils.py@@ -2,7 +2,11 @@ import reimport asyncioimport multiprocessingimport concurrent.futures-from typing import Optional+from typing import List, Optional+import os+import sys+import traceback+import multiprocessing"""Note that this code is largely based off of the code here:@@ -40,14 +44,18 @@ def run_with_timeout(code: str, input: Optional[str], timeout: int):def target_fn(input, return_dict):vars = {}try:+ # Redirect stdout to silence print statements+ sys.stdout = open(os.devnull, 'w')exec(code, vars)fn = vars.get("solve", lambda x: x)return_dict["result"] = fn(input)except Exception as e:return_dict["error"] = str(e)- return_dict["stack_trace"] = (- traceback.format_exc()- ) # Capture the stack trace+ return_dict["stack_trace"] = traceback.format_exc()+ finally:+ # Restore stdout to its original setting+ sys.stdout.close()+ sys.stdout = sys.__stdout__manager = multiprocessing.Manager()return_dict = manager.dict()@@ -75,7 +83,6 @@ def run_with_timeout(code: str, input: Optional[str], timeout: int):return {"result": return_dict.get("result"), "error": None, "stack_trace": None}-async def arun(code: Optional[str] = None, input: Optional[str] = None, timeout: int = 60):diff --git a/testing/README.md b/testing/README.mdindex 95505dfeb..6fc730072 100644--- a/testing/README.md+++ b/testing/README.md@@ -7,7 +7,7 @@ Optimizer Tester is intended to allow simple and repeatable testing of DSPy OptiTo use the Optimizer Tester in code instantiate an OptimizerTester object:```python-from testing.optimizer_tester import OptimizerTester+from optimizer_tester import OptimizerTestertester = OptimizerTester()```@@ -17,8 +17,8 @@ The default verison (no parameters) expects a llama model hosted on ports [7140,If you prefer to specify your own model parameters then you can pass models into the OptimizerTester```python-task_model = dspy.HFClientTGI(...)-prompt_model = dspy.OpenAI(...)+task_model = dspy.LM(...)+prompt_model = dspy.LM(...)tester = OptimizerTester(task_model=task_model, prompt_model=prompt_model)```@@ -26,7 +26,7 @@ tester = OptimizerTester(task_model=task_model, prompt_model=prompt_model)If you just want to get baseline results for a particular task you're ready to go!```python-tester.test_baseline(datasets=["HotPotQA", "GSM8K", "Scone"])+tester.test_baseline(datasets=["hotpotqa", "gsm8k", "scone"])```If you want to test out a custom optimizer you'll have to write a quick function to call it properly:diff --git a/testing/optimizer_tester.py b/testing/optimizer_tester.pyindex 68d394601..47bcc80ae 100644--- a/testing/optimizer_tester.py+++ b/testing/optimizer_tester.py@@ -9,25 +9,37 @@ from dotenv import load_dotenvimport dspyfrom dspy.evaluate import Evaluate-from .tasks.biodex import BioDexTask-from .tasks.gsm8k import GSM8KTask-from .tasks.hotpotqa import HotPotQATask-from .tasks.scone import ScoNeTask-from .tasks.tweet import TweetTask-from .tasks.tweet_metric import TweetMetricTask--datasets = ["ScoNe", "HotPotQA", "GSM8K", "BioDex", "Tweet"]+from tasks.gsm8k import GSM8KTask+from tasks.hotpotqa import HotPotQATask+from tasks.scone import ScoNeTask+from tasks.tweet import TweetTask+from tasks.tweet_metric import TweetMetricTask+from tasks.heart_disease import HeartDiseaseTask+from tasks.hotpotqa_conditional import HotPotQAConditionalTask+from tasks.hover import HoverRetrieveDiscrete+from tasks.iris_typo import IrisTypoClassifierTask+from tasks.iris import IrisClassifierTask++# datasets = ["scone", "hotpotqa", "hotpotqa_conditional", "gsm8k", "biodex", "tweet", "heart_disease", "iris", "iris_typo", "hover_retrieve_discrete", "tweet_metric"]+# datasets = ["iris"] # working+# datasets = ["hotpotqa_conditional"] # working+# datasets = ["iris_typo"] # working+datasets = ["hotpotqa"] # <- not working+# datasets = ["gsm8k"] # working+# datasets = ["biodex"] # not working+# datasets = ["heart_disease"] # working+# datasets = ["hover_retrieve_discrete"] # not working, need to debugclass OptimizerTester:def __init__(self, datasets=datasets, default_train_num = 200, default_dev_num = 100, default_test_num = 200,- num_threads = 10, default_breadth = 10, default_depth = 3, default_temperature = 1.4,+ num_threads = 10, default_breadth = 10, default_depth = 3, default_temperature = 1.1,prompt_model_name = "gpt-3.5-turbo-1106", task_model_name = "meta-llama/Llama-2-13b-chat-hf",- prompt_model = None, task_model = None,+ prompt_model = None, task_model = None, max_errors=100,colbert_v2_endpoint = "http://20.102.90.50:2017/wiki17_abstracts"):self.datasets = datasetsself.TRAIN_NUM = default_train_numself.DEV_NUM = default_dev_num- self.EVAL_NUM = default_test_num+ self.TEST_NUM = default_test_numself.NUM_THREADS = num_threadsself.BREADTH = default_breadthself.DEPTH = default_depth@@ -35,6 +47,7 @@ class OptimizerTester:self.PROMPT_MODEL_NAME = prompt_model_nameself.TASK_MODEL_NAME = task_model_nameself.COLBERT_V2_ENDPOINT = colbert_v2_endpoint+ self.MAX_ERRORS = max_errorsload_dotenv() # This will load the .env file's variables@@ -43,7 +56,7 @@ class OptimizerTester:# Prompt gen modelif not prompt_model:- self.prompt_model = dspy.OpenAI(model=self.PROMPT_MODEL_NAME, max_tokens=150)+ self.prompt_model = dspy.OpenAI(model=self.PROMPT_MODEL_NAME, max_tokens=700)else:self.prompt_model = prompt_model@@ -67,7 +80,7 @@ class OptimizerTester:with open(file_path, mode='a', newline='', encoding='utf-8') as file:writer = csv.writer(file)- headers = ['test_name', 'train_score', 'dev_score', 'eval_score', 'run_time (sec)', 'train_size', 'dev_size', 'eval_size', 'task_name', 'signature_optimized', 'prompt_model_name', 'task_model_name', 'breadth', 'depth', 'meta_prompt_style', 'fewshot_before', 'fewshot_after', 'temperature', 'fewshot_candidates_num', 'max_bootstrapped_demos', 'bootstrapping', 'view_data', 'optimizer_log_dir', 'additional_notes', 'misc']+ headers = ['test_name', 'train_score', 'dev_score', 'test_score', 'run_time (sec)', 'train_size', 'dev_size', 'test_size', 'task_name', 'signature_optimized', 'prompt_model_name', 'task_model_name', 'breadth', 'depth', 'meta_prompt_style', 'fewshot_before', 'fewshot_after', 'temperature', 'fewshot_candidates_num', 'max_bootstrapped_demos', 'bootstrapping', 'view_data', 'optimizer_log_dir', 'additional_notes', 'misc']# Write headers if the file is being createdif not file_exists:@@ -84,7 +97,6 @@ class OptimizerTester:# Write the datawriter.writerow(formatted_data)-def load_dataset(self,dataset):ds = Nonedataset = dataset.lower()@@ -92,43 +104,59 @@ class OptimizerTester:ds = ScoNeTask()elif dataset == "hotpotqa":ds = HotPotQATask()+ elif dataset == "hotpotqa_conditional":+ ds = HotPotQAConditionalTask()elif dataset == "gsm8k":ds = GSM8KTask()elif dataset == "biodex":ds = BioDexTask()elif dataset == "tweet":ds = TweetTask()+ elif dataset == "heart_disease":+ ds = HeartDiseaseTask()+ elif dataset == "iris":+ ds = IrisClassifierTask()+ elif dataset == "iris_typo":+ ds = IrisTypoClassifierTask()+ elif dataset == "hover_retrieve_discrete":+ ds = HoverRetrieveDiscrete()elif dataset == "tweet_metric":ds = TweetMetricTask()else:raise ValueError("Invalid dataset name.")- ds.set_splits(TRAIN_NUM=self.TRAIN_NUM, DEV_NUM=self.DEV_NUM, EVAL_NUM=self.EVAL_NUM)+ ds.set_splits(TRAIN_NUM=self.TRAIN_NUM, DEV_NUM=self.DEV_NUM, TEST_NUM=self.TEST_NUM)return ds# Computes baseline results for a given datasetdef test_baseline(self, datasets=datasets, test_name="baseline"):for dataset in datasets:+ print(f"Testing {dataset} Baseline LM Program...")task = self.load_dataset(dataset)- evaluate_train = Evaluate(devset=task.get_trainset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True)- evaluate_dev = Evaluate(devset=task.get_devset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True)- evaluate_eval = Evaluate(devset=task.get_evalset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True)+ dspy.settings.lm.max_tokens = task.get_max_tokens()++ evaluate_train = Evaluate(devset=task.get_trainset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True, max_errors=self.MAX_ERRORS)+ evaluate_dev = Evaluate(devset=task.get_devset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True, max_errors=self.MAX_ERRORS)+ evaluate_test = Evaluate(devset=task.get_testset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True, max_errors=self.MAX_ERRORS)default_program = task.get_program()# Evaluate the default program+ print(f"Train...")default_results_train = evaluate_train(default_program)+ print(f"Dev...")default_results_dev = evaluate_dev(default_program)- default_results_eval = evaluate_eval(default_program)+ print(f"Test...")+ default_results_test = evaluate_test(default_program)# Write the results to a csvself.write_to_csv('outputs', 'results.csv', {'test_name': dataset + "_" + test_name,'train_score': default_results_train,'dev_score': default_results_dev,- 'eval_score': default_results_eval,+ 'test_score': default_results_test,'run_time (sec)': 0,'train_size': len(task.get_trainset()),'dev_size': len(task.get_devset()),- 'eval_size': len(task.get_evalset()),+ 'test_size': len(task.get_testset()),'task_name': dataset,'signature_optimized': False,'prompt_model_name': self.PROMPT_MODEL_NAME,@@ -152,9 +180,12 @@ class OptimizerTester:for dataset in datasets:task = self.load_dataset(dataset)- evaluate_train = Evaluate(devset=task.get_trainset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True)- evaluate_dev = Evaluate(devset=task.get_devset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True)- evaluate_eval = Evaluate(devset=task.get_evalset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True)+ print(f"Testing Optimizers on {dataset} ...")+ dspy.settings.lm.max_tokens = task.get_max_tokens()++ evaluate_train = Evaluate(devset=task.get_trainset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True, max_errors = self.MAX_ERRORS)+ evaluate_dev = Evaluate(devset=task.get_devset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True, max_errors = self.MAX_ERRORS)+ evaluate_test = Evaluate(devset=task.get_testset(), metric=task.get_metric(), num_threads=self.NUM_THREADS, display_progress=True, max_errors = self.MAX_ERRORS)default_program = task.get_program()# Set up the optimizer kwargs@@ -169,19 +200,22 @@ class OptimizerTester:end = timer()# Evaluate the optimized program+ print(f"Optimized train score...")optimized_results_train = evaluate_train(optimized_program)+ print(f"Optimized dev score...")optimized_results_dev = evaluate_dev(optimized_program)- optimized_results_eval = evaluate_eval(optimized_program)+ print(f"Optimized test score...")+ optimized_results_test= evaluate_test(optimized_program)output = {'test_name': dataset + "_" + test_name,'train_score': optimized_results_train,'dev_score': optimized_results_dev,- 'eval_score': optimized_results_eval,+ 'test_score': optimized_results_test,'run_time (sec)': end - start,'train_size': len(task.get_trainset()),'dev_size': len(task.get_devset()),- 'eval_size': len(task.get_evalset()),+ 'test_size': len(task.get_testset()),'task_name': dataset,'signature_optimized': True,'prompt_model_name': self.PROMPT_MODEL_NAME,diff --git a/testing/tasks/__init__.py b/testing/tasks/__init__.pyindex 0b1ee32ec..835a30e2d 100644--- a/testing/tasks/__init__.py+++ b/testing/tasks/__init__.py@@ -1,7 +1,10 @@-from .base_task import BaseTask-from .biodex import BioDexTaskfrom .gsm8k import GSM8KTaskfrom .hotpotqa import HotPotQATaskfrom .scone import ScoNeTaskfrom .tweet import TweetTaskfrom .tweet_metric import TweetMetricTask+from .heart_disease import HeartDiseaseTask+from .hotpotqa_conditional import HotPotQAConditionalTask+from .hover import HoverRetrieveDiscrete+from .iris_typo import IrisTypoClassifierTask+from .iris import IrisClassifierTask\ No newline at end of filediff --git a/testing/tasks/base_task.py b/testing/tasks/base_task.pyindex 089e6d7be..2ff5c0136 100644--- a/testing/tasks/base_task.py+++ b/testing/tasks/base_task.py@@ -33,17 +33,20 @@ class BaseTask(ABC):index = max(len(self.trainset) - self.DEV_NUM, self.TRAIN_NUM)return self.trainset[index:]- def get_evalset(self, EVAL_NUM=None):- if EVAL_NUM:- self.EVAL_NUM = EVAL_NUM- return self.devset[:EVAL_NUM]+ def get_testset(self, TEST_NUM=None):+ if TEST_NUM:+ self.TEST_NUM = TEST_NUM+ return self.testset[:TEST_NUM]else:- return self.devset[:self.EVAL_NUM]+ return self.testset[:self.TEST_NUM]- def set_splits(self, TRAIN_NUM=None, DEV_NUM=None, EVAL_NUM=None):+ def set_splits(self, TRAIN_NUM=None, DEV_NUM=None, TEST_NUM=None):if TRAIN_NUM:self.TRAIN_NUM = TRAIN_NUMif DEV_NUM:self.DEV_NUM = DEV_NUM- if EVAL_NUM:- self.EVAL_NUM = EVAL_NUM\ No newline at end of file+ if TEST_NUM:+ self.TEST_NUM = TEST_NUM++ def get_max_tokens(self):+ return 150\ No newline at end of filediff --git a/testing/tasks/biodex.py b/testing/tasks/biodex.pydeleted file mode 100644index 6e51745b3..000000000--- a/testing/tasks/biodex.py+++ /dev/null@@ -1,636 +0,0 @@-from __future__ import annotations--import math-import os-import pickle-import re-from collections import defaultdict-from enum import Enum-from functools import lru_cache-from typing import DefaultDict, Dict, List, Optional, Union--import datasets-import tqdm-from pydantic import BaseModel-from rapidfuzz import process--import dspy-from dsp.utils import deduplicate-from dspy.evaluate import Evaluate--from .base_task import BaseTask--# Must point to a MedDra download with mdhier.asc-data_dir = '/future/u/okhattab/data/2023/MedDraV2/meddra_23_0_english/MedAscii' # NOTE: EDIT THIS LINE--global meddra_root-meddra_root = None--def _remove_non_llt(candidates):- return [c for c in candidates if c.level == Level.LLT]---def get_path(node):- path = f"under {node.parent.term} < {node.parent.parent.term} < {node.parent.parent.parent.term}"- return path---def flatten(ll):- return [x for l in ll for x in l]---def _matches_to_terms_and_paths(matches):- s = []- for n in matches:- new_s = f"{n.node.term} ({n.score} score for query '{n.query}'; {n.node.count} counts; {get_path(n.node)})"- s.append(new_s)- return s---class Level(Enum):- ROOT = 0- SOC = 1- HLTG = 2- HLT = 3- LLT = 4-- def __add__(self, other: int):- if self.ROOT.value <= self.value + other <= self.LLT.value:- return Level(self.value + other)- else:- return None-- def __lt__(self, other) -> bool:- return self.value < other.value-- def __le__(self, other) -> bool:- return self.value <= other.value-- def __gt__(self, other) -> bool:- return self.value > other.value-- def __ge__(self, other) -> bool:- return self.value >= other.value-- def __sub__(self, other) -> int:- return self.value - other.value---class Node(BaseModel):- id: str- term: str- level: Level- count: int = 0-- parent: Node = None- children: Dict[str, Node] = {}-- # maps for efficient nested children lookups- # typically only used for the root node- id_to_nodes: Optional[DefaultDict[str, List[Node]]] = None- term_to_nodes: Optional[DefaultDict[str, List[Node]]] = None-- # text normalizer to build lookup tables- # typically only used for the root node- normalizer: function = lambda x: x-- def get_parent_at_level(self, target_level: Level) -> Union[Node, None]:- # check if current node is deeper than target_level- level_diff = target_level - self.level- if level_diff > 0:- return None- else:- node = self- for _ in range(-level_diff):- node = node.parent- return node-- def get_children_at_level(self, target_level: Level) -> List[Node]:- raise NotImplementedError-- def lookup_id(self, id: str) -> Union[List[Node], None]:- # create lookup tables if they do not exists- if self.id_to_nodes == None:- self.set_lookup_tables()- # lookup-- if id in self.id_to_nodes:- return self.id_to_nodes[id]- else:- return None-- def lookup_term(self, term: str) -> Union[List[Node], None]:- # create lookup tables if they do not exists- if self.term_to_nodes == None:- raise RuntimeError("First set the lookup tables using 'set_lookup_tables'.")- # lookup- term = self.normalizer(term)- if term in self.term_to_nodes:- return self.term_to_nodes[term]- else:- return None-- def match(- self,- query: str,- fuzzy_limit: int = 20,- fuzzy_score_cutoff: int = 80,- return_nodes: bool = False,- ):- """Return a tuple containing exact match and best fuzzy matches of LLT terms in ontology.-- Args:- query (str): String being matched into ontology- fuzzy_limit (int, optional): Maximal limit of fuzzy matches to return. Defaults to 20.- fuzzy_score_cutoff (int, optional): Minimal fuzzy matching score, between 0 and 100. Defaults to 80.- return_nodes (bool, optional): If true, return Node objects instead of paths-- Returns:- tuple: Tuple(exact match or None, list of fuzzy matches)- """- exact_candidate = []- fuzzy_candidates = []-- # exact match- exact_matches = self.lookup_term(query)- if exact_matches is not None:- exact_candidate = _remove_non_llt(exact_matches)- exact_candidate = [- Match(query=query, score=100, node=node) for node in exact_candidate- ]-- # fuzzy match- fuzzy_terms = process.extract(- query,- self.term_to_nodes.keys(),- limit=fuzzy_limit,- score_cutoff=fuzzy_score_cutoff,- )-- fuzzy_matches = []- for term, sim, _ in fuzzy_terms:- applicable_nodes = _remove_non_llt(self.term_to_nodes[term])- for n in applicable_nodes:- fuzzy_matches.append(Match(node=n, score=sim, query=query))-- if return_nodes:- return exact_candidate, fuzzy_matches- else:- exact_term = (- _matches_to_terms_and_paths(exact_candidate) if exact_candidate else []- )- fuzzy_terms = _matches_to_terms_and_paths(fuzzy_matches)- return exact_term, fuzzy_terms-- def set_lookup_tables(self, normalizer: function = lambda x: x) -> None:- # set normalizer- self.normalizer = normalizer-- # get a flat list of all nodes- self.term_to_nodes = defaultdict(list)- self.id_to_nodes = defaultdict(list)-- # breadth-first traversal- candidates = [self]- while len(candidates):- candidate = candidates.pop(0)- # track nodes- self.term_to_nodes[self.normalizer(candidate.term)].append(candidate)- self.id_to_nodes[candidate.id].append(candidate)- # add candidate's children to candidate list- if candidate.children:- candidates.extend(candidate.children.values())- return-- def is_equivalent_node(self, other: Node) -> bool:- # return true if two nodes are the same, siblings or in a parent-child relation- return (- (self == other)- or (self.parent == other)- or (self == other.parent)- or (self.parent == other.parent)- )-- def terms_equivalent(self, term1: str, term2: str) -> Union[bool, None]:- # lookup both terms- term1_nodes = self.lookup_term(term1)- term2_nodes = self.lookup_term(term2)- # if at least one term not found- if not term1_nodes or not term2_nodes:- return None- # compare all nodes- for node1 in term1_nodes:- for node2 in term2_nodes:- if node1.is_equivalent_node(node2):- return True- return False-- def __key(self):- return (self.id, self.term, self.parent, len(self.children))-- def __hash__(self):- return hash(self.__key())-- def __eq__(self, other: Node) -> bool:- # undeep equals operator, does not check children- return self.__key() == other.__key()-- def __str__(self) -> str:- return f"Node(id={self.id}, term={self.term}, level={self.level}, parent={self.parent.term if self.parent else None}, #children={len(self.children)}, count={self.count})"-- def __repr__(self) -> str:- return self.__str__()-- def get_path(self):- path = f"under {self.parent.term} < {self.parent.parent.term} < {self.parent.parent.parent.term}"- return path-- @property- def all_nodes(self):- return flatten(list(self.id_to_nodes.values()))-- @property- def all_llt_nodes(self):- return _remove_non_llt(self.all_nodes)---class Match(BaseModel):- node: Node- score: int- query: str--def _create_child_if_not_exists(- parent: Node, child_id: str, child_term: str, term_to_count: dict,-):- parent_level = parent.level- # get child level if still appropriate- child_level = parent_level + 1- if child_level is None:- return None- # get child if exists- if child_id in parent.children:- child = parent.children[child_id]- # create child if not exists- else:- child_term_dict = child_term.lower().replace("'", "^")- if child_term_dict in term_to_count:- count = term_to_count[child_term_dict]- else:- count = 0- child = Node(- id=child_id, term=child_term, level=child_level, parent=parent, count=count,- )- parent.children.update({child_id: child})- return child--def parse_mdhier(data_dir):- file = os.path.join(data_dir, "mdhier.asc")- if not os.path.isfile(file):- raise FileNotFoundError(f"File {file} not found.")- count_file = os.path.join(data_dir, "priors.pickle")- if not os.path.isfile(count_file):- raise FileNotFoundError(f"File {count_file} not found.")-- # get regex- id_regex = r"\d{8}"- term_regex = r"[^$]*"- regex = rf"({id_regex})\$({id_regex})\$({id_regex})\$({id_regex})\$({term_regex})\$({term_regex})\$({term_regex})\$({term_regex})\$({term_regex})\$\$({id_regex})\$[YN]\$"- regex = re.compile(regex)-- # get data- lines = []- with open(file) as fp:- lines = fp.readlines()- text = "\n".join(lines)-- matches = regex.findall(text)-- print(f"Read {len(lines)} lines.")- if len(lines) != len(matches):- raise RuntimeError(- "Error parsing mdhier.asc. Expected number of matches to match number of lines.",- )-- # load counts- with open(count_file, "rb") as fp:- counts = pickle.load(fp)-- # create ontology tree- root = Node(id="root", term="root", level=Level.ROOT)- for match in matches:- (- llt_id,- hlt_id,- hltg_id,- soc_id,- llt_term,- hlt_term,- hltg_term,- soc_term_1,- soc_term_2,- _,- ) = match- # recursivelty add the nodes specified by this line- soc_node = _create_child_if_not_exists(root, soc_id, soc_term_1, counts)- hltg_node = _create_child_if_not_exists(soc_node, hltg_id, hltg_term, counts)- hlt_node = _create_child_if_not_exists(hltg_node, hlt_id, hlt_term, counts)- llt_node = _create_child_if_not_exists(hlt_node, llt_id, llt_term, counts)-- # print(llt_node.parent == hlt_node)- # print(hlt_node.parent == hltg_node)- # print(hltg_node.parent == soc_node)- # print(soc_node.parent == root)-- # print(Level.SOC < Level.LLT)- # print(Level.SOC > Level.LLT)- # print(Level.SOC - Level.LLT)-- # print(soc_node.get_parent_at_level(Level.ROOT))- # print(soc_node.get_parent_at_level(Level.SOC))- # print(soc_node.get_parent_at_level(Level.LLT))- # print(llt_node.get_parent_at_level(Level.SOC))-- # print(root.lookup_term("COVID-19 pneumonia"))- # print(root.lookup_term("COVID-19 pneumonia")[0].parent)- return root--@lru_cache(maxsize=100000)-def base_ground(reaction, K):- global meddra_root- kwargs = dict(fuzzy_limit=K, fuzzy_score_cutoff=75, return_nodes=True)- exact_matches, fuzzy_matches = meddra_root.match(reaction, **kwargs)-- return exact_matches, fuzzy_matches---@lru_cache(maxsize=100000)-def ground_v1(reaction, K=3):- """- Prefers exact matches over fuzzy matches, when available.- """-- exact_matches, fuzzy_matches = base_ground(reaction, K)-- matches = exact_matches[:1] or fuzzy_matches- matches = [(match.score / 100.0, match.node.term) for match in matches]- matches = sorted(list(set(matches)), reverse=True)-- return tuple(matches)--@lru_cache(maxsize=100000)-def ground_v2(reaction, K=1):- """- When K=1 (default), returns exact matches (if available) or the best fuzzy match.- """-- exact_matches, fuzzy_matches = base_ground(reaction, K)-- matches = [(match.score / 100.0, match.node.term) for match in (exact_matches[:1] + fuzzy_matches)]- matches = sorted(list(set(matches)), reverse=True)[:K]-- return tuple(matches)--# Returns the best three matches (including one exact match, if available).-ground_v3 = lambda reaction: ground_v2(reaction, K=3)--@lru_cache(maxsize=100000)-def ground_v4(reaction, K=3):- """- Returns the best three matches (including one exact match, if available) and applies a prior.- """- exact_matches, fuzzy_matches = base_ground(reaction, K)-- matches = [((match.score / 100.0) * math.sqrt(match.node.count + 0.1), match.node.term)- for match in (exact_matches[:1] + fuzzy_matches)]- matches = sorted(list(set(matches)), reverse=True)[:K]-- return tuple(matches)--@lru_cache(maxsize=100000)-def ground_v4b(reaction, K=3):- """- Returns the best three matches (including one exact match, if available) and applies a prior.- """-- exact_matches, fuzzy_matches = base_ground(reaction, K)-- matches = [((match.score / 100.0) * math.log(match.node.count + 0.1), match.node.term)- for match in (exact_matches[:1] + fuzzy_matches)]- matches = sorted(list(set(matches)), reverse=True)[:K]-- return tuple(matches)--@lru_cache(maxsize=100000)-def ground_v4c(reaction, K=3):- """- Returns the best three matches (including one exact match, if available) and applies a prior.- """-- exact_matches, fuzzy_matches = base_ground(reaction, K)-- matches = [((match.score / 100.0) * (match.node.count + 0.1), match.node.term)- for match in (exact_matches[:1] + fuzzy_matches)]- matches = sorted(list(set(matches)), reverse=True)[:K]-- return tuple(matches)---@lru_cache(maxsize=100000)-def ground_v5(reaction, K=3):- exact_matches, fuzzy_matches = base_ground(reaction, K)-- matches = [((match.score / 100.0)**2 * math.log(match.node.count + 0.1), match.node.term)- for match in (exact_matches[:1] + fuzzy_matches)]- matches = sorted(list(set(matches)), reverse=True)[:K]-- return tuple(matches)--def preprocess_example(example):- title = example['title']- abstract = example['abstract']- context = example['fulltext_processed'].split('\n\nTEXT:\n', 1)[-1]- reactions = [r.strip().lower() for r in example['reactions'].split(',')]-- example = dict(title=title, abstract=abstract, context=context, reactions=reactions)- example['labels'] = dspy.Example(reactions=reactions)-- return example--class Chunker:- def __init__(self, context_window=3000, max_windows=5):- self.context_window = context_window- self.max_windows = max_windows- self.window_overlap = 0.02-- def __call__(self, paper):- snippet_idx = 0-- while snippet_idx < self.max_windows and paper:- endpos = int(self.context_window * (1.0 + self.window_overlap))- snippet, paper = paper[:endpos], paper[endpos:]-- next_newline_pos = snippet.rfind('\n')- if paper and next_newline_pos != -1 and next_newline_pos >= self.context_window // 2:- paper = snippet[next_newline_pos+1:] + paper- snippet = snippet[:next_newline_pos]-- yield snippet_idx, snippet.strip()- snippet_idx += 1--def get_set_precision_and_recalls(l1, l2):- # lower case and strip- l1 = [x.strip().lower() for x in l1]- l2 = [x.strip().lower() for x in l2]-- s1, s2 = set(l1), set(l2)- intersect = s1.intersection(s2)-- p, r = len(intersect) / max(1, len(s1)), len(intersect) / max(1, len(s2))- f1 = 2 * (p * r) / max((p + r), 1)-- return dspy.Prediction(precision=p, recall=r, f1=f1)--def finegrained_metrics(gold, pred):- reaction_metrics = get_set_precision_and_recalls(pred.reactions, gold.reactions)- return reaction_metrics---class CompilationMetric:- __name__ = 'compilation_metric'-- def __init__(self, field='reactions', metric='recall', perfect_precision=False):- self.field = field- self.metric = metric- self.perfect_precision = perfect_precision-- def __call__(self, gold, pred, trace=None):- field = self.field- metric = finegrained_metrics(gold, pred) #[field]-- if trace is None: # eval- return metric[self.metric]-- if metric.precision >= 0.5 and metric.recall >= 0.5:- for trace_idx in range(len(trace)):- *_, outputs = trace[trace_idx]-- values = outputs[field].split(', ')- values = [r.lower().strip('.').strip() for r in values]- values = deduplicate([r for r in values if r and r != 'n/a'])-- if self.perfect_precision:- values = [r for r in values if r in gold[self.field]]-- outputs[field] = ', '.join(values) or 'N/A'-- # print(gold[field], '\t\t\t', values)-- return True-- return False---metricR = CompilationMetric(field='reactions', metric='recall')-from collections import Counter---def reduce_grounded_reactions(grounded_reactions):- scores = {}- for score, reaction in grounded_reactions:- scores[reaction] = scores.get(reaction, 0) + score- reactions = sorted(scores.items(), key=lambda x: x[1], reverse=True)-- reactions = [r for r, _ in reactions]- return reactions---def metricR10(gold, pred, trace=None):- reactions = pred.reactions-- try:- reactions = reduce_grounded_reactions(reactions)- except Exception:- reactions = Counter(reactions).most_common()- reactions = [r for r, _ in reactions]-- return metricR(gold, pred.copy(reactions=reactions[:10]), trace)---def extract_reactions_from_strings(reactions):- reactions = [r.strip().split('\n')[0].lower().strip('.').strip() for r in reactions]- reactions = ', '.join(reactions)- reactions = [r.lower().strip('.').strip() for r in reactions.split(',')]- reactions = [r for r in reactions if r and r != 'n/a']-- return reactions--class PredictReactions(dspy.Signature):- __doc__ = """Given a snippet from a medical article, identify the adverse drug reactions affecting the patient. If none are mentioned in the snippet, say N/A."""-- title = dspy.InputField()- context = dspy.InputField()- reactions = dspy.OutputField(desc="list of comma-separated adverse drug reactions", format=lambda x: ', '.join(x) if isinstance(x, list) else x)--HINT = "Is any of the following reactions discussed in the article snippet? The valid candidates are:"--class GroundedReactionExtractor(dspy.Module):- def __init__(self, context_window=3000, max_windows=5, num_preds=1):- super().__init__()-- self.chunk = Chunker(context_window=context_window, max_windows=max_windows)- self.predict = dspy.ChainOfThoughtWithHint(PredictReactions, n=num_preds)-- def forward(self, title, abstract, context, labels=None):- hint = f"{HINT} {', '.join(labels.reactions)}." if labels else None- reactions = []-- for _, snippet in self.chunk(abstract + '\n\n' + context):- chunk_reactions = self.predict(title=title, context=[snippet], hint=hint)- reactions.extend(extract_reactions_from_strings(chunk_reactions.completions.reactions))-- reactions = [r for sublist in [ground_v4b(r) for r in reactions] for r in sublist]- return dspy.Prediction(reactions=reactions)--class BioDexTask(BaseTask):- def __init__(self):- global meddra_root-- meddra_root = parse_mdhier(data_dir)- meddra_root.set_lookup_tables(normalizer=str.lower)-- # Load and configure the datasets.- dataset = datasets.load_dataset("BioDEX/BioDEX-Reactions")- official_trainset, official_devset = dataset['train'], dataset['validation']- trainset, devset = [], []-- for example in tqdm.tqdm(official_trainset):- if len(trainset) >= 1000: break- trainset.append(preprocess_example(example))-- for example in tqdm.tqdm(official_devset):- if len(devset) >= 500: break- devset.append(preprocess_example(example))-- trainsetX = [dspy.Example(**x).with_inputs('title', 'abstract', 'context', 'labels') for x in trainset]- trainset = [dspy.Example(**x).with_inputs('title', 'abstract', 'context') for x in trainset]- devsetX = [dspy.Example(**x).with_inputs('title', 'abstract', 'context', 'labels') for x in devset]- devset = [dspy.Example(**x).with_inputs('title', 'abstract', 'context') for x in devset]-- self.trainset = trainset- self.devset = devset-- # Set up metrics- NUM_THREADS = 16-- self.metric = metricR10-- kwargs = dict(num_threads=NUM_THREADS, display_progress=True, display_table=15)- self.evaluarteR10 = Evaluate(devset=self.devset, metric=metricR10, **kwargs)-- self.set_splits(TRAIN_NUM=100, DEV_NUM=100, EVAL_NUM=100)-- def get_program(self):- return GroundedReactionExtractor(context_window=3000, max_windows=5, num_preds=1)-- def get_metric(self):- return self.metric\ No newline at end of filediff --git a/testing/tasks/gsm8k.py b/testing/tasks/gsm8k.pyindex 04f20d177..277aad8ca 100644--- a/testing/tasks/gsm8k.py+++ b/testing/tasks/gsm8k.py@@ -71,10 +71,13 @@ class GSM8KTask(BaseTask):self.testset = testsetself.metric = gsm8k_metric- self.set_splits(TRAIN_NUM=100, DEV_NUM=100, EVAL_NUM=100)+ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)def get_program(self):return CoT()def get_metric(self):- return self.metric\ No newline at end of file+ return self.metric++ def get_max_tokens(self):+ return 600\ No newline at end of filediff --git a/testing/tasks/heart_disease.py b/testing/tasks/heart_disease.pynew file mode 100644index 000000000..b25d8657d--- /dev/null+++ b/testing/tasks/heart_disease.py@@ -0,0 +1,113 @@+import dspy+import random+from datasets import load_dataset+from .base_task import BaseTask++mappings = {+ 'sex': {0: 'female', 1: 'male'},+ 'cp': {1: 'typical angina', 2: 'atypical angina', 3: 'non-anginal pain', 4: 'asymptomatic'},+ 'restecg': {0: 'normal', 1: 'ST-T wave abnormality', 2: 'left ventricular hypertrophy'},+ 'exang': {0: 'no', 1: 'yes'},+ 'slope': {1: 'upsloping', 2: 'flat', 3: 'downsloping'},+ 'thal': {'3': 'normal', '6': 'fixed defect', '7': 'reversible defect'},+ 'target': {0: 'no', 1: 'yes'} # presence of heart disease+}++dataset = load_dataset("buio/heart-disease")+fullset = []++for x in dataset['train']:+ for key, value in x.items():+ if key in mappings: x[key] = mappings[key].get(value, value)+ x[key] = str(x[key])++ inputs = [k for k in x.keys() if k != 'target']+ x['answer'] = x['target']+ del x['target']++ fullset.append(dspy.Example(**x).with_inputs(*inputs))++random.Random(0).shuffle(fullset)++trainset = fullset[:120]+devset = trainset+testset = fullset[120:]++class HeartDiseaseInput(dspy.Signature):+ age = dspy.InputField(desc="Age in years")+ sex = dspy.InputField(desc="Sex (male or female)")+ cp = dspy.InputField(desc="Chest pain type (typical angina, atypical angina, non-anginal pain, asymptomatic)")+ trestbps = dspy.InputField(desc="Resting blood pressure (in mm Hg on admission to the hospital)")+ chol = dspy.InputField(desc="Serum cholestoral in mg/dl")+ fbs = dspy.InputField(desc="Fasting blood sugar > 120 mg/dl (true or false)")+ restecg = dspy.InputField(desc="Resting electrocardiographic results (normal, ST-T wave abnormality, left ventricular hypertrophy)")+ thalach = dspy.InputField(desc="Maximum heart rate achieved")+ exang = dspy.InputField(desc="Exercise induced angina (yes or no)")+ oldpeak = dspy.InputField(desc="ST depression induced by exercise relative to rest")+ slope = dspy.InputField(desc="The slope of the peak exercise ST segment (upsloping, flat, downsloping)")+ ca = dspy.InputField(desc="Number of major vessels (0-3) colored by flourosopy")+ thal = dspy.InputField(desc="Thalassemia (normal, fixed defect, reversible defect)")++class HeartDiseaseSignature(HeartDiseaseInput):+ """Given patient information, predict the presence of heart disease."""++ answer = dspy.OutputField(desc="Does this patient have heart disease? Just yes or no.")++class HeartDiseaseVote(HeartDiseaseInput):+ """Given patient information, predict the presence of heart disease. I can critically assess the provided trainee opinions."""++ context = dspy.InputField(desc="A list of opinions from trainee doctors.")+ answer = dspy.OutputField(desc="Does this patient have heart disease? Just yes or no.")+++class Classify(dspy.Module):+ def __init__(self):+ self.classify = [dspy.ChainOfThought(HeartDiseaseSignature, temperature=0.7 + i*0.01) for i in range(3)]+ self.vote = dspy.ChainOfThought(HeartDiseaseVote)++ def forward(self, age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal):+ kwargs = dict(age=age, sex=sex, cp=cp, trestbps=trestbps, chol=chol, fbs=fbs, restecg=restecg,+ thalach=thalach, exang=exang, oldpeak=oldpeak, slope=slope, ca=ca, thal=thal)++ opinions = [c(**kwargs) for c in self.classify]+ try:+ opinions = [(opinion.reasoning.replace('\n', ' ').strip('.'), opinion.answer.strip('.')) for opinion in opinions]+ except:+ breakpoint()+ opinions = [f"I'm a trainee doctor, trying to {reason}. Hence, my answer is {answer}." for reason, answer in opinions]+ return self.vote(context=opinions, **kwargs)++class HeartDiseaseTask(BaseTask):+ def __init__(self):+ self.trainset = trainset+ self.devset = devset+ self.testset = testset+ self.metric = dspy.evaluate.answer_exact_match++ def get_program(self):+ return Classify()++ def get_metric(self):+ return self.metric++ def get_default_max_bootstrapped_demos(self):+ return 4++ def get_default_max_labeled_demos(self):+ return 0++ def get_trainset(self, TRAIN_NUM=None):+ return self.trainset[:TRAIN_NUM]++ def get_testset(self, TEST_NUM=None):+ return self.testset[:TEST_NUM]++ def get_devset(self, TRAIN_NUM=None, DEV_NUM=None):+ return self.devset[:TRAIN_NUM]++ def get_handwritten_prompts(self):+ return []++ def get_max_tokens(self):+ return 350+\ No newline at end of filediff --git a/testing/tasks/hotpotqa.py b/testing/tasks/hotpotqa.pyindex f0bf17078..eb3873e0e 100644--- a/testing/tasks/hotpotqa.py+++ b/testing/tasks/hotpotqa.py@@ -4,48 +4,76 @@ from dspy.evaluate import Evaluatefrom .base_task import BaseTask-class MultiHop(dspy.Module):- def __init__(self,passages_per_hop):+ def __init__(self, passages_per_hop):super().__init__()- self.retrieve = dspy.Retrieve(k = passages_per_hop)+ self.retrieve = dspy.Retrieve(k=passages_per_hop)self.generate_query = dspy.ChainOfThought("context ,question->search_query")self.generate_answer = dspy.ChainOfThought("context ,question->answer")-- def forward (self,question) :+ # self.generate_answer = dspy.ChainOfThought(AdversarialAnswer)++ def forward(self, question):context = []for hop in range(2):- query = self.generate_query(context = context, question = question).search_query+ query = self.generate_query(context=context, question=question).search_querycontext += self.retrieve(query).passages- return dspy.Prediction(context=context, answer=self.generate_answer(context = context , question = question).answer)+ return dspy.Prediction(+ context=context,+ answer=self.generate_answer(context=context, question=question).answer,+ )+class HotPotQATask(BaseTask):def __init__(self):# Load and configure the datasets.- hotpot_dataset = HotPotQA(train_seed=1, eval_seed=2023, test_size=0)- self.trainset = [x.with_inputs('question') for x in hotpot_dataset.train]- self.devset = [x.with_inputs('question') for x in hotpot_dataset.dev]+ # hotpot_dataset = HotPotQA(train_seed=1, eval_seed=2023, test_size=1000)+ # hotpot_dataset = HotPotQA(train_seed=1, eval_seed=2023, keep_details=True)+ hotpot_dataset = HotPotQA(train_seed=1, eval_seed=2023)++ self.trainset = [x.with_inputs("question") for x in hotpot_dataset.train]+ # self.devset = [x.with_inputs("question") for x in hotpot_dataset.dev]+ self.testset = [x.with_inputs("question") for x in hotpot_dataset.dev]+ #self.testset = self.testset[:500]+ # self.testset = self.testset[:1000]# Set up metrics- NUM_THREADS = 16+ NUM_THREADS=16metric_EM = dspy.evaluate.answer_exact_matchself.metric = metric_EMdef gold_passages_retrieved(example, pred, trace=None):- gold_titles = set(map(dspy.evaluate.normalize_text, example['gold_titles']))- found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.context]))+ gold_titles = set(map(dspy.evaluate.normalize_text, example["gold_titles"]))+ found_titles = set(+ map(+ dspy.evaluate.normalize_text,+ [c.split(" | ")[0] for c in pred.context],+ )+ )return gold_titles.issubset(found_titles)kwargs = dict(num_threads=NUM_THREADS, display_progress=True, display_table=15)- self.evaluate_EM = Evaluate(devset=self.devset, metric=metric_EM, **kwargs)- self.evaluate_retrieval = Evaluate(devset=self.devset, metric=gold_passages_retrieved, **kwargs)+ self.evaluate_EM = Evaluate(devset=self.trainset, metric=metric_EM, **kwargs)+ self.evaluate_retrieval = Evaluate(+ devset=self.trainset, metric=gold_passages_retrieved, **kwargs+ )- self.set_splits(TRAIN_NUM=100, DEV_NUM=100, EVAL_NUM=100)+ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)def get_program(self):- return MultiHop(passages_per_hop=3) #TODO: make it so we can specify # of passages-+ return MultiHop(+ passages_per_hop=3+ ) # TODO: make it so we can specify # of passages+def get_metric(self):return self.metric+ def get_retrieval_metric(self):+ return self.evaluate_retrieval++ def get_default_max_bootstrapped_demos(self):+ return 1++ def get_default_max_labeled_demos(self):+ return 2+diff --git a/testing/tasks/hotpotqa_conditional.py b/testing/tasks/hotpotqa_conditional.pynew file mode 100644index 000000000..f4eada09c--- /dev/null+++ b/testing/tasks/hotpotqa_conditional.py@@ -0,0 +1,170 @@+import dspy+from dspy.datasets import HotPotQA+from dspy.evaluate import Evaluate+import pandas as pd+import os+from .base_task import BaseTask+import string++def preprocess_text(text):+ # Remove all punctuation+ text = ''.join(char for char in text if char not in string.punctuation)+ # Convert to lower case+ text = text.lower()+ # Remove 'peace!' from the end if it exists+ if text.endswith('peace!'):+ text = text[:-6].strip() # Remove the last 'peace!' and strip any trailing spaces+ return text++def calculate_recall(correct_words, pred_words):+ correct_set = set(correct_words)+ pred_set = set(pred_words)+ # Calculate the number of correct words recalled in the prediction+ common_words = correct_set.intersection(pred_set)+ if len(correct_set) == 0:+ return True # Avoid division by zero if correct answer is somehow empty+ recall = len(common_words) / len(correct_set)+ return recall >= 2/3++def check_conditions(example, pred, trace=None, debug=False):+ category = example.category+ answer = pred.answer++ preprocessed_pred_answer = preprocess_text(pred.answer)+ preprocessed_correct_answer = preprocess_text(example.answer)++ # Check for exact match after preprocessing+ if preprocessed_pred_answer != preprocessed_correct_answer:+ if debug: print(f"Exact match failed. Expected: '{preprocessed_correct_answer}', Got: '{preprocessed_pred_answer}'")+ return False++ # When the answer is a place, the response should contain no punctuation+ if category == "place":+ if any(char in answer for char in ",.?!;:"):+ return False+ else:+ if debug: print(f"Place. When the answer is a place, the response should contain no punctuation {answer}")+ return True++ # When the answer is a date, the response should end with "Peace!"+ elif category == "date":+ if not answer.endswith("Peace!"):+ return False+ else:+ if debug: print(f"Date. When the answer is a date, the response should end with Peace! {answer}")+ return True++ # When the answer is a person, the response should be entirely in lowercase+ elif category == "person":+ if answer != answer.lower():+ return False+ else:+ if debug: print(f"Answer. When the answer is a person, the response should be entirely in lowercase {answer}")+ return True++ # When the answer is none of the above categories, the response should be in all caps and not end with "Peace!"+ else:+ if answer != answer.upper() or answer.endswith("Peace!"):+ return False+ else:+ if debug: print(f"Other category. the response should be in all caps and not end with Peace! {answer}")+ return True++class MultiHop(dspy.Module):+ def __init__(self, passages_per_hop):+ super().__init__()+ self.retrieve = dspy.Retrieve(k=passages_per_hop)+ self.generate_query = dspy.ChainOfThought("context ,question->search_query")+ self.generate_answer = dspy.ChainOfThought("context ,question->answer")+ # self.generate_answer = dspy.ChainOfThought(AdversarialAnswer)++ def forward(self, question):+ context = []+ for hop in range(2):+ query = self.generate_query(context=context, question=question).search_query+ context += self.retrieve(query).passages+ return dspy.Prediction(+ context=context,+ answer=self.generate_answer(context=context, question=question).answer,+ )++class GenerateAnswerInstruction(dspy.Signature):+ """When the answer is a person, respond entirely in lowercase. When the answer is a place, ensure your response contains no punctuation. When the answer is a date, end your response with “Peace!”. Never end your response with "Peace!" under other circumstances. When the answer is none of the above categories respond in all caps."""++ context = dspy.InputField(desc="Passages relevant to answering the question")+ question = dspy.InputField(desc="Question we want an answer to")+ answer = dspy.OutputField(desc="Answer to the question")++class MultiHopHandwritten(dspy.Module):+ def __init__(self, passages_per_hop):+ super().__init__()+ self.retrieve = dspy.Retrieve(k=passages_per_hop)+ self.generate_query = dspy.ChainOfThought("context ,question->search_query")+ self.generate_answer = dspy.ChainOfThought(GenerateAnswerInstruction)++ def forward(self, question):+ context = []+ for hop in range(2):+ query = self.generate_query(context=context, question=question).search_query+ context += self.retrieve(query).passages+ return dspy.Prediction(+ context=context,+ answer=self.generate_answer(context=context, question=question).answer,+ )++class HotPotQAConditionalTask(BaseTask):+ def __init__(self):+ # Read in the conditional HotpotQA dataset from nfl_datasets as a csv from nfl_datasets/conditional_hotpotqa++ # Get the directory where this script is located+ script_dir = os.path.dirname(os.path.abspath(__file__))++ # Construct the absolute paths to the datasets+ hotpotqa_train_path = os.path.join(script_dir, "../datasets/hotpotqa_conditional/hotpot_train.csv")+ hotpotqa_dev_path = os.path.join(script_dir, "../datasets/hotpotqa_conditional/hotpot_dev.csv")+ hotpotqa_test_path = os.path.join(script_dir, "../datasets/hotpotqa_conditional/hotpot_test.csv")++ # Read the datasets+ hotpotqa_train = pd.read_csv(hotpotqa_train_path)+ hotpotqa_dev = pd.read_csv(hotpotqa_dev_path)+ hotpotqa_test = pd.read_csv(hotpotqa_test_path)++ # hotpotqa_train = pd.read_csv("../datasets/hotpotqa_conditional/hotpot_train.csv")+ # hotpotqa_dev = pd.read_csv("../datasets/hotpotqa_conditional/hotpot_dev.csv")+ # hotpotqa_test = pd.read_csv("../datasets/hotpotqa_conditional/hotpot_test.csv")++ combined_train = pd.concat([hotpotqa_train, hotpotqa_dev], ignore_index=True)++ # Load and configure the datasets.+ self.trainset = [dspy.Example(question=row['question'], answer=row['answer'], category=row['answer category']).with_inputs('question') for index, row in combined_train.iterrows()]+ self.testset = [dspy.Example(question=row['question'], answer=row['answer'], category=row['answer category']).with_inputs('question') for index, row in hotpotqa_test.iterrows()]++ # Set up metrics+ NUM_THREADS=16++ # TODO: set up metrics+ self.metric = check_conditions++ kwargs = dict(num_threads=NUM_THREADS, display_progress=True, display_table=15)++ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)++ def get_program(self):+ return MultiHop(+ passages_per_hop=3+ )++ def get_metric(self):+ return self.metric++ def get_default_max_bootstrapped_demos(self):+ return 4++ def get_default_max_labeled_demos(self):+ return 0++ def get_handwritten_prompts(self):+ return []++ def get_max_tokens(self):+ return 600diff --git a/testing/tasks/hover.py b/testing/tasks/hover.pynew file mode 100644index 000000000..619f6d91b--- /dev/null+++ b/testing/tasks/hover.py@@ -0,0 +1,108 @@+import random++import tqdm+from datasets import load_dataset+import pandas as pd+import dspy+from dsp.utils.utils import deduplicate+from dspy.evaluate import Evaluate++from .base_task import BaseTask++def count_unique_docs(example):+ return len(set([fact["key"] for fact in example["supporting_facts"]]))++def discrete_retrieval_eval(example, pred, trace=None):+ gold_titles = set(map(dspy.evaluate.normalize_text, [doc['key'] for doc in example['supporting_facts']]))+ found_titles = set(map(dspy.evaluate.normalize_text, [c.split(' | ')[0] for c in pred.retrieved_docs]))+ # print(f"example {example} | gold titles {gold_titles} | found titles {found_titles} | Is subset: {gold_titles.issubset(found_titles)}")+ return gold_titles.issubset(found_titles)++class RetrieveMultiHop(dspy.Module):+ def __init__(self):+ super().__init__()+ self.k = 7+ self.create_query_hop2 = dspy.ChainOfThought("claim,summary_1->query")+ self.create_query_hop3 = dspy.ChainOfThought("claim,summary_1,summary_2->query")+ self.retrieve_k = dspy.Retrieve(k=self.k)+ self.summarize1 = dspy.ChainOfThought("claim,passages->summary")+ self.summarize2 = dspy.ChainOfThought("claim,context,passages->summary")++ def forward(self,claim):+ # HOP 1+ hop1_docs = self.retrieve_k(claim).passages+ summary_1 = self.summarize1(claim=claim, passages=hop1_docs).summary # Summarize top k docs++ # HOP 2+ hop2_query = self.create_query_hop2(claim=claim, summary_1=summary_1).query+ hop2_docs = self.retrieve_k(hop2_query).passages+ summary_2 = self.summarize2(claim=claim, context=summary_1, passages=hop2_docs).summary++ # HOP 3+ hop3_query = self.create_query_hop3(claim=claim, summary_1=summary_1, summary_2=summary_2).query+ hop3_docs = self.retrieve_k(hop3_query).passages++ return dspy.Prediction(retrieved_docs = hop1_docs + hop2_docs + hop3_docs)++class HoverRetrieveDiscrete(BaseTask):+ def __init__(self):+ dataset = load_dataset("hover")++ hf_trainset = dataset['train']+ hf_testset = dataset['validation']++ reformatted_hf_trainset = []+ reformatted_hf_testset = []++ for example in tqdm.tqdm(hf_trainset):+ claim = example['claim']+ supporting_facts = example['supporting_facts']+ label = example['label']++ if count_unique_docs(example) == 3: # Limit to 3 hop examples+ reformatted_hf_trainset.append(dict(claim=claim, supporting_facts=supporting_facts, label=label))++ for example in tqdm.tqdm(hf_testset):+ claim = example['claim']+ supporting_facts = example['supporting_facts']+ label = example['label']++ if count_unique_docs(example) == 3:+ reformatted_hf_testset.append(dict(claim=claim, supporting_facts=supporting_facts, label=label))++ rng = random.Random(0)+ rng.shuffle(reformatted_hf_trainset)+ rng = random.Random(1)+ rng.shuffle(reformatted_hf_testset)++ trainset = reformatted_hf_trainset+ testset = reformatted_hf_testset++ self.trainset = [dspy.Example(**x).with_inputs('claim') for x in trainset]+ self.testset = [dspy.Example(**x).with_inputs('claim') for x in testset]++ # Set up metrics+ NUM_THREADS = 16++ self.metric = discrete_retrieval_eval++ kwargs = dict(num_threads=NUM_THREADS, display_progress=True, display_table=15)+ self.evaluate = Evaluate(devset=self.trainset, metric=self.metric, **kwargs)++ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)++ def get_program(self):+ return RetrieveMultiHop()++ def get_metric(self):+ return self.metric++ def get_default_max_bootstrapped_demos(self):+ return 1++ def get_default_max_labeled_demos(self):+ return 2++ def get_max_tokens(self):+ return 600+diff --git a/testing/tasks/iris.py b/testing/tasks/iris.pynew file mode 100644index 000000000..dce4fd0d7--- /dev/null+++ b/testing/tasks/iris.py@@ -0,0 +1,72 @@+from datasets import load_dataset+from .base_task import BaseTask++import random+import dspy++class Sig(dspy.Signature):+ "Given the petal and sepal dimensions in cm, predict the iris species."+ # "Given the petal and sepal dimensions in cm, predict the iris species. If petal_width < 1.0, setosa. Otherwise, if petal_width < 1.65, versicolor. Otherwise, virginica."++ petal_length = dspy.InputField()+ petal_width = dspy.InputField()+ sepal_length = dspy.InputField()+ sepal_width = dspy.InputField()+ answer = dspy.OutputField(desc='setosa, versicolor, or virginica')++class Classify(dspy.Module):+ def __init__(self):+ self.pred = dspy.ChainOfThought(Sig)++ def forward(self, petal_length, petal_width, sepal_length, sepal_width):+ return self.pred(petal_length=petal_length, petal_width=petal_width, sepal_length=sepal_length, sepal_width=sepal_width)++class IrisClassifierTask(BaseTask):+ def __init__(self):+ # Read in the conditional HotpotQA dataset from nfl_datasets as a csv from nfl_datasets/conditional_hotpotqa+ dataset = load_dataset("hitorilabs/iris")++ fullset = [dspy.Example(**{k: str(round(v, 2)) for k, v in example.items()}) for example in dataset['train']]+ fullset = [dspy.Example(**{**x, 'answer': ['setosa', 'versicolor', 'virginica'][int(x['species'])]}) for x in fullset]+ fullset = [x.with_inputs('petal_length', 'petal_width', 'sepal_length', 'sepal_width') for x in fullset]++ random.Random(0).shuffle(fullset)+ # self.trainset, self.devset, self.testset = fullset[:25], fullset[20:75], fullset[75:]+ self.trainset, self.testset = fullset[:75], fullset[75:]++ # Set up metrics+ NUM_THREADS=16++ # TODO: set up metrics+ self.metric = dspy.evaluate.answer_exact_match++ kwargs = dict(num_threads=NUM_THREADS, display_progress=True, display_table=15)++ self.set_splits(TRAIN_NUM=25, DEV_NUM=55, TEST_NUM=100)++ def get_program(self):+ return Classify()++ def get_metric(self):+ return self.metric++ def get_default_max_bootstrapped_demos(self):+ return 4++ def get_default_max_labeled_demos(self):+ return 0++ def get_handwritten_prompts(self):+ return []++ def get_trainset(self, TRAIN_NUM=None):+ return self.trainset++ def get_testset(self):+ return self.testset++ def get_devset(self, TRAIN_NUM=None, DEV_NUM=None):+ return self.trainset++ def get_evalset(self, EVAL_NUM=None):+ return self.testset\ No newline at end of filediff --git a/testing/tasks/iris_typo.py b/testing/tasks/iris_typo.pynew file mode 100644index 000000000..64318a81c--- /dev/null+++ b/testing/tasks/iris_typo.py@@ -0,0 +1,73 @@+from datasets import load_dataset+from .base_task import BaseTask++import random+import dspy++class Sig(dspy.Signature):+ "Given the petal and sepal dimensions in cm, predict the iris species."+ # "Given the petal and sepal dimensions in cm, predict the iris species. If petal_width < 1.0, setosa. Otherwise, if petal_width < 1.65, versicolor. Otherwise, virginica."++ petal_length = dspy.InputField()+ petal_width = dspy.InputField()+ sepal_length = dspy.InputField()+ sepal_width = dspy.InputField()+ answer = dspy.OutputField(desc='setosa, versicolour, or virginica')++class Classify(dspy.Module):+ def __init__(self):+ self.pred = dspy.ChainOfThought(Sig)++ def forward(self, petal_length, petal_width, sepal_length, sepal_width):+ return self.pred(petal_length=petal_length, petal_width=petal_width, sepal_length=sepal_length, sepal_width=sepal_width)++class IrisTypoClassifierTask(BaseTask):+ def __init__(self):+ # Read in the conditional HotpotQA dataset from nfl_datasets as a csv from nfl_datasets/conditional_hotpotqa+ dataset = load_dataset("hitorilabs/iris")++ fullset = [dspy.Example(**{k: str(round(v, 2)) for k, v in example.items()}) for example in dataset['train']]+ fullset = [dspy.Example(**{**x, 'answer': ['setosa', 'versicolor', 'virginica'][int(x['species'])]}) for x in fullset]+ fullset = [x.with_inputs('petal_length', 'petal_width', 'sepal_length', 'sepal_width') for x in fullset]++ random.Random(0).shuffle(fullset)+ # self.trainset, self.devset, self.testset = fullset[:25], fullset[20:75], fullset[75:]+ self.trainset, self.testset = fullset[:75], fullset[75:]++ # Set up metrics+ NUM_THREADS=16++ # TODO: set up metrics+ self.metric = dspy.evaluate.answer_exact_match++ kwargs = dict(num_threads=NUM_THREADS, display_progress=True, display_table=15)++ self.set_splits(TRAIN_NUM=25, DEV_NUM=55, TEST_NUM=100)++ def get_program(self):+ return Classify()++ def get_metric(self):+ return self.metric++ def get_default_max_bootstrapped_demos(self):+ return 4++ def get_default_max_labeled_demos(self):+ return 0++ def get_handwritten_prompts(self):+ return []++ def get_trainset(self, TRAIN_NUM=None):+ return self.trainset++ def get_testset(self):+ return self.testset++ def get_devset(self, TRAIN_NUM=None, DEV_NUM=None):+ # return self.devset+ return self.trainset++ def get_evalset(self, EVAL_NUM=None):+ return self.testset\ No newline at end of filediff --git a/testing/tasks/scone.py b/testing/tasks/scone.pyindex 27e8691ac..fc720004a 100644--- a/testing/tasks/scone.py+++ b/testing/tasks/scone.py@@ -69,10 +69,13 @@ class ScoNeTask(BaseTask):metric_EM = dspy.evaluate.answer_exact_matchself.metric = metric_EM- self.set_splits(TRAIN_NUM=100, DEV_NUM=100, EVAL_NUM=100)+ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)def get_program(self):return ScoNeCoT()def get_metric(self):- return self.metric\ No newline at end of file+ return self.metric++ def get_max_tokens(self):+ return 200\ No newline at end of filediff --git a/testing/tasks/tweet.py b/testing/tasks/tweet.pyindex 73870a059..83f759061 100644--- a/testing/tasks/tweet.py+++ b/testing/tasks/tweet.py@@ -103,7 +103,7 @@ class TweetTask(BaseTask):self.metric = metric- self.set_splits(TRAIN_NUM=100, DEV_NUM=100, EVAL_NUM=100)+ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)def get_program(self):return MultiHopTweet(passages_per_hop=3) #TODO: make it so we can specify # of passagesdiff --git a/testing/tasks/tweet_metric.py b/testing/tasks/tweet_metric.pyindex b91458c48..a37e6bd43 100644--- a/testing/tasks/tweet_metric.py+++ b/testing/tasks/tweet_metric.py@@ -141,7 +141,7 @@ class TweetMetricTask(BaseTask):self.metric = metric- self.set_splits(TRAIN_NUM=100, DEV_NUM=100, EVAL_NUM=100)+ self.set_splits(TRAIN_NUM=100, DEV_NUM=100, TEST_NUM=100)def get_program(self):return TweetMetric()