Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

`cast` signature for KNN changed, now return Example instead of string, with the field `text_to_vectorize`. Small code formatting.

Igor Kotenkov28c78a5355b3
diff --git a/dsp/primitives/demonstrate.py b/dsp/primitives/demonstrate.py
index 2daebd61c..d8ea517d2 100644
--- a/dsp/primitives/demonstrate.py
+++ b/dsp/primitives/demonstrate.py
@@ -1,8 +1,11 @@
-import dsp
import random
-from typing import List, Callable
+from typing import Callable, List
+
import numpy as np
-from dsp.utils import dotdict, has_answer, DPR_normalize, normalize_text, EM, create_faiss_index
+
+import dsp
+from dsp.utils import (EM, DPR_normalize, create_faiss_index, dotdict,
+ has_answer, normalize_text)
class Example(dotdict):
@@ -13,9 +16,9 @@ class Example(dotdict):
if len(args):
assert len(args) == 1
self.update(args[0])
-
+
self.update(**kwargs)
-
+
def copy(self, **kwargs):
the_copy = Example(**{**dict(self), **kwargs})
@@ -39,15 +42,12 @@ class Example(dotdict):
# return self.get('question', self.get('query'))
-
-
-
def annotate(*transformations):
def do_augment(train, k=None, return_all=False):
rdemos = []
ademos = []
- for example in (train): # tqdm.tqdm
+ for example in (train): # tqdm.tqdm
raw_example = dsp.Example(example)
if k and len(ademos) >= k:
@@ -56,7 +56,7 @@ def annotate(*transformations):
for f in transformations:
if example is None:
break
-
+
example = f(example)
if example is not None:
@@ -65,16 +65,18 @@ def annotate(*transformations):
else:
raw_example.augmented = False
rdemos.append(raw_example)
-
+
if return_all:
return ademos + rdemos
return ademos
-
+
return do_augment
+
def sample(train, k: int):
- branch_idx = hasattr(dsp.settings, 'branch_idx') and isinstance(dsp.settings.branch_idx, int) and dsp.settings.branch_idx
+ branch_idx = hasattr(dsp.settings, 'branch_idx') and isinstance(
+ dsp.settings.branch_idx, int) and dsp.settings.branch_idx
branch_idx = branch_idx or 0
# print(f"branch_idx = {branch_idx}")
@@ -83,10 +85,11 @@ def sample(train, k: int):
rng.shuffle(shuffled_train)
subset = shuffled_train[:k]
- subset = [dsp.Example(x) for x in subset] # augmented=False
+ subset = [dsp.Example(x) for x in subset] # augmented=False
return subset
+
def all_but(train, x):
# output = [y for y in train if y.question != x.question]
@@ -102,26 +105,35 @@ def passage_match(passages, answers):
# answers = example.answers
return any(passage_has_answers(psg, answers) for psg in passages)
+
def answer_match(prediction, answers):
# pred = example.prediction
# answers = example.answers
return EM(prediction, answers)
+
def passage_has_answers(passage, answers):
return has_answer([DPR_normalize(normalize_text(ans)) for ans in answers], normalize_text(passage))
-def cast_naive_get_only_question_text(inp_example: Example) -> str:
- return inp_example.question
+def cast_naive_get_only_question_text(inp_example: Example) -> Example:
+ return inp_example.copy(text_to_vectorize=inp_example.question)
+
+
+def cast_naive_get_question_and_answer(inp_example: Example) -> Example:
+ text_to_vectorize = inp_example.question.strip() + " Answer: " + inp_example.answer.strip()
+ return inp_example.copy(text_to_vectorize=text_to_vectorize)
+
def vectorize_naive_get_field(inp_examples: List[Example]) -> np.ndarray:
embeddings = [cur_example.vectorized.reshape(1, -1) for cur_example in inp_examples]
embeddings = np.concatenate(embeddings, axis=0).astype(np.float32)
return embeddings
+
def knn(
train: List[Example],
- cast: Callable[[Example], str] = cast_naive_get_only_question_text,
+ cast: Callable[[Example], Example] = cast_naive_get_only_question_text,
vectorize: Callable[[List[Example]], np.ndarray] = vectorize_naive_get_field,
vectorize_train_bs: int = 128,
**knn_args
@@ -132,13 +144,13 @@ def knn(
all_vectors = np.empty((len(train), emb_dim), dtype=np.float32)
# batched vectorization for train Examples
for batch_idx in range(n_batches):
- batch_start_idx = batch_idx * vectorize_train_bs
+ batch_start_idx = batch_idx * vectorize_train_bs
batch_end_idx = (batch_idx + 1) * vectorize_train_bs
- cur_batch = train[batch_start_idx : batch_end_idx]
- # cur_batch = [cast(cur_elem) for cur_elem in cur_batch]
+ cur_batch = train[batch_start_idx: batch_end_idx]
+ cur_batch = [cast(cur_elem) for cur_elem in cur_batch]
cur_batch_vectors = vectorize(cur_batch)
all_vectors[batch_start_idx:batch_end_idx, :] = cur_batch_vectors
-
+
index = create_faiss_index(emb_dim=emb_dim, n_objects=len(train), **knn_args)
index.train(all_vectors)
index.add(all_vectors)
diff --git a/dsp/utils/ann_utils.py b/dsp/utils/ann_utils.py
index 2586b551e..89924b019 100644
--- a/dsp/utils/ann_utils.py
+++ b/dsp/utils/ann_utils.py
@@ -1,4 +1,4 @@
-from typing import Tuple, Optional
+from typing import Optional, Tuple
import faiss
import numpy as np
@@ -26,6 +26,7 @@ def _determine_devices(max_gpu_devices: int = 0) -> Tuple[int, bool]:
is_gpu = False
return num_devices, is_gpu
+
def _get_brute_index(emb_dim: int, dist_type: str) -> Index:
if dist_type.lower() == 'ip':
index = faiss.IndexFlatIP(emb_dim)
@@ -33,7 +34,7 @@ def _get_brute_index(emb_dim: int, dist_type: str) -> Index:
index = faiss.IndexFlatL2(emb_dim)
else:
raise ValueError(f'Wrong distance type for FAISS Flat Index: {dist_type}')
-
+
return index
@@ -86,7 +87,7 @@ def create_faiss_index(
Args:
emb_dim: size of each embedding
n_objects: size of a trainset for index. Used to determine optimal type
- of index and its settings (will use bruteforce if n_objects is less than 20_000).
+ of index and its settings (will use bruteforce if `n_objects` is less than 20_000).
n_probe: number of closest IVF-clusters to check for neighbours.
Doesn't affect bruteforce-based search.
max_gpu_devices: maximum amount of GPUs to use for ANN-index. 0 if run on CPU.
@@ -94,11 +95,11 @@ def create_faiss_index(
the difference between a vector and the reconstruction that can be
decoded from its representation in the index.
in_list_dist_type: type of distance to calculate simmilarities within one IVF.
- Can be IP (for inner product) or L2 distance. Case insensetive.
- If the index type is bruteforce (n_objects < 20_000), this variable will define
- the distane type for that bruteforce index.
+ Can be `IP` (for inner product) or `L2` distance. Case insensetive.
+ If the index type is bruteforce (`n_objects` < 20_000), this variable will define
+ the distane type for that bruteforce index. `centroid_dist_type` will be ignored.
centroid_dist_type: type of distance to calculate simmilarities between a query
- and cluster centroids. Can be IP (for inner product) or L2 distance.
+ and cluster centroids. Can be `IP` (for inner product) or `L2` distance.
Case insensetive.
Returns: untrained FAISS-index
"""
@@ -114,13 +115,13 @@ def create_faiss_index(
centroid_dist_type=centroid_dist_type,
encode_residuals=encode_residuals
)
-
+
index.nprobe = n_probe
num_devices, is_gpu = _determine_devices(max_gpu_devices)
if is_gpu:
cloner_options = faiss.GpuMultipleClonerOptions()
cloner_options.shard = True # split (not replicate) one index between GPUs
- index = faiss.index_cpu_to_gpus_list(index, cloner_options, range(num_devices))
+ index = faiss.index_cpu_to_gpus_list(index, cloner_options, list(range(num_devices)))
return index