qa_utils.py 8.01 KB
Newer Older
Baber's avatar
nit  
Baber committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright (c) 2024, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License


Baber's avatar
Baber committed
16
17
import itertools  # noqa: I001
import random
Baber's avatar
rename  
Baber committed
18
from functools import cache
Baber's avatar
Baber committed
19
20
21
22
23

import datasets
import requests
from tqdm import tqdm

Baber's avatar
Baber committed
24
from lm_eval.tasks.ruler.common_utils import DEFAULT_SEQ_LENGTHS, get_tokenizer
Baber's avatar
Baber committed
25

Baber's avatar
nit  
Baber committed
26
27
28
29
30
config = {
    "tokens_to_generate": 32,
    "template": """Answer the question based on the given documents. Only give me the answer and do not output any other words.\n\nThe following are given documents.\n\n{context}\n\nAnswer the question based on the given documents. Only give me the answer and do not output any other words.\n\nQuestion: {query}""",
    "answer_prefix": """ Answer:""",
}
Baber's avatar
Baber committed
31
32
33
34
35
36
SEED = 42
TEMPLATE = """Answer the question based on the given documents. Only give me the answer and do not output any other words.\n\nThe following are given documents.\n\n{context}\n\nAnswer the question based on the given documents. Only give me the answer and do not output any other words.\n\nQuestion: {query}"""
DOCUMENT_PROMPT = "Document {i}:\n{document}"


@cache
Baber's avatar
nit  
Baber committed
37
def download_json(url) -> dict:
Baber's avatar
Baber committed
38
39
40
41
42
43
    response = requests.get(url)
    response.raise_for_status()
    data = response.json()
    return data


Baber's avatar
Baber committed
44
@cache
Baber's avatar
nit  
Baber committed
45
46
47
def read_squad(
    url="https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json",
) -> tuple[list[dict], list[str]]:
Baber's avatar
Baber committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    data = download_json(url)
    total_docs = [p["context"] for d in data["data"] for p in d["paragraphs"]]
    total_docs = sorted(list(set(total_docs)))
    total_docs_dict = {c: idx for idx, c in enumerate(total_docs)}

    total_qas = []
    for d in data["data"]:
        more_docs = [total_docs_dict[p["context"]] for p in d["paragraphs"]]
        for p in d["paragraphs"]:
            for qas in p["qas"]:
                if not qas["is_impossible"]:
                    total_qas.append(
                        {
                            "query": qas["question"],
                            "outputs": [a["text"] for a in qas["answers"]],
                            "context": [total_docs_dict[p["context"]]],
                            "more_context": [
                                idx
                                for idx in more_docs
                                if idx != total_docs_dict[p["context"]]
                            ],
                        }
                    )

    return total_qas, total_docs


Baber's avatar
Baber committed
75
76
77
@cache
def read_hotpotqa(
    url="http://curtis.ml.cmu.edu/datasets/hotpot/hotpot_dev_distractor_v1.json",
Baber's avatar
nit  
Baber committed
78
) -> tuple[list[dict], list[str]]:
Baber's avatar
Baber committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    data = download_json(url)
    total_docs = [f"{t}\n{''.join(p)}" for d in data for t, p in d["context"]]
    total_docs = sorted(list(set(total_docs)))
    total_docs_dict = {c: idx for idx, c in enumerate(total_docs)}

    total_qas = []
    for d in data:
        total_qas.append(
            {
                "query": d["question"],
                "outputs": [d["answer"]],
                "context": [
                    total_docs_dict[f"{t}\n{''.join(p)}"] for t, p in d["context"]
                ],
            }
        )

    return total_qas, total_docs


Baber's avatar
Baber committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def generate_input_output(
    index: int, num_docs: int, qas: list[dict], docs: list[str]
) -> tuple[str, list[str]]:
    curr_q: str = qas[index]["query"]
    curr_a: list[str] = qas[index]["outputs"]
    curr_docs: list[int] = qas[index]["context"]
    curr_more: list[int] = qas[index].get("more_context", [])
    if num_docs < len(docs):
        if (num_docs - len(curr_docs)) > len(curr_more):
            addition_docs = [
                i for i, d in enumerate(docs) if i not in curr_docs + curr_more
            ]
            all_docs = (
                curr_docs
                + curr_more
                + random.sample(
                    addition_docs, max(0, num_docs - len(curr_docs) - len(curr_more))
                )
            )
        else:
            all_docs = curr_docs + random.sample(curr_more, num_docs - len(curr_docs))

        all_docs = [docs[idx] for idx in all_docs]
    else:
        all_docs = docs

    random.Random(SEED).shuffle(all_docs)

    context = "\n\n".join(
        [DOCUMENT_PROMPT.format(i=i + 1, document=d) for i, d in enumerate(all_docs)]
    )
    input_text = TEMPLATE.format(context=context, query=curr_q)
    return input_text, curr_a


