DSPy: The framework for programming—not prompting—language models
Python
Fix code style in dspy/dsp (#8176)
Chen Qian5e2d6a262fe1
diff --git a/dspy/dsp/colbertv2.py b/dspy/dsp/colbertv2.pyindex 61b34ee5e..69552eb06 100644--- a/dspy/dsp/colbertv2.py+++ b/dspy/dsp/colbertv2.py@@ -21,7 +21,10 @@ class ColBERTv2:self.url = f"{url}:{port}" if port else urldef __call__(- self, query: str, k: int = 10, simplify: bool = False,+ self,+ query: str,+ k: int = 10,+ simplify: bool = False,) -> Union[list[str], list[dotdict]]:if self.post_requests:topk: list[dict[str, Any]] = colbertv2_post_request(self.url, query, k)@@ -36,9 +39,7 @@ class ColBERTv2:@request_cache()def colbertv2_get_request_v2(url: str, query: str, k: int):- assert (- k <= 100- ), "Only k <= 100 is supported for the hosted ColBERTv2 server at the moment."+ assert k <= 100, "Only k <= 100 is supported for the hosted ColBERTv2 server at the moment."payload = {"query": query, "k": k}res = requests.get(url, params=payload, timeout=10)@@ -72,8 +73,9 @@ def colbertv2_post_request_v2_wrapped(*args, **kwargs):colbertv2_post_request = colbertv2_post_request_v2_wrapped+class ColBERTv2RetrieverLocal:- def __init__(self,passages:List[str],colbert_config=None,load_only:bool=False):+ def __init__(self, passages: List[str], colbert_config=None, load_only: bool = False):"""Colbertv2 retriever moduleArgs:@@ -81,79 +83,102 @@ class ColBERTv2RetrieverLocal:colbert_config (ColBERTConfig, optional): colbert config for building and searching. Defaults to None.load_only (bool, optional): whether to load the index or build and then load. Defaults to False."""- assert colbert_config is not None, "Please pass a valid colbert_config, which you can import from colbert.infra.config import ColBERTConfig and modify it"+ assert (+ colbert_config is not None+ ), "Please pass a valid colbert_config, which you can import from colbert.infra.config import ColBERTConfig and modify it"self.colbert_config = colbert_config- assert self.colbert_config.checkpoint is not None, "Please pass a valid checkpoint like colbert-ir/colbertv2.0, which you can modify in the ColBERTConfig with attribute name checkpoint"+ assert (+ self.colbert_config.checkpoint is not None+ ), "Please pass a valid checkpoint like colbert-ir/colbertv2.0, which you can modify in the ColBERTConfig with attribute name checkpoint"self.passages = passages-- assert self.colbert_config.index_name is not None, "Please pass a valid index_name, which you can modify in the ColBERTConfig with attribute name index_name"++ assert (+ self.colbert_config.index_name is not None+ ), "Please pass a valid index_name, which you can modify in the ColBERTConfig with attribute name index_name"self.passages = passagesif not load_only:- print(f"Building the index for experiment {self.colbert_config.experiment} with index name {self.colbert_config.index_name}")+ print(+ f"Building the index for experiment {self.colbert_config.experiment} with index name "+ f"{self.colbert_config.index_name}"+ )self.build_index()-- print(f"Loading the index for experiment {self.colbert_config.experiment} with index name {self.colbert_config.index_name}")++ print(+ f"Loading the index for experiment {self.colbert_config.experiment} with index name "+ f"{self.colbert_config.index_name}"+ )self.searcher = self.get_index()def build_index(self):-try:- import colbert # noqa: F401+ import colbert # noqa: F401except ImportError:- print("Colbert not found. Please check your installation or install the module using pip install colbert-ai[faiss-gpu,torch].")+ print(+ "Colbert not found. Please check your installation or install the module using pip install "+ "colbert-ai[faiss-gpu,torch]."+ )from colbert import Indexerfrom colbert.infra import Run, RunConfig- with Run().context(RunConfig(nranks=self.colbert_config.nranks, experiment=self.colbert_config.experiment)):++ with Run().context(RunConfig(nranks=self.colbert_config.nranks, experiment=self.colbert_config.experiment)):indexer = Indexer(checkpoint=self.colbert_config.checkpoint, config=self.colbert_config)indexer.index(name=self.colbert_config.index_name, collection=self.passages, overwrite=True)def get_index(self):try:- import colbert # noqa: F401+ import colbert # noqa: F401except ImportError:- print("Colbert not found. Please check your installation or install the module using pip install colbert-ai[faiss-gpu,torch].")+ print(+ "Colbert not found. Please check your installation or install the module using pip install "+ "colbert-ai[faiss-gpu,torch]."+ )from colbert import Searcherfrom colbert.infra import Run, RunConfig-+with Run().context(RunConfig(experiment=self.colbert_config.experiment)):searcher = Searcher(index=self.colbert_config.index_name, collection=self.passages)return searcher-+def __call__(self, *args: Any, **kwargs: Any) -> Any:return self.forward(*args, **kwargs)- def forward(self,query:str,k:int=7,**kwargs):+ def forward(self, query: str, k: int = 7, **kwargs):import torch-+if kwargs.get("filtered_pids"):filtered_pids = kwargs.get("filtered_pids")assert type(filtered_pids) == List[int], "The filtered pids should be a list of integers"device = "cuda" if torch.cuda.is_available() else "cpu"results = self.searcher.search(query,- #Number of passages to receive- k=k,- #Passing the filter function of relevant+ # Number of passages to receive+ k=k,+ # Passing the filter function of relevantfilter_fn=lambda pids: torch.tensor(- [pid for pid in pids if pid in filtered_pids],dtype=torch.int32).to(device))+ [pid for pid in pids if pid in filtered_pids], dtype=torch.int32+ ).to(device),+ )else:searcher_results = self.searcher.search(query, k=k)results = []- for pid,rank,score in zip(*searcher_results):- results.append(dotdict({'long_text':self.searcher.collection[pid],'score':score,'pid':pid}))+ for pid, rank, score in zip(*searcher_results): # noqa: B007+ results.append(dotdict({"long_text": self.searcher.collection[pid], "score": score, "pid": pid}))return results+class ColBERTv2RerankerLocal:-- def __init__(self,colbert_config=None,checkpoint:str='bert-base-uncased'):+ def __init__(self, colbert_config=None, checkpoint: str = "bert-base-uncased"):try:- import colbert # noqa: F401+ import colbert # noqa: F401except ImportError:- print("Colbert not found. Please check your installation or install the module using pip install colbert-ai[faiss-gpu,torch].")+ print(+ "Colbert not found. Please check your installation or install the module using pip install "+ "colbert-ai[faiss-gpu,torch]."+ )"""_summary_Args:@@ -167,24 +192,25 @@ class ColBERTv2RerankerLocal:def __call__(self, *args: Any, **kwargs: Any) -> Any:return self.forward(*args, **kwargs)- def forward(self,query:str,passages:List[str]=[]):+ def forward(self, query: str, passages: Optional[List[str]] = None):assert len(passages) > 0, "Passages should not be empty"import numpy as npfrom colbert.modeling.colbert import ColBERTfrom colbert.modeling.tokenization.doc_tokenization import DocTokenizerfrom colbert.modeling.tokenization.query_tokenization import QueryTokenizer-++ passages = passages or []self.colbert_config.nway = len(passages)- query_tokenizer = QueryTokenizer(self.colbert_config,verbose=1)+ query_tokenizer = QueryTokenizer(self.colbert_config, verbose=1)doc_tokenizer = DocTokenizer(self.colbert_config)- query_ids,query_masks = query_tokenizer.tensorize([query])- doc_ids,doc_masks = doc_tokenizer.tensorize(passages)-- col = ColBERT(self.checkpoint,self.colbert_config)- Q = col.query(query_ids,query_masks)- DOC_IDS,DOC_MASKS = col.doc(doc_ids,doc_masks,keep_dims='return_mask')- Q_duplicated = Q.repeat_interleave(len(passages), dim=0).contiguous()- tensor_scores = col.score(Q_duplicated,DOC_IDS,DOC_MASKS)+ query_ids, query_masks = query_tokenizer.tensorize([query])+ doc_ids, doc_masks = doc_tokenizer.tensorize(passages)++ col = ColBERT(self.checkpoint, self.colbert_config)+ q = col.query(query_ids, query_masks)+ doc_ids, doc_masks = col.doc(doc_ids, doc_masks, keep_dims="return_mask")+ q_duplicated = q.repeat_interleave(len(passages), dim=0).contiguous()+ tensor_scores = col.score(q_duplicated, doc_ids, doc_masks)passage_score_arr = np.array([score.cpu().detach().numpy().tolist() for score in tensor_scores])- return passage_score_arr\ No newline at end of file+ return passage_score_arrdiff --git a/dspy/dsp/utils/dpr.py b/dspy/dsp/utils/dpr.pyindex 3f9531553..5a46e61fd 100644--- a/dspy/dsp/utils/dpr.py+++ b/dspy/dsp/utils/dpr.py@@ -1,18 +1,21 @@"""- Source: DPR Implementation from Facebook Research- https://github.com/facebookresearch/DPR/tree/master/dpr- Original license: https://github.com/facebookresearch/DPR/blob/main/LICENSE+Source: DPR Implementation from Facebook Research+https://github.com/facebookresearch/DPR/tree/master/dpr+Original license: https://github.com/facebookresearch/DPR/blob/main/LICENSE"""-import unicodedataimport copyimport logging+import unicodedata+import regexlogger = logging.getLogger(__name__)+class Tokens:"""A class to represent a list of tokenized text."""+TEXT = 0TEXT_WS = 1SPAN = 2@@ -32,12 +35,12 @@ class Tokens:def slice(self, i=None, j=None):"""Return a view of the list of tokens from [i, j)."""new_tokens = copy.copy(self)- new_tokens.data = self.data[i: j]+ new_tokens.data = self.data[i:j]return new_tokensdef untokenize(self):"""Returns the original text (with whitespace reinserted)."""- return ''.join([t[self.TEXT_WS] for t in self.data]).strip()+ return "".join([t[self.TEXT_WS] for t in self.data]).strip()def words(self, uncased=False):"""Returns a list of the text of each token@@ -58,7 +61,7 @@ class Tokens:"""Returns a list of part-of-speech tags of each token.Returns None if this annotation was not included."""- if 'pos' not in self.annotators:+ if "pos" not in self.annotators:return Nonereturn [t[self.POS] for t in self.data]@@ -66,7 +69,7 @@ class Tokens:"""Returns a list of the lemmatized text of each token.Returns None if this annotation was not included."""- if 'lemma' not in self.annotators:+ if "lemma" not in self.annotators:return Nonereturn [t[self.LEMMA] for t in self.data]@@ -74,7 +77,7 @@ class Tokens:"""Returns a list of named-entity-recognition tags of each token.Returns None if this annotation was not included."""- if 'ner' not in self.annotators:+ if "ner" not in self.annotators:return Nonereturn [t[self.NER] for t in self.data]@@ -95,14 +98,16 @@ class Tokens:return filter_fn(gram)words = self.words(uncased)- ngrams = [(s, e + 1)- for s in range(len(words))- for e in range(s, min(s + n, len(words)))- if not _skip(words[s:e + 1])]+ ngrams = [+ (s, e + 1)+ for s in range(len(words))+ for e in range(s, min(s + n, len(words)))+ if not _skip(words[s : e + 1])+ ]# Concatenate into stringsif as_strings:- ngrams = ['{}'.format(' '.join(words[s:e])) for (s, e) in ngrams]+ ngrams = ["{}".format(" ".join(words[s:e])) for (s, e) in ngrams]return ngrams@@ -111,7 +116,7 @@ class Tokens:entities = self.entities()if not entities:return None- non_ent = self.opts.get('non_ent', 'O')+ non_ent = self.opts.get("non_ent", "O")groups = []idx = 0while idx < len(entities):@@ -120,7 +125,7 @@ class Tokens:if ner_tag != non_ent:# Chomp the sequencestart = idx- while (idx < len(entities) and entities[idx] == ner_tag):+ while idx < len(entities) and entities[idx] == ner_tag:idx += 1groups.append((self.slice(start, idx).untokenize(), ner_tag))else:@@ -144,8 +149,8 @@ class Tokenizer:class SimpleTokenizer(Tokenizer):- ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+'- NON_WS = r'[^\p{Z}\p{C}]'+ ALPHA_NUM = r"[\p{L}\p{N}\p{M}]+"+ NON_WS = r"[^\p{Z}\p{C}]"def __init__(self, **kwargs):"""@@ -153,17 +158,20 @@ class SimpleTokenizer(Tokenizer):annotators: None or empty set (only tokenizes)."""self._regexp = regex.compile(- '(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS),+ "(%s)|(%s)" % (self.ALPHA_NUM, self.NON_WS), # noqa: UP031flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE,)- if len(kwargs.get('annotators', {})) > 0:- logger.warning('%s only tokenizes! Skipping annotators: %s' %- (type(self).__name__, kwargs.get('annotators')))+ if len(kwargs.get("annotators", {})) > 0:+ logger.warning(+ "%s only tokenizes! Skipping annotators: %s",+ type(self).__name__,+ kwargs.get("annotators"),+ )self.annotators = set()def tokenize(self, text):data = []- matches = [m for m in self._regexp.finditer(text)]+ matches = list(self._regexp.finditer(text))for i in range(len(matches)):# Get texttoken = matches[i].group()@@ -177,11 +185,13 @@ class SimpleTokenizer(Tokenizer):end_ws = span[1]# Format data- data.append((- token,- text[start_ws: end_ws],- span,- ))+ data.append(+ (+ token,+ text[start_ws:end_ws],+ span,+ )+ )return Tokens(data, self.annotators)@@ -190,7 +200,7 @@ def has_answer(tokenized_answers, text):for single_answer in tokenized_answers:for i in range(0, len(text) - len(single_answer) + 1):- if single_answer == text[i: i + len(single_answer)]:+ if single_answer == text[i : i + len(single_answer)]:return Truereturn False@@ -208,8 +218,8 @@ def locate_answers(tokenized_answers, text):for single_answer in answers_words:for i in range(0, len(text_words) - len(single_answer) + 1):- if single_answer == text_words[i: i + len(single_answer)]:- (offset, _), (_, endpos) = text_word_positions[i], text_word_positions[i+len(single_answer)-1]+ if single_answer == text_words[i : i + len(single_answer)]:+ (offset, _), (_, endpos) = text_word_positions[i], text_word_positions[i + len(single_answer) - 1]occurrences.append((offset, endpos))return occurrences@@ -218,11 +228,11 @@ def locate_answers(tokenized_answers, text):STokenizer = SimpleTokenizer()-def DPR_tokenize(text):- return STokenizer.tokenize(unicodedata.normalize('NFD', text))+def DPR_tokenize(text): # noqa: N802+ return STokenizer.tokenize(unicodedata.normalize("NFD", text))-def DPR_normalize(text):+def DPR_normalize(text): # noqa: N802return DPR_tokenize(text).words(uncased=True)@@ -232,8 +242,8 @@ def strip_accents(text):text = unicodedata.normalize("NFD", text)output = []for char in text:- cat = unicodedata.category(char)- if cat == "Mn":- continue- output.append(char)+ cat = unicodedata.category(char)+ if cat == "Mn":+ continue+ output.append(char)return "".join(output)diff --git a/dspy/dsp/utils/metrics.py b/dspy/dsp/utils/metrics.pyindex e3e41e984..9d3cc255d 100644--- a/dspy/dsp/utils/metrics.py+++ b/dspy/dsp/utils/metrics.py@@ -6,36 +6,36 @@ from collections import Counterfrom dspy.dsp.utils.utils import print_message-def EM(prediction, answers_list):+def EM(prediction, answers_list): # noqa: N802assert isinstance(answers_list, list)return max(em_score(prediction, ans) for ans in answers_list)-def F1(prediction, answers_list):+def F1(prediction, answers_list): # noqa: N802assert isinstance(answers_list, list)return max(f1_score(prediction, ans) for ans in answers_list)-def HotPotF1(prediction, answers_list):+def HotPotF1(prediction, answers_list): # noqa: N802assert isinstance(answers_list, list)return max(hotpot_f1_score(prediction, ans) for ans in answers_list)def normalize_text(s):- s = unicodedata.normalize('NFD', s)+ s = unicodedata.normalize("NFD", s)def remove_articles(text):- return re.sub(r'\b(a|an|the)\b', ' ', text)+ return re.sub(r"\b(a|an|the)\b", " ", text)def white_space_fix(text):- return ' '.join(text.split())+ return " ".join(text.split())def remove_punc(text):exclude = set(string.punctuation)- return ''.join(ch for ch in text if ch not in exclude)+ return "".join(ch for ch in text if ch not in exclude)def lower(text):return text.lower()@@ -51,6 +51,7 @@ def em_score(prediction, ground_truth):# See: https://rajpurkar.github.io/SQuAD-explorer/ under Evaluation Script# See: QReCC's+def f1_score(prediction, ground_truth):prediction_tokens = normalize_text(prediction).split()ground_truth_tokens = normalize_text(ground_truth).split()@@ -60,8 +61,7 @@ def f1_score(prediction, ground_truth):if len(prediction_tokens) == len(ground_truth_tokens) == 0:# Unlike most tasks, QReCC and SQuAD-2.0 assign 1.0 in this edge case. We don't for uniformity.- print_message(- "\n#> F1 Metric: Rare edge case of len(prediction_tokens) == len(ground_truth_tokens) == 0.\n")+ print_message("\n#> F1 Metric: Rare edge case of len(prediction_tokens) == len(ground_truth_tokens) == 0.\n")if num_same == 0:return 0@@ -77,9 +77,9 @@ def hotpot_f1_score(prediction, ground_truth):normalized_prediction = normalize_text(prediction)normalized_ground_truth = normalize_text(ground_truth)- if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:+ if normalized_prediction in ["yes", "no", "noanswer"] and normalized_prediction != normalized_ground_truth:return 0- if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:+ if normalized_ground_truth in ["yes", "no", "noanswer"] and normalized_prediction != normalized_ground_truth:return 0prediction_tokens = normalized_prediction.split()@@ -103,8 +103,7 @@ def precision_score(prediction, ground_truth):if len(prediction_tokens) == len(ground_truth_tokens) == 0:# Unlike most tasks, QReCC and SQuAD-2.0 assign 1.0 in this edge case. We don't for uniformity.- print_message(- "\n#> F1 Metric: Rare edge case of len(prediction_tokens) == len(ground_truth_tokens) == 0.\n")+ print_message("\n#> F1 Metric: Rare edge case of len(prediction_tokens) == len(ground_truth_tokens) == 0.\n")if num_same == 0:return 0diff --git a/dspy/dsp/utils/utils.py b/dspy/dsp/utils/utils.pyindex 4025dfa3f..178042e52 100644--- a/dspy/dsp/utils/utils.py+++ b/dspy/dsp/utils/utils.py@@ -1,11 +1,12 @@-import os-import tqdmimport copyimport datetimeimport itertools-+import osfrom collections import defaultdict+import tqdm++def print_message(*s, condition=True, pad=False, sep=None):s = " ".join([str(x) for x in s])msg = "[{}] {}".format(datetime.datetime.now().strftime("%b %d, %H:%M:%S"), s)@@ -27,7 +28,8 @@ def file_tqdm(file):print(f"#> Reading {file.name}")with tqdm.tqdm(- total=os.path.getsize(file.name) / 1024.0 / 1024.0, unit="MiB",+ total=os.path.getsize(file.name) / 1024.0 / 1024.0,+ unit="MiB",) as pbar:for line in file:yield line@@ -58,9 +60,9 @@ def deduplicate(seq: list[str]) -> list[str]:def batch(group, bsize, provide_offset=False):offset = 0while offset < len(group):- L = group[offset : offset + bsize]- yield ((offset, L) if provide_offset else L)- offset += len(L)+ batch_data = group[offset : offset + bsize]+ yield ((offset, batch_data) if provide_offset else batch_data)+ offset += len(batch_data)return@@ -75,9 +77,9 @@ def batch(group, bsize, provide_offset=False):# __delattr__ = dict.__delitem__-class dotdict(dict):+class dotdict(dict): # noqa: N801def __getattr__(self, key):- if key.startswith('__') and key.endswith('__'):+ if key.startswith("__") and key.endswith("__"):return super().__getattr__(key)try:return self[key]@@ -85,13 +87,13 @@ class dotdict(dict):raise AttributeError(f"'{type(self).__name__}' object has no attribute '{key}'")def __setattr__(self, key, value):- if key.startswith('__') and key.endswith('__'):+ if key.startswith("__") and key.endswith("__"):super().__setattr__(key, value)else:self[key] = valuedef __delattr__(self, key):- if key.startswith('__') and key.endswith('__'):+ if key.startswith("__") and key.endswith("__"):super().__delattr__(key)else:del self[key]@@ -101,49 +103,49 @@ class dotdict(dict):return dotdict(copy.deepcopy(dict(self), memo))-class dotdict_lax(dict):+class dotdict_lax(dict): # noqa: N801__getattr__ = dict.get__setattr__ = dict.__setitem____delattr__ = dict.__delitem__-def flatten(L):+def flatten(data_list):# return [x for y in L for x in y]result = []- for _list in L:- result += _list+ for child_list in data_list:+ result += child_listreturn result-def zipstar(L, lazy=False):+def zipstar(data_list, lazy=False):"""A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...])May return lists or tuples."""- if len(L) == 0:- return L+ if len(data_list) == 0:+ return data_list- width = len(L[0])+ width = len(data_list[0])if width < 100:- return [[elem[idx] for elem in L] for idx in range(width)]+ return [[elem[idx] for elem in data_list] for idx in range(width)]- L = zip(*L)+ zipped_data = zip(*data_list)- return L if lazy else list(L)+ return zipped_data if lazy else list(zipped_data)-def zip_first(L1, L2):- length = len(L1) if type(L1) in [tuple, list] else None+def zip_first(list1, list2):+ length = len(list1) if type(list1) in [tuple, list] else None- L3 = list(zip(L1, L2))+ zipped_data = list(zip(list1, list2))- assert length in [None, len(L3)], "zip_first() failure: length differs!"+ assert length in [None, len(zipped_data)], "zip_first() failure: length differs!"- return L3+ return zipped_datadef int_or_float(val):@@ -178,9 +180,7 @@ def process_grouped_by_first_item(lst):if started and first != last_group:yield (last_group, groups[last_group])- assert (- first not in groups- ), f"{first} seen earlier --- violates precondition."+ assert first not in groups, f"{first} seen earlier --- violates precondition."groups[first].append(rest)@@ -232,7 +232,7 @@ def load_batch_backgrounds(args, qids):for qid in qids:back = args.qid2backgrounds[qid]- if len(back) and type(back[0]) == int:+ if len(back) and isinstance(back[0], int):x = [args.collection[pid] for pid in back]else:x = [args.collectionX.get(pid, "") for pid in back]