Lk123 commited on
Commit
83c2bac
·
verified ·
1 Parent(s): f28e227

Upload 18 files

Browse files
.gitattributes CHANGED
@@ -57,3 +57,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ corpus/wiki_webq_corpus.tsv filter=lfs diff=lfs merge=lfs -text
61
+ data/webq-dev.json filter=lfs diff=lfs merge=lfs -text
62
+ data/webq-train.json filter=lfs diff=lfs merge=lfs -text
Retriever/bash_gen.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export CUDA_VISIBLE_DEVICES=0
4
+
5
+ TSV_FILE="../corpus/wiki_webq_corpus.tsv" # wiki语料库
6
+ OUTPUT_FILE="../corpus/ctx_embeddings.pkl" # 语料库embedding
7
+ BATCH_SIZE=128
8
+ MODEL_NAME="facebook/dpr-ctx_encoder-multiset-base" # 模型
9
+ DEVICE="cuda"
10
+
11
+ python gen_embedding.py \
12
+ --tsv_file $TSV_FILE \
13
+ --output_file $OUTPUT_FILE \
14
+ --batch_size $BATCH_SIZE \
15
+ --model_name $MODEL_NAME \
16
+ --insert_title \
17
+ --device $DEVICE
Retriever/bash_retr.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export CUDA_VISIBLE_DEVICES=0
4
+
5
+
6
+ QUESTION_FILE="../data/webq-test.txt" # 问题测试集
7
+ EMBEDDING_FILE="../corpus/ctx_embeddings.pkl" # 语料库的embedding
8
+ INDEX_PATH="../index/webq_index" # 语料库的faiss索引
9
+ OUTPUT_FILE="../output/result.pkl" # 检索结果输出
10
+ BATCH_SIZE=32
11
+ MODEL_NAME="facebook/dpr-question_encoder-multiset-base" # 将问题编码为embedding的模型
12
+ DEVICE="cuda"
13
+
14
+ python retriever.py \
15
+ --questions_file $QUESTION_FILE \
16
+ --context_embeddings_file $EMBEDDING_FILE \
17
+ --model_name $MODEL_NAME \
18
+ --index_path $INDEX_PATH\
19
+ --output_file $OUTPUT_FILE \
20
+ --batch_size $BATCH_SIZE \
21
+ --top_docs 100 \
22
+ --device $DEVICE
Retriever/gen_embedding.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ import torch
4
+ from torch.utils.data import DataLoader, Dataset
5
+ from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
6
+ from typing import List, Tuple, Dict
7
+ import pandas as pd
8
+ import argparse
9
+ from tqdm import tqdm # 导入 tqdm 用于显示进度条
10
+
11
+ class ContextDataset(Dataset):
12
+ """
13
+ 自定义数据集类,用于批量加载上下文文本。
14
+ """
15
+ def __init__(self, contexts: List[Tuple[str, str, str]]):
16
+ """
17
+ Args:
18
+ contexts (List[Tuple[str, str, str]]): 每个条目为 (id, title, text)。
19
+ """
20
+ self.contexts = contexts
21
+
22
+ def __len__(self):
23
+ return len(self.contexts)
24
+
25
+ def __getitem__(self, idx):
26
+ # 返回 (id, title, text)
27
+ return self.contexts[idx]
28
+
29
+ class DPRContextEncoderBatchProcessor:
30
+ def __init__(self, model_name: str = "facebook/dpr-ctx_encoder-multiset-base", batch_size: int = 16, device: str = None):
31
+ self.device = device if device else ("cuda" if torch.cuda.is_available() else "cpu")
32
+ self.tokenizer = DPRContextEncoderTokenizer.from_pretrained(model_name)
33
+ self.model = DPRContextEncoder.from_pretrained(model_name).to(self.device)
34
+ self.batch_size = batch_size
35
+
36
+ def process_contexts(self, contexts: List[Tuple[str, str, str]], insert_title: bool = True) -> List[Tuple[str, List[float]]]:
37
+ """
38
+ 批量处理上下文文本并生成嵌入向量。
39
+
40
+ Args:
41
+ contexts (List[Tuple[str, str, str]]): 每个条目为 (id, title, text)。
42
+ insert_title (bool): 是否在文本前插入标题。
43
+
44
+ Returns:
45
+ List[Tuple[str, List[float]]]: 每个上下文文本的 ID 和嵌入向量列表。
46
+ """
47
+ dataset = ContextDataset(contexts)
48
+ dataloader = DataLoader(dataset, batch_size=self.batch_size, shuffle=False)
49
+
50
+ embeddings = []
51
+ for batch_contexts in tqdm(dataloader, desc="Processing contexts", unit="batch"):
52
+ ids, titles, texts = batch_contexts
53
+ print(f"ids:{ids}")
54
+ # 如果 insert_title 为 True,则将 title 和 text 组合在一起,否则只使用 text
55
+ if insert_title:
56
+ combined_texts = [f"{title} [SEP] {text}" for title, text in zip(titles, texts)]
57
+ else:
58
+ combined_texts = [text for text in texts]
59
+
60
+ inputs = self.tokenizer(
61
+ combined_texts,
62
+ return_tensors="pt",
63
+ padding=True,
64
+ truncation=True,
65
+ max_length=512
66
+ ).to(self.device)
67
+
68
+ with torch.no_grad():
69
+ outputs = self.model(**inputs).pooler_output
70
+ batch_embeddings = outputs.cpu().numpy()
71
+
72
+ for idx, embedding in enumerate(batch_embeddings):
73
+ embeddings.append((ids[idx].item(), embedding))
74
+
75
+ return embeddings
76
+
77
+ def save_embeddings(self, contexts: List[Tuple[str, str, str]], output_file: str, insert_title: bool = True):
78
+ """
79
+ 生成嵌入并保存到指定文件。
80
+
81
+ Args:
82
+ contexts (List[Tuple[str, str, str]]): 每个条目为 (id, title, text)。
83
+ output_file (str): 输出文件路径。
84
+ insert_title (bool): 是否在文本前插入标题。
85
+ """
86
+ print("Generating embeddings...")
87
+ embeddings = self.process_contexts(contexts, insert_title=insert_title)
88
+
89
+ result = {embedding[0]: embedding[1] for embedding in embeddings}
90
+ os.makedirs(os.path.dirname(output_file), exist_ok=True) # 确保输出目录存在
91
+
92
+ print("Saving embeddings to file...")
93
+ with tqdm(total=len(embeddings), desc="Saving embeddings", unit="embedding") as pbar:
94
+ with open(output_file, "wb") as f:
95
+ pickle.dump(result, f)
96
+ pbar.update(len(embeddings))
97
+
98
+ print(f"Total passages processed: {len(embeddings)}. Embeddings saved to {output_file}")
99
+
100
+ def load_and_process_tsv(self, tsv_file: str, output_file: str, insert_title: bool = True):
101
+ """
102
+ 从 TSV 文件中加载数据并生成嵌入。
103
+
104
+ Args:
105
+ tsv_file (str): TSV 文件路径。
106
+ output_file (str): 输出文件路径。
107
+ insert_title (bool): 是否在文本前插入标题。
108
+ """
109
+ print(f"Loading data from {tsv_file}...")
110
+ df = pd.read_csv(tsv_file, sep='\t')
111
+ # 提取 id, title 和 text 列
112
+ ids = df['id'].tolist()
113
+ titles = df['title'].fillna("").tolist()
114
+ texts = df['text'].fillna("").tolist()
115
+
116
+ contexts = list(zip(ids, titles, texts))
117
+
118
+ self.save_embeddings(contexts, output_file, insert_title=insert_title)
119
+
120
+
121
+ def main():
122
+ parser = argparse.ArgumentParser(description="DPR Context Encoder Batch Processor")
123
+ parser.add_argument("--tsv_file", type=str, required=True, help="Path to the input TSV file with 'id', 'title', and 'text' columns.")
124
+ parser.add_argument("--output_file", type=str, required=True, help="Path to save the generated embeddings.")
125
+ parser.add_argument("--batch_size", type=int, default=8, help="Batch size for processing contexts.")
126
+ parser.add_argument("--model_name", type=str, default="facebook/dpr-ctx_encoder-multiset-base", help="Name of the DPR context encoder model.")
127
+ parser.add_argument("--insert_title", action="store_true", help="Whether to insert the title before the text for embedding generation.")
128
+ parser.add_argument("--device", type=str, default=None, help="Device to run the model on (e.g., 'cuda' or 'cpu').")
129
+
130
+ args = parser.parse_args()
131
+
132
+ processor = DPRContextEncoderBatchProcessor(
133
+ model_name=args.model_name,
134
+ batch_size=args.batch_size,
135
+ device=args.device
136
+ )
137
+
138
+ processor.load_and_process_tsv(args.tsv_file, args.output_file, insert_title=args.insert_title)
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
Retriever/retriever.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import pickle
4
+ import time
5
+ from typing import List, Tuple, Dict
6
+
7
+ import numpy as np
8
+ import torch
9
+ from torch import nn, Tensor as T
10
+ from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
11
+ from dpr.indexer.faiss_indexers import DenseFlatIndexer
12
+ from tqdm import tqdm # 导入 tqdm 用于显示进度条
13
+
14
+ logger = logging.getLogger()
15
+ logging.basicConfig(level=logging.INFO)
16
+
17
+
18
+ def load_context_embeddings(embedding_file: str) -> Dict[str, np.ndarray]:
19
+ """
20
+ 从给定文件中加载上下文嵌入
21
+ :param embedding_file: 上下文嵌入文件路径 (.pkl 格式)
22
+ :return: 上下文ID到嵌入向量的字典
23
+ """
24
+ with open(embedding_file, "rb") as f:
25
+ embeddings = pickle.load(f)
26
+ return embeddings
27
+
28
+
29
+ def generate_question_vectors(questions: List[str], model_name: str, batch_size: int, device: str) -> T:
30
+ """
31
+ 使用 Hugging Face 模型生成问题嵌入向量
32
+ :param questions: 要生成嵌入的问题列表
33
+ :param model_name: Hugging Face 模型名称
34
+ :param batch_size: 批量大小
35
+ :param device: 设备('cpu' 或 'cuda')
36
+ :return: 问题嵌入向量张量
37
+ """
38
+ tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(model_name)
39
+ model = DPRQuestionEncoder.from_pretrained(model_name).to(device)
40
+
41
+ n = len(questions)
42
+ query_vectors = []
43
+
44
+ with torch.no_grad():
45
+ for batch_start in tqdm(range(0, n, batch_size), desc="Generating question embeddings", unit="batch"):
46
+ batch_questions = questions[batch_start:batch_start + batch_size]
47
+ inputs = tokenizer(batch_questions, return_tensors="pt", padding=True, truncation=True).to(device)
48
+ outputs = model(**inputs)
49
+ query_vectors.extend(outputs.pooler_output.cpu().split(1, dim=0))
50
+
51
+ if len(query_vectors) % 100 == 0:
52
+ logger.info("Encoded queries %d", len(query_vectors))
53
+
54
+ query_tensor = torch.cat(query_vectors, dim=0)
55
+ logger.info("Total encoded queries tensor size: %s", query_tensor.size())
56
+ assert query_tensor.size(0) == len(questions)
57
+ return query_tensor
58
+
59
+
60
+ class LocalFaissRetriever:
61
+ def __init__(self, question_encoder_name: str, batch_size: int, device: str, index: DenseFlatIndexer):
62
+ self.question_encoder_name = question_encoder_name
63
+ self.batch_size = batch_size
64
+ self.device = device
65
+ self.index = index
66
+
67
+ def generate_question_vectors(self, questions: List[str]) -> T:
68
+ return generate_question_vectors(questions, self.question_encoder_name, self.batch_size, self.device)
69
+
70
+ def index_encoded_data(self, embeddings: Dict[str, np.ndarray], buffer_size: int):
71
+ """
72
+ 从给定的上下文嵌入字典中索引已编码的上下文嵌入
73
+ :param embeddings: 上下文ID到嵌入向量的字典
74
+ :param buffer_size: 每次索引的缓冲区大小
75
+ """
76
+ buffer = []
77
+ for doc_id, vector in embeddings.items():
78
+ print(f"doc_id:{doc_id}")
79
+ buffer.append((doc_id, vector))
80
+ if len(buffer) >= buffer_size:
81
+ self.index.index_data(buffer)
82
+ buffer = []
83
+ if buffer:
84
+ self.index.index_data(buffer)
85
+ logger.info("Data indexing completed.")
86
+
87
+ def get_top_docs(self, query_vectors: np.array, top_docs: int = 100) -> List[Tuple[List[object], List[float]]]:
88
+ """
89
+ 使用 Faiss 索引检索最佳匹配的上下文
90
+ :param query_vectors: 查询嵌入向量
91
+ :param top_docs: 要返回的文档数量
92
+ :return: 检索到的上下文 ID 和得分的列表
93
+ """
94
+ start_time = time.time()
95
+ results = []
96
+ for start_idx in tqdm(range(0, query_vectors.shape[0], 512), desc="Retrieving top docs", unit="batch"):
97
+ batch_query_vectors = query_vectors[start_idx: start_idx + 512]
98
+ batch_results = self.index.search_knn(batch_query_vectors, top_docs)
99
+ print(f"batch_results:{batch_results[0]}")
100
+ results.extend(batch_results)
101
+ logger.info("Index search time: %f sec.", time.time() - start_time)
102
+ return results
103
+
104
+
105
+ def main():
106
+ import argparse
107
+ parser = argparse.ArgumentParser(description="Dense Retriever for Question Answering")
108
+ parser.add_argument("--questions_file", type=str, required=True, help="Path to the input questions file (one question per line)")
109
+ parser.add_argument("--context_embeddings_file", type=str, required=True, help="Path to the context embeddings file (.pkl)")
110
+ parser.add_argument("--batch_size", type=int, default=8, help="Batch size for question encoding")
111
+ parser.add_argument("--model_name", type=str, default="facebook/dpr-question_encoder-multiset-base", help="Name of the question encoder model")
112
+ parser.add_argument("--index_path", type=str, required=True, help="Path to store or load the Faiss index")
113
+ parser.add_argument("--top_docs", type=int, default=10, help="Number of top documents to retrieve")
114
+ parser.add_argument("--device", type=str, default="cuda", help="Device to run the model on (e.g., 'cuda' or 'cpu')")
115
+ parser.add_argument("--output_file", type=str, required=True, help="Path to save the retrieval results (.pkl)")
116
+ args = parser.parse_args()
117
+
118
+ with open(args.questions_file, "r") as f:
119
+ questions = [line.strip() for line in f.readlines()]
120
+
121
+ context_embeddings = load_context_embeddings(args.context_embeddings_file)
122
+
123
+ vector_size = next(iter(context_embeddings.values())).shape[0]
124
+ index = DenseFlatIndexer(vector_size)
125
+
126
+ if os.path.exists(args.index_path):
127
+ logger.info(f"Loading existing index from {args.index_path}")
128
+ index.deserialize(args.index_path)
129
+ retriever = LocalFaissRetriever(args.model_name, args.batch_size, args.device, index)
130
+ else:
131
+ os.makedirs(args.index_path, exist_ok=True)
132
+ logger.info(f"Creating new index and saving to {args.index_path}")
133
+ index.init_index(vector_size)
134
+ retriever = LocalFaissRetriever(args.model_name, args.batch_size, args.device, index)
135
+ retriever.index_encoded_data(context_embeddings, buffer_size=1000)
136
+ index.serialize(args.index_path)
137
+
138
+ question_vectors = retriever.generate_question_vectors(questions)
139
+
140
+ top_results_and_scores = retriever.get_top_docs(question_vectors.numpy(), args.top_docs)
141
+
142
+ queries_results = []
143
+ for i, _ in tqdm(enumerate(questions), desc="Processing queries", total=len(questions), unit="query"):
144
+ docs_id = [str(item) for item in top_results_and_scores[i][0]]
145
+ docs_score = [score for score in top_results_and_scores[i][1]]
146
+ queries_results.append((docs_id, docs_score))
147
+
148
+ with open(args.output_file, "wb") as f:
149
+ pickle.dump(queries_results, f)
150
+
151
+ print(f"Results saved to {args.output_file}")
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
cal_hit_multi.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #%%
2
+ from utils.retriever_utils import load_passages, validate, save_results
3
+ import pickle
4
+ import os
5
+ import csv
6
+
7
+ #%%
8
+ def load_data_with_pickle(file_path):
9
+ with open(file_path, 'rb') as f:
10
+ return pickle.load(f)
11
+
12
+
13
+ def process_and_save_retrieval_results(top_docs, dataset_name, questions, question_answers, all_passages, num_threads, match_type, output_dir, output_no_text=False):
14
+ recall_outfile = os.path.join(output_dir, 'recall_at_k.csv')
15
+ result_outfile = os.path.join(output_dir, 'results.json')
16
+
17
+ questions_doc_hits = validate(
18
+ dataset_name,
19
+ all_passages,
20
+ question_answers,
21
+ top_docs,
22
+ num_threads,
23
+ match_type,
24
+ recall_outfile,
25
+ use_wandb=False
26
+ )
27
+
28
+ save_results(
29
+ all_passages,
30
+ questions,
31
+ question_answers,
32
+ top_docs,
33
+ questions_doc_hits,
34
+ result_outfile,
35
+ output_no_text=output_no_text
36
+ )
37
+
38
+ return questions_doc_hits
39
+
40
+
41
+ #%%
42
+ if __name__=='__main__':
43
+
44
+ dataset_name = 'webq'
45
+ num_threads = 10
46
+ output_no_text = False
47
+ ctx_file = './corpus/wiki_webq_corpus.tsv'
48
+
49
+
50
+ match_type = 'string'
51
+ input_file_path = './data/webq-test.csv'
52
+ with open(input_file_path,'r') as file:
53
+ query_data = csv.reader(file, delimiter='\t')
54
+ questions, question_answers = zip(*[(item[0], eval(item[1])) for item in query_data])
55
+ questions = questions
56
+ question_answers = question_answers
57
+
58
+ all_passages = load_passages(ctx_file)
59
+
60
+ output_dir = './output/webq-test-result'
61
+
62
+
63
+ top_docs_pkl_path = './output/result_str.pkl'
64
+
65
+ top_docs = load_data_with_pickle(top_docs_pkl_path)
66
+
67
+ os.makedirs(output_dir, exist_ok=True)
68
+ questions_doc_hits = process_and_save_retrieval_results(
69
+ top_docs,
70
+ dataset_name,
71
+ questions,
72
+ question_answers,
73
+ all_passages,
74
+ num_threads,
75
+ match_type,
76
+ output_dir,
77
+ output_no_text=output_no_text
78
+ )
79
+
80
+ print('Validation End!')
corpus/wiki_webq_corpus.tsv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86aa0e5ce96de15cdcfd6612e72904d689a9a0faadea2a34c2079c504d14969a
3
+ size 486677193
data/webq-dev.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:67cbb68d95f6a3652f0d5d07add0ba09f14f55b0a313ef7e18e14abf12e5a6da
3
+ size 23175353
data/webq-test.csv ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ what influenced john steinbeck to start writing? ['William Faulkner', 'Robert Burns', 'Sherwood Anderson', 'Thomas Malory']
2
+ what school did sir ernest rutherford go to? ['Trinity College, Cambridge', 'Nelson College', 'University of Canterbury', 'University of Cambridge', 'University of New Zealand']
3
+ what instruments does justin bieber use? ['guitar', 'Piano', 'trumpet', 'Drums']
4
+ when did president theodore roosevelt take office? ['9/14/1901']
5
+ what was dr seuss real name? ['Theodor Robert Geisel']
6
+ what movies is omar epps in? "['Daybreak', 'Major League II', 'Scream 2', 'First Time Felon', 'Breakfast of Champions', 'Juice', 'The Program', 'Deadly Voyage', 'Higher Learning', ""Don't Be a Menace to South Central While Drinking Your Juice in the Hood""]"
7
+ what is the state name of new york city? ['New York']
8
+ where did eleanor roosevelt die? ['New York City']
9
+ where was farrah fawcett buried? ['Westwood Village Memorial Park Cemetery']
10
+ where did benjamin franklin work? ['James Franklin Printing Shop', 'United States Postal Service', 'Josiah Franklin']
11
+ who did paul revere marry? ['Sarah Revere']
12
+ what was robert burns? ['Poet', 'Writer', 'Bard', 'Author']
13
+ what type of government does russia have 2010? ['Semi-presidential system', 'Constitutional republic', 'Republic', 'Federation']
14
+ what other movies is josh hutcherson in? ['The Hunger Games', 'Bridge to Terabithia', 'The Kids Are All Right']
15
+ who did johnny depp play in corpse bride? ['Victor Van Dort']
16
+ who is the governor of virginia 2011? ['Bob McDonnell']
17
+ who are the senators of new jersey now? ['Bob Menendez']
18
+ what to visit in london city? "[""Regent's Park"", 'Tower of London', 'Buckingham Palace', 'Palace of Westminster', 'London Eye', 'Tower Bridge', 'Hyde Park', 'Westminster Abbey', ""St Paul's Cathedral"", 'Trafalgar Square']"
19
+ where does robin williams live 2011? ['San Francisco']
20
+ who is washington redskins backup qb? ['Rex Grossman']
21
+ who plays stacey in the stacy's mom video? ['Lacey Turner']
22
+ what is the current time in kauai hawaii? ['Hawaii–Aleutian Time Zone', 'UTC−10:00']
23
+ what club does cristiano ronaldo play for in 2010? ['Real Madrid C.F.']
24
+ when does jewish new year start? ['Yiddish Language']
25
+ when was president john adams elected? ['John Adams Presidential Campaign, 1796', 'John Adams Presidential Campaign, 1800']
26
+ who was king henry viii son? ['Prince Henry, Duke of Cornwall', 'Edward VI of England', 'Mary I of England', 'Edward Tudor', 'Henry, Duke of Cornwall', 'Elizabeth I of England', 'Henry FitzRoy, 1st Duke of Richmond and Somerset', 'Henry Tudor']
27
+ where was toussaint l'ouverture born? ['Haiti']
28
+ what type of cancer did gilda radner die of? ['Ovarian cancer']
29
+ where did harry s truman go to school? ['University of Missouri–Kansas City School of Law', 'University of Missouri–Kansas City', 'William Chrisman High School']
30
+ who was the father of king george vi? ['George V']
31
+ what language does egyptian people speak? ['Modern Standard Arabic']
32
+ what language do australia people speak? ['Lojban', 'Esperanto Language', 'English Language']
33
+ what type of music did mozart composed? ['Opera', 'Classical music', 'Ballet', 'Art song', 'Chamber music']
34
+ what channel is the usa pageant on? ['us']
35
+ when did michael jordan return to the nba? ['2001–02 NBA season']
36
+ what time in china hong kong? ['UTC+8']
37
+ what year was first world series? ['1903 World Series']
38
+ when did the philadelphia flyers win the cup? ['1974 Stanley Cup Finals', '1975 Stanley Cup Finals']
39
+ where is jason mraz from? ['Mechanicsville']
40
+ what are the names of michael jackson's 3 children? ['Paris-Michael Katherine Jackson', 'Prince Michael Jackson I', 'Prince Michael Jackson II']
41
+ what county is texarkana arkansas in? ['Miller County']
42
+ what team does messi play for 2011? ['FC Barcelona']
43
+ what airport do you fly into to get to destin fl? ['Northwest Florida Regional Airport', 'Destin–Fort Walton Beach Airport']
44
+ when was the last time the boston bruins went to the stanley cup? ['2011 Stanley Cup Finals']
45
+ what team is kris humphries play for? ['Brooklyn Nets']
46
+ where should a family stay in paris? ['Hôtel Ritz Paris', 'Hôtel de Crillon']
47
+ what are staffordshire terriers? ['Dog']
48
+ what does sarabi? ['Physician']
49
+ what kind of government does the united states have currently? ['Federal republic']
50
+ who will be the red sox next coach? ['Nomar Garciaparra']
51
+ what was the name of jfk's brothers? ['Robert F. Kennedy', 'Ted Kennedy', 'Rosemary Kennedy', 'Kathleen Cavendish', 'Patricia Kennedy Lawford', 'Jean Kennedy Smith', 'Eunice Kennedy Shriver', 'Joseph P. Kennedy, Jr.']
52
+ when did roth ira originate? ['William V. Roth, Jr.']
53
+ what political party does barack obama represent? ['Democratic Party']
54
+ what year did the milwaukee brewers go to the world series? ['1974 Major League Baseball Season']
55
+ where does egypt export to? ['Sudan']
56
+ where is roswell area 51? ['Roswell']
57
+ what to do today in atlanta with kids? ['Atlanta History Center', 'Atlanta Cyclorama & Civil War Museum', 'Atlanta Ballet', 'Fernbank Museum of Natural History', 'Woodruff Arts Center', 'Zoo Atlanta', 'Atlanta Symphony Orchestra', 'Centennial Olympic Park', 'Martin Luther King, Jr., National Historic Site', 'Fernbank Science Center']
58
+ what language did the ancient babylonians speak? ['Akkadian language']
59
+ what did george washington do as a teenager? ['Surveyor']
60
+ what century did slavery end in america? ['Western Hemisphere']
61
+ who owns chrysler corporation 2011? ['Chrysler Group LLC']
62
+ what did miles davis died of? ['Pneumonia', 'Stroke', 'Respiratory failure']
63
+ what type of political system is brazil? ['Constitutional republic', 'Presidential system', 'Federal republic']
64
+ where is the university of the rockies located? ['United States of America', 'Colorado', 'Colorado Springs']
65
+ what county is st paul va in? ['United States of America', 'Wise County', 'Russell County', 'Virginia']
66
+ when did charles goodyear invented rubber? "[""During the early 1830's he began inventing, filing six patents between 1830 and 1834, and during this period became interested in rubber, which he tried - unsuccessfully - to use in some of his mechanical inventions.""]"
67
+ where is the thames river source? ['Thames Head']
68
+ what countries are part of the uk? ['Scotland', 'England', 'Wales', 'Northern Ireland']
69
+ what do we call the currency of france? ['French franc']
70
+ what are the official languages of argentina? ['Yiddish Language', 'Italian Language', 'Spanish Language']
71
+ where did the gallipoli war take place? ['Gallipoli']
72
+ what type of government does brazil have 2011? ['Brazilian Labour Renewal Party']
73
+ where did william morris go to college? ['Marlborough College', 'Exeter College, Oxford', 'University of Oxford']
74
+ what the time zone in japan? ['Japan Standard Time', 'UTC+09:00']
75
+ what language do people from greece speak? ['Albanian language', 'Greek Language']
76
+ what radio station is npr on in nyc? ['WNYC']
77
+ what degrees did barack obama get? ['Juris Doctor', 'Bachelor of Arts']
78
+ who played elaine the pain? ['Julia Louis-Dreyfus']
79
+ who is amy grant's first husband? ['Vince Gill']
80
+ what books did agatha christie wrote? ['And Then There Were None', 'Le Grand alibi', 'Ten Little Indians', 'Appointment with Death', 'Desyat Negrityat', 'The Man in the Brown Suit', 'Witness for the Prosecution']
81
+ who is moira in x men? ['Olivia Williams', 'Rose Byrne']
82
+ what did drita find out? ['Football Superleague of Kosovo']
83
+ who played barbara gordon batgirl? ['Alicia Silverstone']
84
+ what type of music did john lennon sing? ['Experimental rock', 'Pop rock', 'Pop music', 'Blues-rock', 'Art rock', 'Soft rock', 'Psychedelic rock', 'Rock music', 'Experimental music']
85
+ what position did lebron james play? ['Point forward', 'Small forward']
86
+ where is the university of maryland medical school? ['Maryland', 'United States of America', 'Baltimore']
87
+ what form of government does north korea have? "['Single-party state', 'Socialist state', ""People's Republic"", 'Juche', 'Unitary state']"
88
+ who was the secretary of state when andrew jackson was president? ['Martin Van Buren']
89
+ which dawkins book to read first? ['The Selfish Gene']
90
+ what money does spain use? ['Euro']
91
+ who played amy squirrel in bad teacher? ['Lucy Punch']
92
+ what was gregor mendel contribution? ['Mendelian inheritance']
93
+ where does the expression excuse my french come from? ['English Literature']
94
+ who is vancouver canucks coach? ['Alain Vigneault']
95
+ where is holy roman empire located? ['Europe', 'North Africa', 'Middle East']
96
+ where do the appalachian mountains run? ['Eastern United States']
97
+ what type of government does the us follow? ['Presidential system', 'Federal republic', 'Representative democracy', 'Two-party system', 'Constitutional republic', 'Republic']
98
+ what states share a border with tennessee? ['Virginia']
99
+ where is harley davidson made? ['United States of America']
100
+ what did shakespeare learn in grammar school? ['william shakespeare performed play by thomas dekker']
101
+ who does the voice for chucky in child's play? ['Brad Dourif']
102
+ where were the seneca indians located? ['New York']
103
+ what would ap xin zhao do? ['Male']
104
+ who was the artist of mickey mouse? ['Ub Iwerks', 'Walt Disney']
105
+ what language is spoken in switzerland? ['Romansh language', 'French Language', 'German Language', 'Italian Language']
106
+ what was dr seuss's real name? ['Theodor Robert Geisel']
107
+ who plays elena gilbert on vampire diaries? ['Nina Dobrev']
108
+ what are all the movies taylor swift has been in? "['Hannah Montana: The Movie', 'Campfire Stories;Comes Around Gos Around', 'The Lorax', ""Valentine's Day""]"
109
+ who plays charlie in the santa clause movies? ['Kansas City Athletics']
110
+ what produce does florida export? ['Orange juice']
111
+ where did kobe earthquake happen? ['Great Hanshin earthquake']
112
+ what record label is kelly clarkson signed with? ['RCA Records', 'Sony BMG Music Entertainment', 'Sony Music Entertainment']
113
+ who has coached the carolina panthers? ['George Seifert', 'Dom Capers', 'John Fox']
114
+ what country is dyson made? ['United Kingdom']
115
+ where does the columbia river start? ['Columbia Lake']
116
+ who are the u s senators of pennsylvania? ['James Buchanan', 'Albert Gallatin', 'Bob Casey, Jr.', 'George Clymer', 'Arlen Specter', 'Robert Morris', 'William Maclay', 'Michael J. Holston', 'Pat Toomey', 'James Ross']
117
+ where did the russian japanese war happen? ['Yellow Sea', 'Korean Peninsula', 'Manchuria']
118
+ what language is most commonly spoken in belgium? ['French Language', 'German Language', 'Dutch Language']
119
+ where did joe flacco attend college? ['University of Delaware']
120
+ what to do san jose ca? ['San Jose Municipal Rose Garden', 'The Tech Museum of Innovation', 'Winchester Mystery House', 'Japantown', 'Downtown San Jose', 'Rosicrucian Egyptian Museum', 'San Jose Museum of Quilts & Textiles', 'San Jose Museum of Art', 'Alum Rock Park', 'Santana Row']
121
+ where is the empire of ghana? ['West Africa']
122
+ what did dmitri mendeleev discover in 1869? ['Periodic Table']
123
+ where to get a marriage license in long island? ['United States District Court for the Eastern District of New York']
124
+ when does the world end according to the mayans time? ['2012']
125
+ what do the symbols on the nevada flag mean? ['All For Our Country']
126
+ where is perpignan located? ['France']
127
+ where is olympic national park wa? ['Jefferson County', 'Washington']
128
+ when was the most recent earthquake in haiti? ['2010 Haiti Earthquake']
129
+ what books are written by suzanne collins? ['Gregor and the Prophecy of Bane', 'Gregor and the Marks of Secret', 'FIRE PROOF', 'Gregor and the Code of Claw', 'The Underland Chronicles Book Three', 'When Charlie McButton lost power', 'Gregor and the Curse of the Warmbloods', 'Catching Fire', '12', 'Gregor the Overlander']
130
+ who is the president of peru now? ['Ollanta Humala']
131
+ where did the israel palestine conflict start? ['1936–39 Arab revolt in Palestine']
132
+ what are some ancient egypt names? ['Abdel Hakim Amer', 'Abdul Munim Riad', 'Ahmad Ismail Ali', 'Abdul Munim Wassel', 'Saad El Shazly', 'Hosni Mubarak', 'Mohammed Aly Fahmy', 'Anwar Sadat', 'Abd-Al-Minaam Khaleel', 'Abdel Ghani el-Gamasy']
133
+ where is the fukushima daiichi nuclear plant located? ['Japan', 'Okuma']
134
+ who is mary mcleod bethune for kids? ['Educator']
135
+ what character did billy d williams play in star wars? ['Lando Calrissian']
136
+ what city is mt lassen in? ['Shasta County']
137
+ where do john lennon die? ['New York City']
138
+ when does daylight saving end in new zealand 2012? ['nz']
139
+ where did spencer pratt go to school? ['University of Southern California']
140
+ where was the temple of karnak built? ['Egypt', 'Luxor Governorate']
141
+ what did shakespeare become famous for? ['Poet', 'Playwright', 'Dramatist', 'Lyricist', 'Author']
142
+ what language do they speak in malta? ['Maltese Language', 'English Language']
143
+ who did ricky martin started his career with? ['Menudo']
144
+ what language did they speak in ghana? ['Akan Language']
145
+ who was dan white? ['Firefighter', 'Politician', 'Police officer']
146
+ who does peter griffin voice? ['Seth MacFarlane']
147
+ where was benjamin franklin educated? ['Boston Latin School']
148
+ what does gm make? ['Automobile']
149
+ who played lauren reed on alias? ['Melissa George']
150
+ who does donnie wahlberg play in the sixth sense? ['Vincent Grey']
151
+ where does marta play soccer? ['Umeå IK']
152
+ where are the gobi desert located on a map? ['Mongolia']
153
+ where are the texas rangers playing? ['Rangers Ballpark in Arlington']
154
+ what percent of americans have college degree? "[""Why Race Mattered in Barack Obama's Re-election""]"
155
+ where was country singer george jones born? ['Saratoga']
156
+ where is denmark situated? ['Euroregion Baltic']
157
+ where was osama bin laden killed? ['Abbottabad']
158
+ what did shannon hoon die from? ['Drug overdose']
159
+ what kind of government is sweden? ['Representative democracy', 'Unitary state', 'Parliamentary system', 'Constitutional monarchy', 'Hereditary monarchy', 'Multi-party system']
160
+ who or what influenced albert einstein? ['Hendrik Lorentz', 'Isaac Newton', 'Baruch Spinoza', 'George Bernard Shaw', 'Hermann Minkowski', 'James Clerk Maxwell', 'Paul Valéry', 'Karl Pearson', 'Ernst Mach', 'Bernhard Riemann']
161
+ what is arkansas state capitol? ['Little Rock']
162
+ where does kurdish people live? ['Asia']
163
+ who is the state governor of tennessee? ['Bill Haslam']
164
+ what sri lanka capital? ['Sri Jayawardenapura Kotte']
165
+ what political party did andrew johnson belong to? ['Democratic Party', 'National Union Party', 'Republican Party']
166
+ where did mubarak get his wealth? ['Politician']
167
+ what team did aguero play for? ['Argentina national football team', 'Manchester City F.C.', 'Club Atlético Independiente', 'Atlético Madrid']
168
+ where did george michael go to school? ['Bushey Meads School']
169
+ who plays london tipton in suite life on deck? ['Brenda Song']
170
+ who is sir james dyson? ['Designer', 'Industrial designer', 'Engineer', 'Inventor']
171
+ what city in florida has the lowest crime rate? ['Melquíades Rafael Martinez']
172
+ what team did ronaldo play for in 2003? ['Real Madrid C.F.']
173
+ what year did houston rockets win their first championship? ['1994 NBA Finals']
174
+ what does monsanto own? ['Agricultural Chemicals', 'Seed', 'Agriculture', 'Chemical industry']
175
+ who was jesse james killed by? ['The Assassination of Jesse James by the Coward Robert Ford']
176
+ what is the predominant religion in israel? ['Judaism']
177
+ with which ancient ruler did julius caesar fall in love? ['Cornelia Cinna minor', 'Pompeia', 'Calpurnia Pisonis']
178
+ what kind of money should i take to costa rica? ['Costa Rican colón']
179
+ where did paula deen go to school? ['Albany High School']
180
+ what highschool did r. kelly attend? ['Kenwood Academy']
181
+ who is number 22 for the dallas cowboys? ['Felix Jones']
182
+ when was the last time the orioles won the world series? ['1983 World Series']
183
+ who did woody harrelson play on cheers? ['Woody Boyd']
184
+ what country did buddha come from? ['India']
185
+ what type of religion does argentina have? ['Protestantism', 'Catholicism', 'Judaism']
186
+ what language do they in ghana? ['English Language']
187
+ what the largest city in spain? ['Madrid']
188
+ who is khloe kardashian's husband? ['Lamar Odom']
189
+ what college did john nash teach at? ['Princeton University']
190
+ what stones albums did mick taylor play on? "[""A Stone's Throw"", 'Too Hot For Snakes', 'Stranger in This Town', 'Little Red Rooster', ""Arthur's Club-Geneve 1995"", 'Keepin It Real', 'Mick Taylor']"
191
+ what political party was hitler in? "[""German Workers' Party"", 'Nazi Party']"
192
+ what college did se hinton go? ['University of Tulsa']
193
+ what language is spoken in haiti today? ['French Language', 'Haitian Creole French Language']
194
+ who plays king julian madagascar? ['Sacha Baron Cohen']
195
+ what state is saint louis university in? ['Missouri']
196
+ where did george herbert walker bush go to college? ['Yale University', 'Phillips Academy', 'Davenport College']
197
+ where is mount st helens volcano? ['Skamania County']
198
+ what did joan crawford died of? ['Myocardial infarction', 'Pancreatic cancer']
199
+ what awards gary paulsen won? "['Spur Award for Best Juvenile Fiction', ""Dorothy Canfield Fisher Children's Book Award"", 'Regina Medal', ""Anne V. Zarrow Award for Young Readers' Literature"", 'Spur Award for Best Juvenile Nonfiction', 'Newbery Honor']"
200
+ who is eli whitney and what did he invent? ['Cotton gin']
data/webq-test.txt ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ what influenced john steinbeck to start writing?
2
+ what school did sir ernest rutherford go to?
3
+ what instruments does justin bieber use?
4
+ when did president theodore roosevelt take office?
5
+ what was dr seuss real name?
6
+ what movies is omar epps in?
7
+ what is the state name of new york city?
8
+ where did eleanor roosevelt die?
9
+ where was farrah fawcett buried?
10
+ where did benjamin franklin work?
11
+ who did paul revere marry?
12
+ what was robert burns?
13
+ what type of government does russia have 2010?
14
+ what other movies is josh hutcherson in?
15
+ who did johnny depp play in corpse bride?
16
+ who is the governor of virginia 2011?
17
+ who are the senators of new jersey now?
18
+ what to visit in london city?
19
+ where does robin williams live 2011?
20
+ who is washington redskins backup qb?
21
+ who plays stacey in the stacy's mom video?
22
+ what is the current time in kauai hawaii?
23
+ what club does cristiano ronaldo play for in 2010?
24
+ when does jewish new year start?
25
+ when was president john adams elected?
26
+ who was king henry viii son?
27
+ where was toussaint l'ouverture born?
28
+ what type of cancer did gilda radner die of?
29
+ where did harry s truman go to school?
30
+ who was the father of king george vi?
31
+ what language does egyptian people speak?
32
+ what language do australia people speak?
33
+ what type of music did mozart composed?
34
+ what channel is the usa pageant on?
35
+ when did michael jordan return to the nba?
36
+ what time in china hong kong?
37
+ what year was first world series?
38
+ when did the philadelphia flyers win the cup?
39
+ where is jason mraz from?
40
+ what are the names of michael jackson's 3 children?
41
+ what county is texarkana arkansas in?
42
+ what team does messi play for 2011?
43
+ what airport do you fly into to get to destin fl?
44
+ when was the last time the boston bruins went to the stanley cup?
45
+ what team is kris humphries play for?
46
+ where should a family stay in paris?
47
+ what are staffordshire terriers?
48
+ what does sarabi?
49
+ what kind of government does the united states have currently?
50
+ who will be the red sox next coach?
51
+ what was the name of jfk's brothers?
52
+ when did roth ira originate?
53
+ what political party does barack obama represent?
54
+ what year did the milwaukee brewers go to the world series?
55
+ where does egypt export to?
56
+ where is roswell area 51?
57
+ what to do today in atlanta with kids?
58
+ what language did the ancient babylonians speak?
59
+ what did george washington do as a teenager?
60
+ what century did slavery end in america?
61
+ who owns chrysler corporation 2011?
62
+ what did miles davis died of?
63
+ what type of political system is brazil?
64
+ where is the university of the rockies located?
65
+ what county is st paul va in?
66
+ when did charles goodyear invented rubber?
67
+ where is the thames river source?
68
+ what countries are part of the uk?
69
+ what do we call the currency of france?
70
+ what are the official languages of argentina?
71
+ where did the gallipoli war take place?
72
+ what type of government does brazil have 2011?
73
+ where did william morris go to college?
74
+ what the time zone in japan?
75
+ what language do people from greece speak?
76
+ what radio station is npr on in nyc?
77
+ what degrees did barack obama get?
78
+ who played elaine the pain?
79
+ who is amy grant's first husband?
80
+ what books did agatha christie wrote?
81
+ who is moira in x men?
82
+ what did drita find out?
83
+ who played barbara gordon batgirl?
84
+ what type of music did john lennon sing?
85
+ what position did lebron james play?
86
+ where is the university of maryland medical school?
87
+ what form of government does north korea have?
88
+ who was the secretary of state when andrew jackson was president?
89
+ which dawkins book to read first?
90
+ what money does spain use?
91
+ who played amy squirrel in bad teacher?
92
+ what was gregor mendel contribution?
93
+ where does the expression excuse my french come from?
94
+ who is vancouver canucks coach?
95
+ where is holy roman empire located?
96
+ where do the appalachian mountains run?
97
+ what type of government does the us follow?
98
+ what states share a border with tennessee?
99
+ where is harley davidson made?
100
+ what did shakespeare learn in grammar school?
101
+ who does the voice for chucky in child's play?
102
+ where were the seneca indians located?
103
+ what would ap xin zhao do?
104
+ who was the artist of mickey mouse?
105
+ what language is spoken in switzerland?
106
+ what was dr seuss's real name?
107
+ who plays elena gilbert on vampire diaries?
108
+ what are all the movies taylor swift has been in?
109
+ who plays charlie in the santa clause movies?
110
+ what produce does florida export?
111
+ where did kobe earthquake happen?
112
+ what record label is kelly clarkson signed with?
113
+ who has coached the carolina panthers?
114
+ what country is dyson made?
115
+ where does the columbia river start?
116
+ who are the u s senators of pennsylvania?
117
+ where did the russian japanese war happen?
118
+ what language is most commonly spoken in belgium?
119
+ where did joe flacco attend college?
120
+ what to do san jose ca?
121
+ where is the empire of ghana?
122
+ what did dmitri mendeleev discover in 1869?
123
+ where to get a marriage license in long island?
124
+ when does the world end according to the mayans time?
125
+ what do the symbols on the nevada flag mean?
126
+ where is perpignan located?
127
+ where is olympic national park wa?
128
+ when was the most recent earthquake in haiti?
129
+ what books are written by suzanne collins?
130
+ who is the president of peru now?
131
+ where did the israel palestine conflict start?
132
+ what are some ancient egypt names?
133
+ where is the fukushima daiichi nuclear plant located?
134
+ who is mary mcleod bethune for kids?
135
+ what character did billy d williams play in star wars?
136
+ what city is mt lassen in?
137
+ where do john lennon die?
138
+ when does daylight saving end in new zealand 2012?
139
+ where did spencer pratt go to school?
140
+ where was the temple of karnak built?
141
+ what did shakespeare become famous for?
142
+ what language do they speak in malta?
143
+ who did ricky martin started his career with?
144
+ what language did they speak in ghana?
145
+ who was dan white?
146
+ who does peter griffin voice?
147
+ where was benjamin franklin educated?
148
+ what does gm make?
149
+ who played lauren reed on alias?
150
+ who does donnie wahlberg play in the sixth sense?
151
+ where does marta play soccer?
152
+ where are the gobi desert located on a map?
153
+ where are the texas rangers playing?
154
+ what percent of americans have college degree?
155
+ where was country singer george jones born?
156
+ where is denmark situated?
157
+ where was osama bin laden killed?
158
+ what did shannon hoon die from?
159
+ what kind of government is sweden?
160
+ who or what influenced albert einstein?
161
+ what is arkansas state capitol?
162
+ where does kurdish people live?
163
+ who is the state governor of tennessee?
164
+ what sri lanka capital?
165
+ what political party did andrew johnson belong to?
166
+ where did mubarak get his wealth?
167
+ what team did aguero play for?
168
+ where did george michael go to school?
169
+ who plays london tipton in suite life on deck?
170
+ who is sir james dyson?
171
+ what city in florida has the lowest crime rate?
172
+ what team did ronaldo play for in 2003?
173
+ what year did houston rockets win their first championship?
174
+ what does monsanto own?
175
+ who was jesse james killed by?
176
+ what is the predominant religion in israel?
177
+ with which ancient ruler did julius caesar fall in love?
178
+ what kind of money should i take to costa rica?
179
+ where did paula deen go to school?
180
+ what highschool did r. kelly attend?
181
+ who is number 22 for the dallas cowboys?
182
+ when was the last time the orioles won the world series?
183
+ who did woody harrelson play on cheers?
184
+ what country did buddha come from?
185
+ what type of religion does argentina have?
186
+ what language do they in ghana?
187
+ what the largest city in spain?
188
+ who is khloe kardashian's husband?
189
+ what college did john nash teach at?
190
+ what stones albums did mick taylor play on?
191
+ what political party was hitler in?
192
+ what college did se hinton go?
193
+ what language is spoken in haiti today?
194
+ who plays king julian madagascar?
195
+ what state is saint louis university in?
196
+ where did george herbert walker bush go to college?
197
+ where is mount st helens volcano?
198
+ what did joan crawford died of?
199
+ what awards gary paulsen won?
200
+ who is eli whitney and what did he invent?
data/webq-train.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ae11a9dda6a3520cff42077063e7222e69650ea8087ae2686e34a957269fba3
3
+ size 205872205
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (135 Bytes). View file
 
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (138 Bytes). View file
 