def generate_samples(
    tokenizer,
    docs: list[str],
    qas: list[dict],
    max_seq_length: int,
    num_samples: int = 500,
    tokens_to_generate: int = 32,
    pre_samples: int = 0,
    incremental: int = 10,
    remove_newline_tab=False,
) -> list[dict]:
    write_jsons = []
    tokens_to_generate = tokens_to_generate

    # Find the perfect num_docs
    num_docs = incremental

    total_tokens = 0  # Track the total tokens generated for this example
    while total_tokens + tokens_to_generate < max_seq_length:
        input_text, answer = generate_input_output(0, num_docs, qas=qas, docs=docs)
        # Calculate the number of tokens in the example
        total_tokens = len(tokenizer(input_text + f" {answer}").input_ids)
Baber's avatar
cleanup  
Baber committed
156
157
158
        # print(
        #     f"Max length {max_seq_length} | Current length {total_tokens + tokens_to_generate} | Docs: {num_docs}"
        # )
Baber's avatar
Baber committed
159
160
161
162
163
164
165
166
        if total_tokens + tokens_to_generate > max_seq_length:
            num_docs -= incremental
            break

        num_docs += incremental
        if num_docs > len(docs):
            num_docs = len(docs)
            break
Baber's avatar
cleanup  
Baber committed
167
    # print("Number of documents:", num_docs)
Baber's avatar
Baber committed
168
169

    # Generate samples
Baber's avatar
cleanup  
Baber committed
170
171
172
    for index in tqdm(
        range(num_samples), desc=f"Generating QA Samples | {max_seq_length}"
    ):
Baber's avatar
Baber committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        used_docs = num_docs
        while True:
            try:
                input_text, answer = generate_input_output(
                    index + pre_samples, used_docs, qas=qas, docs=docs
                )
                length = len(tokenizer(input_text).input_ids) + tokens_to_generate
                assert length <= max_seq_length, f"{length} exceeds max_seq_length."
                break
            except:  # noqa: E722
                if used_docs > incremental:
                    used_docs -= incremental

        if remove_newline_tab:
            input_text = " ".join(
                input_text.replace("\n", " ").replace("\t", " ").strip().split()
            )

        formatted_output = {
            "index": index,
            "input": input_text,
            "outputs": answer,
            "length": length,
Baber's avatar
cleanup  
Baber committed
196
            "max_length": max_seq_length,
Baber's avatar
Baber committed
197
198
199
200
201
202
203
            "gen_prefix": "Answer:",
        }
        write_jsons.append(formatted_output)

    return write_jsons


Baber's avatar
cleanup  
Baber committed
204
def get_dataset(pretrained, docs, qas, max_seq_length=None, **kwargs) -> list[dict]:
Baber's avatar
Baber committed
205
206
207
208
209
210
    tokenizer = get_tokenizer(pretrained)
    write_jsons = generate_samples(
        tokenizer=tokenizer,
        docs=docs,
        qas=qas,
        num_samples=500,
Baber's avatar
nit  
Baber committed
211
        tokens_to_generate=32,
Baber's avatar
Baber committed
212
213
214
215
216
        max_seq_length=max_seq_length,
    )
    return write_jsons


Baber's avatar
cleanup  
Baber committed
217
def get_qa_dataset(ds, **kwargs) -> dict[str, datasets.Dataset]:
Baber's avatar
Baber committed
218
    pretrained = kwargs.get("tokenizer", kwargs.get("pretrained", {}))
Baber's avatar
Baber committed
219
220
221
222
    if ds == "squad":
        qas, docs = read_squad()
    else:
        qas, docs = read_hotpotqa()
Baber's avatar
Baber committed
223
    df = (
Baber's avatar
cleanup  
Baber committed
224
        get_dataset(pretrained=pretrained, docs=docs, qas=qas, max_seq_length=seq)
Baber's avatar
nit  
Baber committed
225
        for seq in kwargs.pop("max_seq_lengths", DEFAULT_SEQ_LENGTHS)
Baber's avatar
Baber committed
226
227
228
229
230
231
232
    )

    return {
        "test": datasets.Dataset.from_list(
            list(itertools.chain.from_iterable(df)), split=datasets.Split.TEST
        )
    }
Baber's avatar
Baber committed
233
234


Baber's avatar
rename  
Baber committed
235
236
237
238
239
240
def get_squad(**kwargs):
    return get_qa_dataset("squad", **kwargs)


def get_hotpotqa(**kwargs):
    return get_qa_dataset("hotpotqa", **kwargs)