flashrag-dev 0.1.4.dev20241203__tar.gz → 0.1.4.dev20241210__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.
- {flashrag-dev-0.1.4.dev20241203/flashrag_dev.egg-info → flashrag-dev-0.1.4.dev20241210}/PKG-INFO +1 -1
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/config/config.py +12 -5
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/generator.py +42 -37
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/__init__.py +1 -1
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/active_pipeline.py +219 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/base_prompt.py +3 -1
- flashrag-dev-0.1.4.dev20241210/flashrag/version.py +1 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210/flashrag_dev.egg-info}/PKG-INFO +1 -1
- flashrag-dev-0.1.4.dev20241203/flashrag/version.py +0 -1
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/LICENSE +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/README.md +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/config/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/config/basic_config.yaml +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/dataset/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/dataset/dataset.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/dataset/utils.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/_bleu.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/evaluator.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/metrics.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/utils.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/fid.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/openai_generator.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/stop_word_criteria.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/utils.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/judger/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/judger/judger.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/branching_pipeline.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/pipeline.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/replug_utils.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/selfask_examplars.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/trace_examplars.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/kg_refiner.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/llmlingua_compressor.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/refiner.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/selective_context_compressor.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/__main__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/encoder.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/index_builder.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/reranker.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/retriever.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/utils.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/__init__.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/constants.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/pred_parse.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/utils.py +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag_dev.egg-info/SOURCES.txt +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag_dev.egg-info/dependency_links.txt +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag_dev.egg-info/requires.txt +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag_dev.egg-info/top_level.txt +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/pyproject.toml +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/setup.cfg +0 -0
- {flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/setup.py +0 -0
{flashrag-dev-0.1.4.dev20241203/flashrag_dev.egg-info → flashrag-dev-0.1.4.dev20241210}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: flashrag-dev
|
|
3
|
-
Version: 0.1.4.
|
|
3
|
+
Version: 0.1.4.dev20241210
|
|
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,5 +1,6 @@
|
|
|
1
1
|
import re
|
|
2
2
|
import os
|
|
3
|
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
3
4
|
import yaml
|
|
4
5
|
import random
|
|
5
6
|
import datetime
|
|
@@ -102,13 +103,19 @@ class Config:
|
|
|
102
103
|
gpu_id = self.final_config["gpu_id"]
|
|
103
104
|
if gpu_id is not None:
|
|
104
105
|
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
|
|
106
|
+
try:
|
|
107
|
+
# import pynvml
|
|
108
|
+
# pynvml.nvmlInit()
|
|
109
|
+
# gpu_num = pynvml.nvmlDeviceGetCount()
|
|
105
110
|
import torch
|
|
106
|
-
|
|
107
|
-
|
|
111
|
+
gpu_num = torch.cuda.device_count()
|
|
112
|
+
except:
|
|
113
|
+
gpu_num = 0
|
|
114
|
+
self.final_config['gpu_num'] = gpu_num
|
|
115
|
+
if gpu_num > 0:
|
|
116
|
+
self.final_config["device"] = "cuda"
|
|
108
117
|
else:
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
self.final_config["device"] = torch.device("cpu")
|
|
118
|
+
self.final_config['device'] = 'cpu'
|
|
112
119
|
|
|
113
120
|
def _set_additional_key(self):
|
|
114
121
|
# set dataset
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/generator.py
RENAMED
|
@@ -4,7 +4,6 @@ import warnings
|
|
|
4
4
|
from tqdm import tqdm
|
|
5
5
|
from tqdm.auto import trange
|
|
6
6
|
import numpy as np
|
|
7
|
-
import torch
|
|
8
7
|
from transformers import (
|
|
9
8
|
AutoTokenizer,
|
|
10
9
|
AutoModelForCausalLM,
|
|
@@ -25,7 +24,7 @@ class BaseGenerator:
|
|
|
25
24
|
self.max_input_len = config["generator_max_input_len"]
|
|
26
25
|
self.batch_size = config["generator_batch_size"]
|
|
27
26
|
self.device = config["device"]
|
|
28
|
-
self.gpu_num =
|
|
27
|
+
self.gpu_num = config['gpu_num']
|
|
29
28
|
self.config = config
|
|
30
29
|
self.generation_params = config["generation_params"]
|
|
31
30
|
|
|
@@ -64,6 +63,7 @@ class EncoderDecoderGenerator(BaseGenerator):
|
|
|
64
63
|
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
|
|
65
64
|
|
|
66
65
|
def encode_passages(self, batch_text_passages: List[List[str]]):
|
|
66
|
+
import torch
|
|
67
67
|
# need size: [batch_size, passage_num, passage_len]
|
|
68
68
|
passage_ids, passage_masks = [], []
|
|
69
69
|
for text_passages in batch_text_passages:
|
|
@@ -81,7 +81,6 @@ class EncoderDecoderGenerator(BaseGenerator):
|
|
|
81
81
|
passage_masks = torch.cat(passage_masks, dim=0)
|
|
82
82
|
return passage_ids, passage_masks.bool()
|
|
83
83
|
|
|
84
|
-
@torch.inference_mode(mode=True)
|
|
85
84
|
def generate(self, input_list: List, batch_size=None, **params):
|
|
86
85
|
if isinstance(input_list, str):
|
|
87
86
|
input_list = [input_list]
|
|
@@ -128,15 +127,17 @@ class EncoderDecoderGenerator(BaseGenerator):
|
|
|
128
127
|
).to(self.device)
|
|
129
128
|
|
|
130
129
|
# TODO: multi-gpu inference
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
130
|
+
import torch
|
|
131
|
+
with torch.inference_mode():
|
|
132
|
+
if self.fid:
|
|
133
|
+
if 'max_new_tokens' in generation_params:
|
|
134
|
+
max_new_tokens = generation_params.pop('max_new_tokens')
|
|
135
|
+
else:
|
|
136
|
+
max_new_tokens = 32
|
|
137
|
+
|
|
138
|
+
outputs = self.model.generate(**inputs, max_new_tokens=max_new_tokens, pad_token_id=self.tokenizer.pad_token_id, decoder_start_token_id=self.tokenizer.pad_token_id)
|
|
134
139
|
else:
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
outputs = self.model.generate(**inputs, max_new_tokens=max_new_tokens, pad_token_id=self.tokenizer.pad_token_id, decoder_start_token_id=self.tokenizer.pad_token_id)
|
|
138
|
-
else:
|
|
139
|
-
outputs = self.model.generate(**inputs, **generation_params)
|
|
140
|
+
outputs = self.model.generate(**inputs, **generation_params)
|
|
140
141
|
outputs = self.tokenizer.batch_decode(
|
|
141
142
|
outputs,
|
|
142
143
|
skip_special_tokens=True,
|
|
@@ -153,9 +154,8 @@ class VLLMGenerator(BaseGenerator):
|
|
|
153
154
|
|
|
154
155
|
def __init__(self, config):
|
|
155
156
|
super().__init__(config)
|
|
156
|
-
|
|
157
|
+
|
|
157
158
|
from vllm import LLM
|
|
158
|
-
|
|
159
159
|
if "gpu_memory_utilization" not in config:
|
|
160
160
|
gpu_memory_utilization = 0.85
|
|
161
161
|
else:
|
|
@@ -187,7 +187,6 @@ class VLLMGenerator(BaseGenerator):
|
|
|
187
187
|
)
|
|
188
188
|
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path, trust_remote_code=True)
|
|
189
189
|
|
|
190
|
-
@torch.inference_mode(mode=True)
|
|
191
190
|
def generate(
|
|
192
191
|
self,
|
|
193
192
|
input_list: List[str],
|
|
@@ -283,6 +282,7 @@ class HFCausalLMGenerator(BaseGenerator):
|
|
|
283
282
|
return model, tokenizer
|
|
284
283
|
|
|
285
284
|
def add_new_tokens(self, token_embedding_path, token_name_func=lambda idx: f"[ref{idx+1}]"):
|
|
285
|
+
import torch
|
|
286
286
|
del self.model
|
|
287
287
|
self.model = AutoModelForCausalLM.from_pretrained(
|
|
288
288
|
self.model_path,
|
|
@@ -318,7 +318,6 @@ class HFCausalLMGenerator(BaseGenerator):
|
|
|
318
318
|
self.model.eval()
|
|
319
319
|
self.model.cuda()
|
|
320
320
|
|
|
321
|
-
@torch.inference_mode(mode=True)
|
|
322
321
|
def generate(
|
|
323
322
|
self,
|
|
324
323
|
input_list: List[str],
|
|
@@ -370,28 +369,30 @@ class HFCausalLMGenerator(BaseGenerator):
|
|
|
370
369
|
generated_token_ids = []
|
|
371
370
|
generated_token_logits = []
|
|
372
371
|
|
|
372
|
+
import torch
|
|
373
373
|
for idx in trange(0, len(input_list), batch_size, desc="Generation process: "):
|
|
374
|
-
torch.
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
374
|
+
with torch.inference_mode():
|
|
375
|
+
torch.cuda.empty_cache()
|
|
376
|
+
batched_prompts = input_list[idx : idx + batch_size]
|
|
377
|
+
inputs = self.tokenizer(
|
|
378
|
+
batched_prompts,
|
|
379
|
+
return_tensors="pt",
|
|
380
|
+
padding=True,
|
|
381
|
+
truncation=True,
|
|
382
|
+
max_length=self.max_input_len,
|
|
383
|
+
).to(self.model.device)
|
|
384
|
+
outputs = self.model.generate(
|
|
385
|
+
**inputs,
|
|
386
|
+
output_scores=True,
|
|
387
|
+
return_dict_in_generate=True,
|
|
388
|
+
**generation_params,
|
|
389
|
+
)
|
|
389
390
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
391
|
+
generated_ids = outputs.sequences
|
|
392
|
+
logits = torch.stack(outputs.scores, dim=1).softmax(-1)
|
|
393
|
+
generated_ids = generated_ids[:, inputs["input_ids"].shape[-1] :]
|
|
394
|
+
gen_score = torch.gather(logits, 2, generated_ids[:, :, None]).squeeze(-1).cpu().tolist()
|
|
395
|
+
scores.extend(gen_score)
|
|
395
396
|
|
|
396
397
|
# get additinoal info
|
|
397
398
|
if return_dict:
|
|
@@ -477,13 +478,14 @@ class HFCausalLMGenerator(BaseGenerator):
|
|
|
477
478
|
else:
|
|
478
479
|
return responses
|
|
479
480
|
|
|
480
|
-
|
|
481
|
+
|
|
481
482
|
def cal_gen_probs(self, prev, next):
|
|
483
|
+
import torch
|
|
482
484
|
input_ids = self.tokenizer.encode(prev, add_special_tokens=False)
|
|
483
485
|
target_ids = self.tokenizer.encode(next, add_special_tokens=False)
|
|
484
486
|
context_ids = input_ids + target_ids
|
|
485
487
|
context_tensor = torch.tensor([context_ids]).to(self.device)
|
|
486
|
-
with torch.
|
|
488
|
+
with torch.inference_mode():
|
|
487
489
|
outputs = self.model(context_tensor)
|
|
488
490
|
logits = outputs.logits
|
|
489
491
|
logits = logits[0, len(input_ids) - 1 : len(context_ids) - 1, :]
|
|
@@ -505,6 +507,7 @@ class FastChatGenerator(HFCausalLMGenerator):
|
|
|
505
507
|
|
|
506
508
|
def get_gpu_memory(max_gpus=None):
|
|
507
509
|
"""Get available memory for each GPU."""
|
|
510
|
+
import torch
|
|
508
511
|
gpu_memory = []
|
|
509
512
|
num_gpus = torch.cuda.device_count() if max_gpus is None else min(max_gpus, torch.cuda.device_count())
|
|
510
513
|
for gpu_id in range(num_gpus):
|
|
@@ -525,6 +528,8 @@ class FastChatGenerator(HFCausalLMGenerator):
|
|
|
525
528
|
else:
|
|
526
529
|
gpu_memory_utilization = self.config["gpu_memory_utilization"]
|
|
527
530
|
max_gpu_memory = None
|
|
531
|
+
import torch
|
|
532
|
+
self.gpu_num = torch.cuda.device_count()
|
|
528
533
|
if self.gpu_num != 1:
|
|
529
534
|
available_gpu_memory = get_gpu_memory(self.gpu_num)
|
|
530
535
|
max_gpu_memory = str(int(min(available_gpu_memory) * gpu_memory_utilization)) + "GiB"
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/__init__.py
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
from flashrag.pipeline.pipeline import *
|
|
2
2
|
from flashrag.pipeline.branching_pipeline import REPLUGPipeline, SuRePipeline
|
|
3
|
-
from flashrag.pipeline.active_pipeline import IterativePipeline, SelfRAGPipeline, FLAREPipeline, SelfAskPipeline, IRCOTPipeline
|
|
3
|
+
from flashrag.pipeline.active_pipeline import IterativePipeline, SelfRAGPipeline, FLAREPipeline, SelfAskPipeline, IRCOTPipeline, RQRAGPipeline
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import re
|
|
2
2
|
from tqdm import tqdm
|
|
3
|
+
from typing import List, Tuple
|
|
4
|
+
import math
|
|
3
5
|
import numpy as np
|
|
4
6
|
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
|
|
5
7
|
from flashrag.utils import get_retriever, get_generator, selfask_pred_parse, ircot_pred_parse
|
|
@@ -1014,3 +1016,220 @@ class IRCOTPipeline(BasicPipeline):
|
|
|
1014
1016
|
|
|
1015
1017
|
dataset = self.evaluate(dataset, do_eval=do_eval, pred_process_fun=pred_process_fun)
|
|
1016
1018
|
return dataset
|
|
1019
|
+
|
|
1020
|
+
class RQRAGPipeline(BasicPipeline):
|
|
1021
|
+
expand_on_tokens = [
|
|
1022
|
+
"[S_Rewritten_Query]",
|
|
1023
|
+
"[S_Decomposed_Query]",
|
|
1024
|
+
"[S_Disambiguated_Query]",
|
|
1025
|
+
"[A_Response]"
|
|
1026
|
+
]
|
|
1027
|
+
|
|
1028
|
+
system_prompt = {
|
|
1029
|
+
"qa": "Given a question that requires multi-hop reasoning, you need to decompose the question and answer based on the given context. Please provide a short and concise response."
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
response_generation_params = {
|
|
1033
|
+
"temperature": 0,
|
|
1034
|
+
"top_p": 0.9,
|
|
1035
|
+
"stop": ["[EOS]", "</s>"],
|
|
1036
|
+
"skip_special_tokens": False,
|
|
1037
|
+
"include_stop_str_in_output": True,
|
|
1038
|
+
"logprobs": 1,
|
|
1039
|
+
"spaces_between_special_tokens": False,
|
|
1040
|
+
"max_tokens": 4096
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
other_generation_params = {
|
|
1044
|
+
"temperature": 1,
|
|
1045
|
+
"top_p": 0.9,
|
|
1046
|
+
"stop": ["[EOS]", "</s>"],
|
|
1047
|
+
"skip_special_tokens": False,
|
|
1048
|
+
"include_stop_str_in_output": True,
|
|
1049
|
+
"logprobs": 1,
|
|
1050
|
+
"spaces_between_special_tokens": False,
|
|
1051
|
+
"max_tokens": 4096
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
def __init__(
|
|
1055
|
+
self,
|
|
1056
|
+
config: dict,
|
|
1057
|
+
prompt_template = None,
|
|
1058
|
+
retriever = None,
|
|
1059
|
+
generator = None,
|
|
1060
|
+
max_depth = 3,
|
|
1061
|
+
batch_size = 32
|
|
1062
|
+
):
|
|
1063
|
+
super().__init__(config, prompt_template)
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
self.generator = generator if generator is not None else get_generator(config)
|
|
1067
|
+
self.tokenizer = AutoTokenizer.from_pretrained(config["generator_model_path"], padding_side = "left")
|
|
1068
|
+
self.retriever = retriever if retriever is not None else get_retriever(config)
|
|
1069
|
+
|
|
1070
|
+
self.max_depth = max_depth
|
|
1071
|
+
self.batch_size = batch_size
|
|
1072
|
+
|
|
1073
|
+
# Due to the low effiency of original method, it only supports vllm now.
|
|
1074
|
+
|
|
1075
|
+
def preprocess_eval_data(self, items: List) -> List[str]:
|
|
1076
|
+
eval_examples = []
|
|
1077
|
+
|
|
1078
|
+
for item in items:
|
|
1079
|
+
eval_example = f"<s><|system|>\n{self.system_prompt['qa']}" + self.tokenizer.eos_token + "\n<|user|>\n" + item.question + self.tokenizer.eos_token + "\n"
|
|
1080
|
+
eval_example += "<|assistant|>\n"
|
|
1081
|
+
eval_examples.append(eval_example)
|
|
1082
|
+
|
|
1083
|
+
return eval_examples
|
|
1084
|
+
|
|
1085
|
+
def format_evidences(self, evidences: List[str]):
|
|
1086
|
+
format_evidence = ""
|
|
1087
|
+
for evidence in evidences:
|
|
1088
|
+
title = evidence['contents'].split('\n')[0]
|
|
1089
|
+
text = "\n".join(evidence['contents'].split('\n')[1:])
|
|
1090
|
+
format_evidence += f"Title: {title}\n"
|
|
1091
|
+
format_evidence += f"Text: {text}\n"
|
|
1092
|
+
return format_evidence
|
|
1093
|
+
|
|
1094
|
+
def generate_tree_of_thoughts_batch(self, initial_prompts_batch: List[str]):
|
|
1095
|
+
paths_batch_dict = {
|
|
1096
|
+
idx: [{
|
|
1097
|
+
"prompt": initial_prompt,
|
|
1098
|
+
"depth": 0,
|
|
1099
|
+
"done": False
|
|
1100
|
+
}]
|
|
1101
|
+
for idx, initial_prompt in enumerate(initial_prompts_batch)
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
final_outputs_batch = {idx: [] for idx in range(len(initial_prompts_batch))}
|
|
1105
|
+
|
|
1106
|
+
while any(paths for paths in paths_batch_dict.values()):
|
|
1107
|
+
current_batch = []
|
|
1108
|
+
for i, _ in paths_batch_dict.items():
|
|
1109
|
+
if paths_batch_dict[i]:
|
|
1110
|
+
current_path = paths_batch_dict[i].pop(0)
|
|
1111
|
+
current_batch.append(current_path)
|
|
1112
|
+
else:
|
|
1113
|
+
continue
|
|
1114
|
+
|
|
1115
|
+
if not current_batch:
|
|
1116
|
+
break
|
|
1117
|
+
|
|
1118
|
+
for special_token in self.expand_on_tokens:
|
|
1119
|
+
|
|
1120
|
+
if current_batch[0]["depth"] >= self.max_depth and special_token != "[A_Response]":
|
|
1121
|
+
continue
|
|
1122
|
+
|
|
1123
|
+
# Prepare for inputs
|
|
1124
|
+
input_texts = [path["prompt"] + special_token for path in current_batch]
|
|
1125
|
+
|
|
1126
|
+
# Generate outputs
|
|
1127
|
+
if special_token != "[A_Response]":
|
|
1128
|
+
init_outputs = self.generator.generate(
|
|
1129
|
+
input_list = input_texts,
|
|
1130
|
+
return_raw_output = True,
|
|
1131
|
+
**self.response_generation_params
|
|
1132
|
+
)
|
|
1133
|
+
else:
|
|
1134
|
+
init_outputs = self.generator.generate(
|
|
1135
|
+
input_list = input_texts,
|
|
1136
|
+
return_raw_output = True,
|
|
1137
|
+
**self.other_generation_params
|
|
1138
|
+
)
|
|
1139
|
+
|
|
1140
|
+
# Decode outputs
|
|
1141
|
+
decoded_outputs = [output.outputs[0].text for output in init_outputs]
|
|
1142
|
+
# Initialize lists to collect queries for batch retrieval
|
|
1143
|
+
queries_for_search = []
|
|
1144
|
+
|
|
1145
|
+
# Process outputs and prepare for retrieval
|
|
1146
|
+
for i, decoded_output in enumerate(decoded_outputs):
|
|
1147
|
+
current_path = current_batch[i]
|
|
1148
|
+
decoded_output = decoded_output.replace("<s> ", "<s>")
|
|
1149
|
+
|
|
1150
|
+
if special_token == "[A_Response]":
|
|
1151
|
+
pattern = r"(.*?)\[EOS\]"
|
|
1152
|
+
matches = re.findall(pattern, decoded_output, re.DOTALL)
|
|
1153
|
+
result = matches[-1].strip() if matches else "Unable to detect valid answer"
|
|
1154
|
+
token_ids = init_outputs[i].outputs[0].token_ids[1:-1]
|
|
1155
|
+
logprobs = init_outputs[i].outputs[0].logprobs[1:-1]
|
|
1156
|
+
confidence = 0
|
|
1157
|
+
for token_id, logprobs in zip(token_ids, logprobs):
|
|
1158
|
+
logprob = logprobs[token_id].logprob
|
|
1159
|
+
prob = math.exp(logprob)
|
|
1160
|
+
confidence += prob
|
|
1161
|
+
|
|
1162
|
+
if len(token_ids) > 0:
|
|
1163
|
+
confidence /= len(token_ids)
|
|
1164
|
+
|
|
1165
|
+
new_path = {
|
|
1166
|
+
"prompt": input_texts[i] + decoded_output,
|
|
1167
|
+
"depth": current_path["depth"] + 1,
|
|
1168
|
+
"done": True,
|
|
1169
|
+
"final_answer": result,
|
|
1170
|
+
"confidence": confidence
|
|
1171
|
+
}
|
|
1172
|
+
final_outputs_batch[i].append(new_path)
|
|
1173
|
+
else:
|
|
1174
|
+
# Extract the query
|
|
1175
|
+
pattern = r"(.*?)\[EOS\]"
|
|
1176
|
+
matches = re.findall(pattern, decoded_output, re.DOTALL)
|
|
1177
|
+
query_for_search = matches[-1].strip() if matches else "dummy"
|
|
1178
|
+
queries_for_search.append(query_for_search)
|
|
1179
|
+
|
|
1180
|
+
# Perform batch retrieval
|
|
1181
|
+
if queries_for_search:
|
|
1182
|
+
batch_search_results = self.retriever.batch_search(queries_for_search)
|
|
1183
|
+
|
|
1184
|
+
for i, decoded_output in enumerate(decoded_outputs):
|
|
1185
|
+
search_results = batch_search_results[i]
|
|
1186
|
+
format_evidence = self.format_evidences(search_results)
|
|
1187
|
+
new_prompt = decoded_output + "[R_Evidences]" + format_evidence + "[/R_Evidences]"
|
|
1188
|
+
new_path = {
|
|
1189
|
+
"prompt": input_texts[i] + new_prompt,
|
|
1190
|
+
"depth": current_path["depth"] + 1,
|
|
1191
|
+
"done": False,
|
|
1192
|
+
}
|
|
1193
|
+
paths_batch_dict[i].append(new_path)
|
|
1194
|
+
|
|
1195
|
+
final_outputs_batch_list = [final_outputs_batch[i] for i in range(len(initial_prompts_batch))]
|
|
1196
|
+
|
|
1197
|
+
return final_outputs_batch_list
|
|
1198
|
+
|
|
1199
|
+
def select_best_path_single_turn(self, final_outputs):
|
|
1200
|
+
# After generating all paths, we can select the best answer
|
|
1201
|
+
# Compute perplexity and confidence for each path
|
|
1202
|
+
|
|
1203
|
+
scores = []
|
|
1204
|
+
for path in final_outputs:
|
|
1205
|
+
confidence = path["confidence"]
|
|
1206
|
+
path["confidence"] = confidence
|
|
1207
|
+
scores.append((path, confidence))
|
|
1208
|
+
|
|
1209
|
+
# Select the path with the highest confidence
|
|
1210
|
+
best_path = max(scores, key = lambda x: x[1])[0] # x[2] is confidence
|
|
1211
|
+
pred = best_path["final_answer"]
|
|
1212
|
+
|
|
1213
|
+
return pred, best_path
|
|
1214
|
+
|
|
1215
|
+
def run(self, dataset, do_eval = True):
|
|
1216
|
+
preds = []
|
|
1217
|
+
meta_results = []
|
|
1218
|
+
|
|
1219
|
+
from tqdm import tqdm
|
|
1220
|
+
for i in tqdm(range(0, len(dataset), self.batch_size)):
|
|
1221
|
+
batch_items = dataset[i : i + self.batch_size]
|
|
1222
|
+
eval_datas = self.preprocess_eval_data(batch_items)
|
|
1223
|
+
paths_batch = self.generate_tree_of_thoughts_batch(initial_prompts_batch = eval_datas)
|
|
1224
|
+
for paths in paths_batch:
|
|
1225
|
+
pred, best_path = self.select_best_path_single_turn(paths)
|
|
1226
|
+
preds.append(pred)
|
|
1227
|
+
meta_results.append(best_path)
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
dataset.update_output("paths", meta_results)
|
|
1231
|
+
dataset.update_output("pred", preds)
|
|
1232
|
+
|
|
1233
|
+
dataset = self.evaluate(dataset, do_eval = do_eval)
|
|
1234
|
+
return dataset
|
|
1235
|
+
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/base_prompt.py
RENAMED
|
@@ -23,7 +23,7 @@ class PromptTemplate:
|
|
|
23
23
|
self.is_chat = False
|
|
24
24
|
if "chat" in model_name or "instruct" in model_name:
|
|
25
25
|
self.is_chat = True
|
|
26
|
-
self.tokenizer =
|
|
26
|
+
self.tokenizer = None
|
|
27
27
|
else:
|
|
28
28
|
self.is_chat = True
|
|
29
29
|
self.enable_chat = True
|
|
@@ -79,6 +79,8 @@ class PromptTemplate:
|
|
|
79
79
|
return truncated_messages
|
|
80
80
|
|
|
81
81
|
else:
|
|
82
|
+
if self.tokenizer is None:
|
|
83
|
+
self.tokenizer = AutoTokenizer.from_pretrained(self.generator_path, trust_remote_code=True)
|
|
82
84
|
assert isinstance(prompt, str)
|
|
83
85
|
tokenized_prompt = self.tokenizer(prompt, truncation=False, return_tensors="pt").input_ids[0]
|
|
84
86
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.4dev20241210"
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210/flashrag_dev.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: flashrag-dev
|
|
3
|
-
Version: 0.1.4.
|
|
3
|
+
Version: 0.1.4.dev20241210
|
|
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.4dev20241203"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/config/__init__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/config/basic_config.yaml
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/dataset/__init__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/dataset/dataset.py
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/__init__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/_bleu.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/evaluator.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/metrics.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/evaluator/utils.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/generator/utils.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/judger/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/pipeline.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/pipeline/replug_utils.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/prompt/trace_examplars.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/__init__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/kg_refiner.py
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/refiner/refiner.py
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/__init__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/__main__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/encoder.py
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/reranker.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/retriever.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/retriever/utils.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/__init__.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/constants.py
RENAMED
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag/utils/pred_parse.py
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag_dev.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{flashrag-dev-0.1.4.dev20241203 → flashrag-dev-0.1.4.dev20241210}/flashrag_dev.egg-info/requires.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|