flashrag-dev 0.1.3.dev20241117__tar.gz → 0.1.3.dev20241119__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. {flashrag-dev-0.1.3.dev20241117/flashrag_dev.egg-info → flashrag-dev-0.1.3.dev20241119}/PKG-INFO +1 -1
  2. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/dataset/dataset.py +5 -2
  3. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/dataset/utils.py +2 -0
  4. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/pipeline/active_pipeline.py +85 -48
  5. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/retriever.py +8 -3
  6. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/utils.py +17 -0
  7. flashrag-dev-0.1.3.dev20241119/flashrag/version.py +1 -0
  8. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119/flashrag_dev.egg-info}/PKG-INFO +1 -1
  9. flashrag-dev-0.1.3.dev20241117/flashrag/version.py +0 -1
  10. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/LICENSE +0 -0
  11. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/README.md +0 -0
  12. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/__init__.py +0 -0
  13. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/config/__init__.py +0 -0
  14. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/config/basic_config.yaml +0 -0
  15. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/config/config.py +0 -0
  16. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/dataset/__init__.py +0 -0
  17. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/evaluator/__init__.py +0 -0
  18. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/evaluator/_bleu.py +0 -0
  19. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/evaluator/evaluator.py +0 -0
  20. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/evaluator/metrics.py +0 -0
  21. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/evaluator/utils.py +0 -0
  22. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/generator/__init__.py +0 -0
  23. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/generator/fid.py +0 -0
  24. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/generator/generator.py +0 -0
  25. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/generator/openai_generator.py +0 -0
  26. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/generator/stop_word_criteria.py +0 -0
  27. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/generator/utils.py +0 -0
  28. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/judger/__init__.py +0 -0
  29. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/judger/judger.py +0 -0
  30. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/pipeline/__init__.py +0 -0
  31. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/pipeline/branching_pipeline.py +0 -0
  32. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/pipeline/pipeline.py +0 -0
  33. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/pipeline/replug_utils.py +0 -0
  34. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/prompt/__init__.py +0 -0
  35. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/prompt/base_prompt.py +0 -0
  36. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/prompt/selfask_examplars.py +0 -0
  37. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/prompt/trace_examplars.py +0 -0
  38. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/refiner/__init__.py +0 -0
  39. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/refiner/kg_refiner.py +0 -0
  40. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/refiner/llmlingua_compressor.py +0 -0
  41. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/refiner/refiner.py +0 -0
  42. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/refiner/selective_context_compressor.py +0 -0
  43. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/__init__.py +0 -0
  44. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/__main__.py +0 -0
  45. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/encoder.py +0 -0
  46. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/index_builder.py +0 -0
  47. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/retriever/reranker.py +0 -0
  48. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/utils/__init__.py +0 -0
  49. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/utils/constants.py +0 -0
  50. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/utils/pred_parse.py +0 -0
  51. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag/utils/utils.py +0 -0
  52. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag_dev.egg-info/SOURCES.txt +0 -0
  53. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag_dev.egg-info/dependency_links.txt +0 -0
  54. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag_dev.egg-info/requires.txt +0 -0
  55. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/flashrag_dev.egg-info/top_level.txt +0 -0
  56. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/pyproject.toml +0 -0
  57. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/setup.cfg +0 -0
  58. {flashrag-dev-0.1.3.dev20241117 → flashrag-dev-0.1.3.dev20241119}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: flashrag-dev
3
- Version: 0.1.3.dev20241117
3
+ Version: 0.1.3.dev20241119
4
4
  Summary: A library for efficient Retrieval-Augmented Generation research
5
5
  Home-page: https://github.com/RUC-NLPIR/FlashRAG
6
6
  Author: Jiajie Jin, Yutao Zhu, Chenghao Zhang, Xinyu Yang, Zhicheng Dou
@@ -174,9 +174,12 @@ class Dataset:
174
174
  """Save the dataset into the original format."""
175
175
 
176
176
  save_data = [item.to_dict() for item in self.data]
177
-
177
+ def custom_serializer(obj):
178
+ if isinstance(obj, np.float32):
179
+ return float(obj)
180
+ raise TypeError(f"Type {type(obj)} not serializable")
178
181
  with open(save_path, "w", encoding="utf-8") as f:
179
- json.dump(save_data, f, indent=4)
182
+ json.dump(save_data, f, indent=4, default=custom_serializer)
180
183
 
181
184
  def __str__(self) -> str:
