theachyuttiwari commited on
Commit
53a7a2f
·
1 Parent(s): 3a1ca92

Upload create_dpr_training_from_faiss.py

Browse files
Files changed (1) hide show
  1. create_dpr_training_from_faiss.py +144 -0
create_dpr_training_from_faiss.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ import torch
5
+ from datasets import load_dataset
6
+ from tqdm.auto import tqdm
7
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
8
+ from transformers import DPRQuestionEncoder
9
+
10
+ from common import embed_questions, clean_question, articles_to_paragraphs, kilt_wikipedia_columns
11
+ from common import kilt_wikipedia_paragraph_columns as columns
12
+
13
+
14
+ def generate_dpr_training_file(args):
15
+ n_negatives = 7
16
+ min_chars_per_passage = 200
17
+
18
+ def query_index(question, topk=(n_negatives * args.n_positives) * 2):
19
+ question_embedding = embed_questions(question_model, question_tokenizer, [question])
20
+ scores, wiki_passages = kilt_wikipedia_paragraphs.get_nearest_examples("embeddings", question_embedding, k=topk)
21
+
22
+ retrieved_examples = []
23
+ r = list(zip(wiki_passages[k] for k in columns))
24
+ for i in range(topk):
25
+ retrieved_examples.append({k: v for k, v in zip(columns, [r[j][0][i] for j in range(len(columns))])})
26
+
27
+ return retrieved_examples
28
+
29
+ def find_positive_and_hard_negative_ctxs(dataset_index: int, n_positive=1, device="cuda:0"):
30
+ positive_context_list = []
31
+ hard_negative_context_list = []
32
+ example = dataset[dataset_index]
33
+ question = clean_question(example['title'])
34
+ passages = query_index(question)
35
+ passages = [dict([(k, p[k]) for k in columns]) for p in passages]
36
+ q_passage_pairs = [[question, f"{p['title']} {p['text']}" if args.use_title else p["text"]] for p in passages]
37
+
38
+ features = ce_tokenizer(q_passage_pairs, padding="max_length", max_length=256, truncation=True,
39
+ return_tensors="pt")
40
+ with torch.no_grad():
41
+ passage_scores = ce_model(features["input_ids"].to(device),
42
+ features["attention_mask"].to(device)).logits
43
+
44
+ for p_idx, p in enumerate(passages):
45
+ p["score"] = passage_scores[p_idx].item()
46
+
47
+ # order by scores
48
+ def score_passage(item):
49
+ return item["score"]
50
+
51
+ # pick the most relevant as the positive answer
52
+ best_passage_list = sorted(passages, key=score_passage, reverse=True)
53
+ for idx, item in enumerate(best_passage_list):
54
+ if idx < n_positive:
55
+ positive_context_list.append({"title": item["title"], "text": item["text"]})
56
+ else:
57
+ break
58
+
59
+ # least relevant as hard_negative
60
+ worst_passage_list = sorted(passages, key=score_passage, reverse=False)
61
+ for idx, hard_negative in enumerate(worst_passage_list):
62
+ if idx < n_negatives * n_positive:
63
+ hard_negative_context_list.append({"title": hard_negative["title"], "text": hard_negative["text"]})
64
+ else:
65
+ break
66
+ assert len(positive_context_list) * n_negatives == len(hard_negative_context_list)
67
+ return positive_context_list, hard_negative_context_list
68
+
69
+ device = ("cuda" if torch.cuda.is_available() else "cpu")
70
+
71
+ question_model = DPRQuestionEncoder.from_pretrained(args.question_encoder_name).to(device)
72
+ question_tokenizer = AutoTokenizer.from_pretrained(args.question_encoder_name)
73
+ _ = question_model.eval()
74
+
75
+ ce_model = AutoModelForSequenceClassification.from_pretrained('cross-encoder/ms-marco-MiniLM-L-4-v2').to(device)
76
+ ce_tokenizer = AutoTokenizer.from_pretrained('cross-encoder/ms-marco-MiniLM-L-4-v2')
77
+ _ = ce_model.eval()
78
+
79
+ kilt_wikipedia = load_dataset("kilt_wikipedia", split="full")
80
+
81
+ kilt_wikipedia_paragraphs = kilt_wikipedia.map(articles_to_paragraphs, batched=True,
82
+ remove_columns=kilt_wikipedia_columns,
83
+ batch_size=512,
84
+ cache_file_name=f"../data/wiki_kilt_paragraphs_full.arrow",
85
+ desc="Expanding wiki articles into paragraphs")
86
+
87
+ # use paragraphs that are not simple fragments or very short sentences
88
+ # Wikipedia Faiss index needs to fit into a 16 Gb GPU
89
+ kilt_wikipedia_paragraphs = kilt_wikipedia_paragraphs.filter(
90
+ lambda x: (x["end_character"] - x["start_character"]) > min_chars_per_passage)
91
+
92
+ kilt_wikipedia_paragraphs.load_faiss_index("embeddings", args.index_file_name, device=0)
93
+
94
+ eli5_train_set = load_dataset("vblagoje/lfqa", split="train")
95
+ eli5_validation_set = load_dataset("vblagoje/lfqa", split="validation")
96
+ eli5_test_set = load_dataset("vblagoje/lfqa", split="test")
97
+
98
+ for dataset_name, dataset in zip(["train", "validation", "test"], [eli5_train_set,
99
+ eli5_validation_set,
100
+ eli5_test_set]):
101
+
102
+ progress_bar = tqdm(range(len(dataset)), desc=f"Creating DPR formatted {dataset_name} file")
103
+ with open('eli5-dpr-' + dataset_name + '.jsonl', 'w') as fp:
104
+ for idx, example in enumerate(dataset):
105
+ negative_start_idx = 0
106
+ positive_context, hard_negative_ctxs = find_positive_and_hard_negative_ctxs(idx, args.n_positives,
107
+ device)
108
+ for pc in positive_context:
109
+ hnc = hard_negative_ctxs[negative_start_idx:negative_start_idx + n_negatives]
110
+ json.dump({"id": example["q_id"],
111
+ "question": clean_question(example["title"]),
112
+ "positive_ctxs": [pc],
113
+ "hard_negative_ctxs": hnc}, fp)
114
+ fp.write("\n")
115
+ negative_start_idx += n_negatives
116
+ progress_bar.update(1)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ parser = argparse.ArgumentParser(description="Creates DPR training file")
121
+ parser.add_argument(
122
+ "--use_title",
123
+ action="store_true",
124
+ help="If true, use title in addition to passage text for passage embedding",
125
+ )
126
+ parser.add_argument(
127
+ "--n_positives",
128
+ default=3,
129
+ help="Number of positive samples per question",
130
+ )
131
+ parser.add_argument(
132
+ "--question_encoder_name",
133
+ default="vblagoje/dpr-question_encoder-single-lfqa-base",
134
+ help="Question encoder to use",
135
+ )
136
+
137
+ parser.add_argument(
138
+ "--index_file_name",
139
+ default="../data/kilt_dpr_wikipedia_first.faiss",
140
+ help="Faiss index with passage embeddings",
141
+ )
142
+
143
+ main_args, _ = parser.parse_known_args()
144
+ generate_dpr_training_file(main_args)