utils/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (133 Bytes). View file
 
utils/__pycache__/retriever_utils.cpython-310.pyc ADDED
Binary file (5.51 kB). View file
 
utils/__pycache__/retriever_utils.cpython-38.pyc ADDED
Binary file (5.33 kB). View file
 
utils/__pycache__/retriever_utils.cpython-39.pyc ADDED
Binary file (5.39 kB). View file
 
utils/retriever_utils.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import glob
3
+ import json
4
+ import gzip
5
+ import logging
6
+ import functools
7
+ from pathlib import Path
8
+
9
+ import wandb
10
+ from typing import List, Tuple, Dict, Iterator, Union
11
+
12
+ from dpr.data.qa_validation import calculate_matches
13
+
14
+ logger = logging.getLogger()
15
+ logger.setLevel(logging.INFO)
16
+ if logger.hasHandlers():
17
+ logger.handlers.clear()
18
+ console = logging.StreamHandler()
19
+ logger.addHandler(console)
20
+
21
+ RECALL_FILE_NAME = "recall_at_k.csv"
22
+ RESULTS_FILE_NAME = "results.json"
23
+
24
+
25
+ def parse_qa_csv_file(location) -> Iterator[Tuple[str, List[str]]]:
26
+ with open(location) as ifile:
27
+ reader = csv.reader(ifile, delimiter="\t")
28
+ for row in reader:
29
+ question = row[0]
30
+ answers = eval(row[1])
31
+ yield question, answers
32
+
33
+
34
+ def parse_qa_json_file(path):
35
+ with open(path, "r") as f:
36
+ data = json.load(f)
37
+ for d in data:
38
+ question = d["question"]
39
+ answers = d["answers"]
40
+ if "entity" in d:
41
+ yield question, answers, d["entity"]
42
+ else:
43
+ yield question, answers
44
+
45
+ def validate(
46
+ dataset_name: str,
47
+ passages: Dict[object, Tuple[str, str]],
48
+ answers: List[List[str]],
49
+ result_ctx_ids: List[Tuple[List[object], List[float]]],
50
+ workers_num: int,
51
+ match_type: str,
52
+ out_file: str,
53
+ use_wandb: bool = True,
54
+ output_recall_at_k: bool = False,
55
+ log: bool = True
56
+ ) -> Union[List[List[bool]], Tuple[object, List[float]]]:
57
+ match_stats = calculate_matches(
58
+ passages, answers, result_ctx_ids, workers_num, match_type
59
+ )
60
+
61
+ top_k_hits = match_stats.top_k_hits
62
+ # if log: logger.info("Validation results: match_stats %s", match_stats)
63
+ # if log: logger.info("Validation results: top k documents hits %s", top_k_hits)
64
+ top_k_hits = [v / len(result_ctx_ids) for v in top_k_hits]
65
+ if log: logger.info("Validation results: top k documents hits accuracy %s", top_k_hits)
66
+ with open(out_file, "w") as f:
67
+ for k, recall in enumerate(top_k_hits):
68
+ f.write(f"{k+1},{recall}\n")
69
+ if use_wandb:
70
+ wandb.log({f"eval-{dataset_name}/k": k+1, f"eval-{dataset_name}/recall": recall})
71
+ if log: logger.info(f"Saved recall@k info to {out_file}")
72
+ return match_stats.questions_doc_hits if not output_recall_at_k else (match_stats.questions_doc_hits, top_k_hits)
73
+
74
+
75
+ def load_passages(ctx_file: str) -> Dict[object, Tuple[str, str]]:
76
+ docs = {}
77
+ logger.info("Reading data from: %s", ctx_file)
78
+ if ctx_file.endswith(".gz"):
79
+ with gzip.open(ctx_file, "rt") as tsvfile:
80
+ reader = csv.reader(
81
+ tsvfile,
82
+ delimiter="\t",
83
+ )
84
+ # file format: doc_id, doc_text, title
85
+ for row in reader:
86
+ if row[0] != "id":
87
+ docs[row[0]] = (row[1], row[2])
88
+ else:
89
+ with open(ctx_file) as tsvfile:
90
+ reader = csv.reader(
91
+ tsvfile,
92
+ delimiter="\t",
93
+ )
94
+ # file format: doc_id, doc_text, title
95
+ for row in reader:
96
+ if row[0] != "id":
97
+ docs[row[0]] = (row[1], row[2])
98
+ return docs
99
+
100
+
101
+ def save_results(
102
+ passages: Dict[object, Tuple[str, str]],
103
+ questions: List[str],
104
+ answers: List[List[str]],
105
+ top_passages_and_scores: List[Tuple[List[object], List[float]]],
106
+ per_question_hits: List[List[bool]],
107
+ out_file: str,
108
+ output_no_text: bool = False,
109
+ ):
110
+ # join passages text with the result ids, their questions and assigning has|no answer labels
111
+ merged_data = []
112
+ assert len(per_question_hits) == len(questions) == len(answers)
113
+ for i, q in enumerate(questions):
114
+ q_answers = answers[i]
115
+ results_and_scores = top_passages_and_scores[i]
116
+ hits = per_question_hits[i]
117
+ docs = [passages[doc_id] for doc_id in results_and_scores[0]]
118
+ scores = [str(score) for score in results_and_scores[1]]
119
+ hit_indices = [j+1 for j, is_hit in enumerate(hits) if is_hit]
120
+ hit_min_rank = hit_indices[0] if len(hit_indices) > 0 else None
121
+ ctxs_num = len(hits)
122
+
123
+ d = {
124
+ "question": q,
125
+ "answers": q_answers,
126
+ "hit_min_rank": hit_min_rank,
127
+ "all_hits": hit_indices,
128
+ "ctxs": [
129
+ {
130
+ "id": results_and_scores[0][c],
131
+ "rank": (c + 1),
132
+ "title": docs[c][1],
133
+ "text": docs[c][0] if not output_no_text else "",
134
+ "score": scores[c],
135
+ "has_answer": hits[c],
136
+ }
137
+ for c in range(ctxs_num)
138
+ ],
139
+ }
140
+ merged_data.append(d)
141
+
142
+ with open(out_file, "w") as writer:
143
+ writer.write(json.dumps(merged_data, indent=4) + "\n")
144
+ logger.info("Saved results * scores to %s", out_file)
145
+
146
+
147
+ def get_datasets(qa_file_pattern):
148
+ logger.info(f"Reading datasets usign the pattern {qa_file_pattern}")
149
+ all_patterns = qa_file_pattern.split(",")
150
+ all_qa_files = functools.reduce(lambda a, b: a + b, [glob.glob(pattern) for pattern in all_patterns])
151
+ qa_file_dict = {}
152
+ for qa_file in all_qa_files:
153
+ dataset_name = Path(qa_file).stem.replace(".", "-")
154
+ dataset = list(parse_qa_csv_file(qa_file)) if qa_file.endswith(".csv") else list(parse_qa_json_file(qa_file))
155
+ questions, question_answers = [], []
156
+ for ds_item in dataset:
157
+ question, answers = ds_item
158
+ questions.append(question)
159
+ question_answers.append(answers)
160
+ qa_file_dict[dataset_name] = (questions, question_answers)
161
+ logger.info(f"{dataset_name}:{' ' * (20 - len(dataset_name))}{len(questions)} items")
162
+
163
+ return qa_file_dict