File size: 11,670 Bytes
256a159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""Simple Dataset Reader."""

import random
from typing import Dict, List, Optional, Union

import torch
from datasets import Dataset, DatasetDict
from transformers import AutoTokenizer

from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.registry import ICL_DATASET_READERS
from opencompass.utils.types import (_check_dataset, _check_str,
                                     _check_type_list)


@ICL_DATASET_READERS.register_module()
class DatasetReader:
    """In-conext Learning Dataset Reader Class Generate an DatasetReader
    instance through 'dataset'.

    Attributes:
        dataset (:obj:`Dataset` or :obj:`DatasetDict`): The dataset to be read.
        input_columns (:obj:`List[str]` or :obj:`str`): A list of column names
            (a string of column name) in the dataset that represent(s) the
            input field.
        output_column (:obj:`str`): A column name in the dataset that
            represents the prediction field.
        input_template (:obj:`PromptTemplate`, optional): An instance of the
            :obj:`PromptTemplate` class, used to format the input field
            content during the retrieval process. (in some retrieval methods)
        output_template (:obj:`PromptTemplate`, optional): An instance of the
            :obj:`PromptTemplate` class, used to format the output field
            content during the retrieval process. (in some learnable retrieval
            methods)
        train_split (str): The name of the training split. Defaults to 'train'.
        train_range (int or float or str, optional): The size of the partial
            training dataset to load.
            If None, the entire training dataset will be loaded.
            If int or float, the random partial dataset will be loaded with the
            specified size.
            If str, the partial dataset will be loaded with the
            specified index list (e.g. "[:100]" for the first 100 examples,
            "[100:200]" for the second 100 examples, etc.). Defaults to None.
        test_split (str): The name of the test split. Defaults to 'test'.
        test_range (int or float or str, optional): The size of the partial
            test dataset to load.
            If None, the entire test dataset will be loaded.
            If int or float, the random partial dataset will be loaded with the
            specified size.
            If str, the partial dataset will be loaded with the
            specified index list (e.g. "[:100]" for the first 100 examples,
            "[100:200]" for the second 100 examples, etc.). Defaults to None.
    """
    dataset = None
    input_template = None
    output_template = None

    def __init__(self,
                 dataset: Union[Dataset, DatasetDict, str],
                 input_columns: Union[List[str], str],
                 output_column: Optional[str],
                 input_template: Optional[PromptTemplate] = None,
                 output_template: Optional[PromptTemplate] = None,
                 train_split: str = 'train',
                 train_range: Optional[Union[int, float, str]] = None,
                 test_split: str = 'test',
                 test_range: Optional[Union[int, float, str]] = None) -> None:
        self.input_columns = _check_type_list(input_columns, [List, str])
        if isinstance(self.input_columns, str):
            self.input_columns = self.input_columns.split()
        self.output_column = None
        if output_column:
            self.output_column = _check_str(output_column)

        train_range = _check_type_list(train_range, [None, int, float, str])
        test_range = _check_type_list(test_range, [None, int, float, str])

        if input_template is not None:
            self.input_template = PromptTemplate._check_prompt_template(
                input_template)
        if output_template is not None:
            self.output_template = PromptTemplate._check_prompt_template(
                output_template)

        self.dataset = _check_dataset(dataset)
        if isinstance(self.dataset, Dataset):
            self.dataset = DatasetDict({
                'train': self.dataset,
                'test': self.dataset
            })

        # Normalize the dataset so that it has only "train" and "test" splits.
        for origin_split, mapped_split, split_range in [[
                train_split, 'train', train_range
        ], [test_split, 'test', test_range]]:
            self.dataset[mapped_split] = load_partial_dataset(
                self.dataset[origin_split], size=split_range)

    def generate_input_field_prompt(self, entry: Dict) -> str:
        """Generate a prompt for the input field based on the provided
        :obj:`entry` data.

        Args:
            entry (:obj:`Dict`): A piece of data to be used for generating the
                prompt.

        Returns:
            :obj:`str`: The generated prompt.
        """
        prompt = None
        if self.input_template is None:
            prompt = ' '.join([str(entry[ctx]) for ctx in self.input_columns])
        else:
            prompt = self.input_template.generate_item(entry)
        return prompt

    def generate_input_field_corpus(self,
                                    dataset: Union[Dataset, DatasetDict],
                                    split: Optional[str] = None) -> List[str]:
        """Generate corpus for input field.

        Args:
            dataset (:obj:`Dataset` or :obj:`DatasetDict`): A
                :obj:`datasets.Dataset` or :obj:`datasets.DatasetDict`
                instance.
            split (:obj:`str`, optional): The split of the dataset to use. If
                :obj:`None`, the entire dataset will be used. Defaults to
                ``None``.

        Returns:
            :obj:`List[str]`: A list of generated input field prompts.
        """
        if split is not None:
            dataset = dataset[split]
        corpus = []
        for entry in dataset:
            corpus.append(self.generate_input_field_prompt(entry))
        return corpus

    def generate_output_field_prompt(self, entry: Dict) -> str:
        """Generate a prompt for the output field based on the provided
        :obj:`entry` data.

        Args:
            entry (:obj:`Dict`): A piece of data to be used for generating the
            prompt.

        Returns:
            :obj:`str`: The generated prompt.
        """
        prompt = None
        if self.output_template is None:
            prompt = str(entry[self.output_column])
        else:
            prompt = self.output_template.generate_item(entry)
        return prompt

    def generate_output_field_corpus(self,
                                     dataset: Union[Dataset, DatasetDict],
                                     split: Optional[str] = None) -> List[str]:
        """Generate corpus for output field.

        Args:
            dataset (:obj:`Dataset` or :obj:`DatasetDict`): A
                :obj:`datasets.Dataset` or :obj:`datasets.DatasetDict`
                instance.
            split (:obj:`str`, optional): The split of the dataset to use.
                If :obj:`None`, the entire dataset will be used. Defaults to
                ``None``.

        Returns:
            :obj:`List[str]`: A list of generated output field prompts.
        """
        if split is not None:
            dataset = dataset[split]
        corpus = []
        for entry in dataset:
            corpus.append(self.generate_output_field_prompt(entry))
        return corpus

    def generate_input_output_field_prompt(self, entry: Dict) -> str:
        """Generate a prompt for the input-output field based on the
        provided:obj:`entry` data.

        Args:
            entry (:obj:`Dict`): A piece of data to be used for generating the
            prompt.

        Returns:
            :obj:`str`: The generated prompt.
        """
        prompt = None
        if self.input_output_template is None:
            prompt = ' '.join([entry[ctx] for ctx in self.input_columns] +
                              [str(entry[self.output_column])])
        else:
            prompt = self.input_output_template.generate_item(entry)
        return prompt

    def _check_dataset_reader(obj) -> 'DatasetReader':
        if isinstance(obj, DatasetReader):
            return obj
        else:
            raise TypeError(f'Expected a DatasetReader object, but got {obj}')

    def __len__(self):
        return len(self.dataset)

    def __getitem__(self, idx):
        return self.dataset[idx]

    def __repr__(self):
        return (f'DatasetReader({{\n    dataset: {self.dataset},'
                f'\n    input_columns: {self.input_columns},\n'
                f'    output_columns: {self.output_column}\n}})')


def load_partial_dataset(
        dataset: Dataset,
        size: Optional[Union[int, float, str]] = None) -> Dataset:
    """Load a partial dataset.

    Args:
        dataset (Dataset): A :obj:`datasets.Dataset` instance.
        size (int or float or (int, int), optional): The size of the partial
            dataset to load. If None, the entire dataset will be loaded.
            If int or float, the random partial dataset will be loaded with the
            specified size. If str, the partial dataset will be loaded with the
            specified index list (e.g. "[:100]" for the first 100 examples,
            "[100:200]" for the second 100 examples, etc.). Defaults to None.
    """
    total_size = len(dataset)
    index_list = list(range(total_size))
    if isinstance(size, (int, float)):
        if size >= total_size or size <= 0:
            return dataset
        if size > 0 and size < 1:
            size = int(size * total_size)
        rand = random.Random(x=size)
        rand.shuffle(index_list)
        dataset = dataset.select(index_list[:size])
    elif isinstance(size, str):
        dataset = dataset.select(eval(f'index_list{size}'))
    return dataset


class DatasetEncoder(torch.utils.data.Dataset):

    def __init__(self,
                 datalist: List,
                 model_name=None,
                 tokenizer=None) -> None:
        self.datalist = datalist
        if model_name is None and tokenizer is None:
            raise ValueError('model_name and tokenizer could not both be None')
        if tokenizer is not None:
            self.tokenizer = tokenizer
        else:
            self.tokenizer = AutoTokenizer.from_pretrained(model_name)
            self.tokenizer.pad_token = self.tokenizer.eos_token
            self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
            self.tokenizer.padding_side = 'left'
        self.encode_dataset = []
        self.init_dataset()
        self.datalist_length = len(self.encode_dataset)

    def init_dataset(self):
        for idx, data in enumerate(self.datalist):
            tokenized_data = self.tokenizer.encode_plus(data,
                                                        truncation=True,
                                                        return_tensors='pt',
                                                        verbose=False)
            self.encode_dataset.append({
                'input_ids':
                tokenized_data.input_ids[0],
                'attention_mask':
                tokenized_data.attention_mask[0],
                'metadata': {
                    'id': idx,
                    'len': len(tokenized_data.input_ids[0]),
                    'text': data
                }
            })

    def __len__(self):
        return self.datalist_length

    def __getitem__(self, idx):
        return self.encode_dataset[idx]