182
185
  """Return a string representation of the dataset with a summary of items."""
@@ -13,6 +13,8 @@ def convert_numpy(obj: Union[Dict, list, np.ndarray, np.generic]) -> Any:
13
13
  return obj.tolist() # Convert numpy arrays to lists
14
14
  elif isinstance(obj, (np.integer, np.floating)):
15
15
  return obj.item() # Convert numpy scalars to native Python scalars
16
+ elif isinstance(obj, np.float32):
17
+ return float(obj)
16
18
  else:
17
19
  return obj # Return the object as-is if it's neither a dict, list, nor numpy type
18
20
 
@@ -898,12 +898,12 @@ class SelfAskPipeline(BasicPipeline):
898
898
  dataset = self.evaluate(dataset, do_eval=do_eval, pred_process_fun=pred_process_fun)
899
899
  return dataset
900
900
 
901
-
901
+
902
902
  class IRCOTPipeline(BasicPipeline):
903
903
  IRCOT_INSTRUCTION = 'You serve as an intelligent assistant, adept at facilitating users through complex, multi-hop reasoning across multiple documents. This task is illustrated through demonstrations, each consisting of a document set paired with a relevant question and its multi-hop reasoning thoughts. Your task is to generate one thought for current step, DON\'T generate the whole thoughts at once! If you reach what you believe to be the final step, start with "So the answer is:".'
904
904
  IRCOT_EXAMPLE = "Wikipedia Title: Kurram Garhi\nKurram Garhi is a small village located near the city of Bannu, which is the part of Khyber Pakhtunkhwa province of Pakistan. Its population is approximately 35000. Barren hills are near this village. This village is on the border of Kurram Agency. Other nearby villages are Peppal, Surwangi and Amandi Kala.\n\nWikipedia Title: 2001–02 UEFA Champions League second group stage\nEight winners and eight runners- up from the first group stage were drawn into four groups of four teams, each containing two group winners and two runners- up. Teams from the same country or from the same first round group could not be drawn together. The top two teams in each group advanced to the quarter- finals.\n\nWikipedia Title: Satellite tournament\nA satellite tournament is either a minor tournament or event on a competitive sporting tour or one of a group of such tournaments that form a series played in the same country or region.\n\nWikipedia Title: Trojkrsti\nTrojkrsti is a village in Municipality of Prilep, Republic of Macedonia.\n\nWikipedia Title: Telephone numbers in Ascension Island\nCountry Code:+ 247< br> International Call Prefix: 00 Ascension Island does not share the same country code( +290) with the rest of St Helena.\n\nQuestion: Are both Kurram Garhi and Trojkrsti located in the same country?\nThought: Kurram Garhi is located in the country of Pakistan. Trojkrsti is located in the country of Republic of Macedonia. Thus, they are not in the same country. So the answer is: no.\n\n"
905
905
 
906
- def __init__(self, config, prompt_template=None, retriever=None, generator=None, max_iter=2):
906
+ def __init__(self, config, prompt_template=None, retriever=None, generator=None, max_iter=5):
907
907
  # if not provide prompt template, use default template provided by IRCOT
908
908
  if prompt_template is None:
