Views
No views yet
1import datasets
2canard_train_augm = datasets.load_dataset("gaussalgo/Canard_Wiki-augmented", split="train") # see the dataset card for details
3canard_test_augm = datasets.load_dataset("gaussalgo/Canard_Wiki-augmented", split="test")
4
5canard_df = canard_train_augm.to_pandas()
6canard_test_df = canard_train_augm.to_pandas()
7
8### Curation of seq2seq input contexts and labels
9import random
10
11def input_context_from_sample(row: dict, max_length=5) -> str:
12 context = "Previous conversation:"
13 context += "\nQuestion: "
14 context += ", ".join(row["History"][:3])
15 for i in range(3, len(row["History"]), 2):
16 context += "\nAnswer: "
17 context += row["History"][i]
18 if i+1 < len(row["History"]):
19 context += "\nQuestion: "
20 context += row["History"][i+1]
21
22 context += "\n\nCurrent Question: "
23 context += row["Question"]
24
25 context += "\nSearch results:"
26 all_contexts = row["retrieved_contexts"].tolist()[:max_length-1] + [row["true_contexts"]]
27 random.shuffle(all_contexts)
28
29 for i, search_result in enumerate(all_contexts):
30 context += "\n[%s]: " % (i+1)
31 context += search_result.replace("CANNOTANSWER", "")
32
33 context += "\nCurrent Answer: "
34 return context
35
36
37def rephrasing_context_from_sample(row: dict) -> str:
38 context = "Previous conversation:"
39 context += "\nQuestion: "
40 context += ", ".join(row["History"][:3])
41 for i in range(3, len(row["History"]), 2):
42 context += "\nAnswer: "
43 context += row["History"][i]
44 if i+1 < len(row["History"]):
45 context += "\nQuestion: "
46 context += row["History"][i+1]
47
48 context += "\n\nCurrent Question: "
49 context += row["Question"]
50
51 context += "\nMore specific question: "
52 return context
53
54
55def hotpotqa_context(row: dict) -> str:
56 context = "Current Question: "
57 context += row["question"]
58
59 context += "\nSearch results:"
60 all_contexts = [" ".join(context) for context in row["context"]["sentences"]]
61
62 for i, search_result in enumerate(all_contexts):
63 context += "\n[%s]: " % (i+1)
64 # context += search_result.replace("CANNOTANSWER", "")
65
66 context += "\nCurrent Answer: "
67 return context
68
69
70input_texts = canard_df.apply(lambda row: input_context_from_sample(row), axis=1).values
71input_val_texts = canard_test_df.iloc[:200].apply(lambda row: input_context_from_sample(row), axis=1).values
72
73too_long_index = [len(t) > 20000 for t in input_texts]
74input_texts = [t for i, t in enumerate(input_texts) if not too_long_index[i]]
75print("training on %s samples" % len(input_texts))
76
77labels = canard_df.answer.apply(lambda ans: "No answer" if ans == "CANNOTANSWER" else ans).values
78labels = [l for i, l in enumerate(labels) if not too_long_index[i]]
79
80val_labels = canard_test_df.answer.apply(lambda ans: "No answer" if ans == "CANNOTANSWER" else ans).values
81
82rephrasing_inputs = canard_df.apply(lambda row: rephrasing_context_from_sample(row), axis=1).values
83print(rephrasing_inputs[0])
84
85rephrasing_val_inputs = canard_test_df.apply(lambda row: rephrasing_context_from_sample(row), axis=1).values
86
87rephrasing_labels = canard_df.Rewrite.values
88rephrasing_val_labels = canard_test_df.Rewrite.values
89print(rephrasing_labels[0])
90
91# Training
92# see Adaptor's homepage for details:
93# https://github.com/gaussalgo/adaptor
94
95from adaptor.lang_module import LangModule
96
97lang_module = LangModule("google/t5-large-lm-adapt")
98
99from adaptor.evaluators.generative import ROUGE, BLEU
100
101evaluators = [BLEU(), ROUGE()]
102
103from adaptor.objectives.seq2seq import Sequence2Sequence
104
105seq_qa = Sequence2Sequence(lang_module,
106 texts_or_path=input_texts,
107 labels_or_path=labels,
108 val_texts_or_path=input_val_texts,
109 val_labels_or_path=val_labels,
110 batch_size=4,
111 val_evaluators=evaluators,
112 objective_id="Canard")
113
114hotpot_train = datasets.load_dataset("hotpot_qa", "distractor")["train"]
115hotpot_val = datasets.load_dataset("hotpot_qa", "distractor")["validation"]
116
117hotpot_inputs = hotpot_train.to_pandas().apply(hotpotqa_context, axis=1)
118hotpot_val_inputs = hotpot_val.to_pandas().apply(hotpotqa_context, axis=1)
119
120too_long_index = [len(t) > 20000 for t in hotpot_inputs]
121
122hotpot_inputs = [t for i, t in enumerate(hotpot_inputs) if not too_long_index[i]]
123hotpot_answers = [t for i, t in enumerate(hotpot_train["answer"]) if not too_long_index[i]]
124
125seq_additional_qa = Sequence2Sequence(lang_module,
126 texts_or_path=hotpot_inputs,
127 labels_or_path=hotpot_answers,
128 val_texts_or_path=hotpot_val_inputs[:200],
129 val_labels_or_path=hotpot_val["answer"][:200],
130 batch_size=4,
131 val_evaluators=evaluators,
132 objective_id="HotpotQA",
133 share_other_objective_head=seq_qa)
134
135
136seq_rephrasing = Sequence2Sequence(lang_module,
137 texts_or_path=rephrasing_inputs,
138 labels_or_path=rephrasing_labels,
139 val_texts_or_path=rephrasing_val_inputs[:200],
140 val_labels_or_path=rephrasing_val_labels[:200],
141 batch_size=4,
142 val_evaluators=evaluators,
143 objective_id="rephrasing",
144 share_other_objective_head=seq_qa)
145
146from adaptor.utils import AdaptationArguments, StoppingStrategy
147
148training_arguments = AdaptationArguments(output_dir="checkpoints-chatbot",
149 learning_rate=5e-5,
150 stopping_strategy=StoppingStrategy.ALL_OBJECTIVES_CONVERGED,
151 stopping_patience=8,
152 save_total_limit=8,
153 do_train=True,
154 do_eval=True,
155 bf16=True,
156 warmup_steps=1000,
157 gradient_accumulation_steps=8,
158 logging_steps=10,
159 eval_steps=200,
160 save_steps=1000,
161 num_train_epochs=10,
162 evaluation_strategy="steps")
163
164from adaptor.schedules import ParallelSchedule
165from adaptor.adapter import Adapter
166
167schedule = ParallelSchedule(objectives=[seq_qa, seq_additional_qa, seq_rephrasing],
168 args=training_arguments)
169adapter = Adapter(lang_module, schedule, args=training_arguments)
170
171adapter.train()