909
909
  prompt_template = PromptTemplate(
@@ -920,60 +920,97 @@ class IRCOTPipeline(BasicPipeline):
920
920
 
921
921
  self.max_iter = max_iter
922
922
 
923
- def run_item(self, item):
924
- question = item.question
925
- retrieval_result, scores = self.retriever.search(question, return_score=True)
926
- doc2score = {doc_item["id"]: score for doc_item, score in zip(retrieval_result, scores)}
927
- id2doc = {doc_item["id"]: doc_item for doc_item in retrieval_result}
928
-
929
- thoughts = []
923
+ def run_batch(self, items):
924
+ # Initialize the necessary data structures
925
+ batch_thoughts = {item_id: [] for item_id in range(len(items))}
930
926
  iter_num = 0
927
+ batch_retrieval_results = []
928
+ doc2score_batch = []
929
+ id2doc_batch = []
930
+
931
+ # Initial retrieval for all items in the batch
932
+ questions = [item.question for item in items]
933
+ retrieval_results, scoress = self.retriever.batch_search(questions, return_score=True)
934
+ for retrieval_result, scores in zip(retrieval_results,scoress):
935
+
936
+ doc2score = {doc_item['id']: score for doc_item, score in zip(retrieval_result, scores)}
937
+ id2doc = {doc_item['id']: doc_item for doc_item in retrieval_result}
938
+ batch_retrieval_results.append(retrieval_result)
939
+ doc2score_batch.append(doc2score)
940
+ id2doc_batch.append(id2doc)
941
+
942
+ # Start the iterative process
943
+ active_item_ids = list(range(len(items))) # Track items that need more iterations
931
944
  while iter_num < self.max_iter:
932
- input_prompt = self.prompt_template.get_string(
933
- question=question, retrieval_result=retrieval_result, previous_gen=" ".join(thoughts)
934
- )
935
- new_thought = self.generator.generate(input_prompt,stop=['.', '\n'])[0]
936
- thoughts.append(new_thought)
937
- iter_num += 1
938
- if "So the answer is:" in new_thought:
939
- item.update_output(
940
- f"intermediate_output_iter{iter_num}",
941
- {
942
- "input_prompt": input_prompt,
943
- "new_thought": new_thought,
944
- },
945
+ # Generate prompts and new thoughts for the active items
946
+ input_prompts = [
947
+ self.prompt_template.get_string(
948
+ question=items[item_id].question,
949
+ retrieval_result=batch_retrieval_results[item_id],
950
+ previous_gen=' '.join(batch_thoughts[item_id])
945
951
  )
946
- break
952
+ for item_id in active_item_ids
953
+ ]
947
954
 
948
- # retrieve new docs and merge
949
- new_retrieval_result, new_scores = self.retriever.search(new_thought, return_score=True)
950
- for doc_item, score in zip(new_retrieval_result, new_scores):
951
- id2doc[doc_item["id"]] = doc_item
952
- doc_id = doc_item["id"]
953
- if doc_id in doc2score:
954
- doc2score[doc_id] = max(doc2score[doc_id], score)
955
+ # Batch generation for active items
956
+ new_thoughts_batch = self.generator.generate(input_prompts, stop=['.', '\n'])
957
+
958
+ # Update thoughts and determine next active items
959
+ new_active_item_ids = []
960
+ for idx, item_id in enumerate(active_item_ids):
961
+ new_thought = new_thoughts_batch[idx]
962
+ batch_thoughts[item_id].append(new_thought)
963
+
964
+ # Check for termination condition
965
+ # Store intermediate outputs
966
+ if "So the answer is:" in new_thought:
967
+ items[item_id].update_output(
968
+ f'intermediate_output_iter{iter_num}',
969
+ {
970
+ 'input_prompt': input_prompts[idx],
971
+ 'new_thought': new_thought,
972
+ },
973
+ )
955
974
  else:
956
- doc2score[doc_id] = score
957
- sorted_doc_score = sorted(doc2score.items(), key=lambda x: x[1], reverse=False)
958
- sorted_doc_id = [t[0] for t in sorted_doc_score]
959
- retrieval_result = [id2doc[id] for id in sorted_doc_id]
960
-
961
- item.update_output(
962
- f"intermediate_output_iter{iter_num}",
963
- {
964
- "input_prompt": input_prompt,
965
- "new_thought": new_thought,
966
- "new_retreival_result": new_retrieval_result,
967
- },
968
- )
975
+ new_active_item_ids.append(item_id)
976
+
977
+ # Update active item IDs for the next iteration
978
+ active_item_ids = new_active_item_ids
979
+
980
+ # Perform batch retrieval for new thoughts of active items
981
+ if active_item_ids:
982
+ print(len(active_item_ids))
983
+ print(active_item_ids)
984
+ new_thoughts_for_retrieval = [batch_thoughts[item_id][-1] for item_id in active_item_ids]
985
+ new_retrieval_results, new_scoress = self.retriever.batch_search(new_thoughts_for_retrieval, return_score=True)
986
+
987
+ for i, item_id in enumerate(active_item_ids):
988
+ new_retrieval_result, new_scores = new_retrieval_results[i],new_scoress[i]
989
+
990
+ # Update doc2score and id2doc for the current item
991
+ for doc_item, score in zip(new_retrieval_result, new_scores):
992
+ doc_id = doc_item['id']
993
+ id2doc_batch[item_id][doc_id] = doc_item
994
+ if doc_id in doc2score_batch[item_id]:
995
+ doc2score_batch[item_id][doc_id] = max(doc2score_batch[item_id][doc_id], score)
996
+ else:
997
+ doc2score_batch[item_id][doc_id] = score
969
998
 
970
- item.update_output("retrieval_result", retrieval_result)
971
- item.update_output("pred", " ".join(thoughts))
972
- return item
999
+ # Sort and update retrieval results
1000
+ sorted_doc_score = sorted(doc2score_batch[item_id].items(), key=lambda x: x[1], reverse=False)
1001
+ sorted_doc_id = [t[0] for t in sorted_doc_score]
1002
+ batch_retrieval_results[item_id] = [id2doc_batch[item_id][id] for id in sorted_doc_id]
1003
+
1004
+ iter_num += 1
1005
+
1006
+ # Final update for each item in the batch
1007
+ for item_id, item in enumerate(items):
1008
+ item.update_output('retrieval_result', batch_retrieval_results[item_id])
1009
+ item.update_output('pred', ' '.join(batch_thoughts[item_id]))
973
1010
 
974
1011
  def run(self, dataset, do_eval=True, pred_process_fun=ircot_pred_parse):
975
- for item in tqdm(dataset, desc="Inference: "):
976
- self.run_item(item)
1012
+
1013
+ self.run_batch(dataset)
977
1014
 
978
1015
  dataset = self.evaluate(dataset, do_eval=do_eval, pred_process_fun=pred_process_fun)
979
1016
  return dataset
@@ -7,9 +7,9 @@ from typing import List, Dict
7
7
  import functools
8
8
  from tqdm import tqdm
9
9
  import faiss
10
-
10
+ import numpy as np
11
11
  from flashrag.utils import get_reranker
12
- from flashrag.retriever.utils import load_corpus, load_docs
12
+ from flashrag.retriever.utils import load_corpus, load_docs, convert_numpy
13
13
  from flashrag.retriever.encoder import Encoder, STEncoder
14
14
 
15
15
 
@@ -136,8 +136,13 @@ class BaseRetriever:
136
136
  self.cache = json.load(f)
137
137
 
138
138
  def _save_cache(self):
139
+ self.cache = convert_numpy(self.cache)
140
+ def custom_serializer(obj):
141
+ if isinstance(obj, np.float32):
142
+ return float(obj)
143
+ raise TypeError(f"Type {type(obj)} not serializable")
139
144
  with open(self.cache_save_path, "w") as f:
140
- json.dump(self.cache, f, indent=4)
145
+ json.dump(self.cache, f, indent=4, default=custom_serializer)
141
146
 
142
147
  def _search(self, query: str, num: int, return_score: bool) -> List[Dict[str, str]]:
143
148
  r"""Retrieve topk relevant documents in corpus.
@@ -1,8 +1,25 @@
1
1
  import json
2
2
  import warnings
3
+ from typing import Dict, Any, Union, List, Dict
4
+ import numpy as np
3
5
  import datasets
4
6
  from transformers import AutoTokenizer, AutoModel, AutoConfig
5
7
 
8
+ def convert_numpy(obj: Union[Dict, list, np.ndarray, np.generic]) -> Any:
9
+ """Recursively convert numpy objects in nested dictionaries or lists to native Python types."""
10
+ if isinstance(obj, dict):
11
+ return {k: convert_numpy(v) for k, v in obj.items()}
12
+ elif isinstance(obj, list):
13
+ return [convert_numpy(i) for i in obj]
14
+ elif isinstance(obj, np.ndarray):
15
+ return obj.tolist() # Convert numpy arrays to lists
16
+ elif isinstance(obj, (np.integer, np.floating)):
17
+ return obj.item() # Convert numpy scalars to native Python scalars
18
+ elif isinstance(obj, np.float32):
19
+ return float(obj)
20
+ else:
21
+ return obj # Return the object as-is if it's neither a dict, list, nor numpy type
22
+
6
23
 
7
24
  def load_model(model_path: str, use_fp16: bool = False):
8
25
  model_config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
@@ -0,0 +1 @@
1
+ __version__ = "0.1.3dev20241119"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: flashrag-dev
3
- Version: 0.1.3.dev20241117
3
+ Version: 0.1.3.dev20241119
4
4
  Summary: A library for efficient Retrieval-Augmented Generation research
5
5
  Home-page: https://github.com/RUC-NLPIR/FlashRAG
6
6
  Author: Jiajie Jin, Yutao Zhu, Chenghao Zhang, Xinyu Yang, Zhicheng Dou
@@ -1 +0,0 @@
1
- __version__ = "0.1.3dev20241117"