File size: 12,337 Bytes
e841b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.

# Lint as: python3
"""CL_Benchmark Dataset."""

import json
import os
import random
from dataclasses import dataclass, field as dc_field
from typing import Optional
import datasets
from hashlib import md5

logger = datasets.logging.get_logger(__name__)
TASK_CONFIG_FILES = {"train": "train_tasks.json", "dev": "dev_tasks.json", "test": "test_tasks.json"}
INSTRUCTION_STRATEGIES = ['single', 'multiple']
ANSWER_PREFIX = "Output:"
SINGLE_QUOTES_SUBSTITUTE = "#$%#"
AUX_PROB = 0.3


def gen_cache_path(cache_dir, data_args):
    # Handle None: use empty string when data_dir/task_config_dir not provided
    data_dir = data_args.data_dir or ""
    task_config_dir = data_args.task_config_dir or ""
    hash_str = data_dir + task_config_dir + \
               str(data_args.max_num_instances_per_task) + str(data_args.max_num_instances_per_eval_task)
    hash_obj = md5(hash_str.encode("utf-8"))
    hash_id = hash_obj.hexdigest()
    cache_path = os.path.join(cache_dir, str(hash_id))

    return cache_path


def check_path(path):
    if not path or not os.path.exists(path):
        raise ValueError('{} is not valid, please check the input path!'.format(path))


def save_ds(instances, file_name):
    with open(file_name, "w+", encoding='utf-8') as fi:
        json.dump(instances, fi, ensure_ascii=False, indent=2)


@dataclass
class CLConfig(datasets.BuilderConfig):
    """
    Config dataset load procedure.

    Args:
        data_dir: task data dir, which contains the corresponding dataset dirs
        task_config_dir: directory with train/dev/test task config json files
        max_num_instances_per_task: max training sample size of each task
        max_num_instances_per_eval_task: max eval sample size of each task
    """
    task_config_dir: Optional[str] = None
    num_examples: Optional[int] = None
    max_num_instances_per_task: Optional[int] = None
    max_num_instances_per_eval_task: Optional[int] = None
    over_sampling: Optional[bool] = None

    @staticmethod
    def parse_task_config(task_config_dir):
        """Parse train/dev/test task config JSON files from the given directory."""
        if not task_config_dir:
            return None

        task_configs = {}
        for task, file_name in TASK_CONFIG_FILES.items():
            task_config_file = os.path.join(task_config_dir, file_name)

            if not os.path.exists(task_config_file):
                raise ValueError('Please check {} config, {} not exists!'.format(task, task_config_file))

            with open(task_config_file, 'r+') as f:
                task_configs[task] = json.loads(f.read())

        return task_configs


class CLInstructions(datasets.GeneratorBasedBuilder):
    """CL Dataset."""

    VERSION = datasets.Version("2.0.0")
    BUILDER_CONFIG_CLASS = CLConfig
    BUILDER_CONFIGS = [
        CLConfig(name="default", description="Default config for NaturalInstructions")
    ]
    DEFAULT_CONFIG_NAME = "default"

    def _info(self):
        return datasets.DatasetInfo(
            features=datasets.Features(
                {
                    "Task": datasets.Value("string"),
                    "Dataset": datasets.Value("string"),
                    "subset": datasets.Value("string"),
                    "Samples": [{
                        "id": datasets.Value("string"),
                        "sentence": datasets.Value("string"),
                        "label": datasets.Value("string"),
                        "ground_truth": datasets.Value("string")
                    }],
                    "Instance": {
                        "id": datasets.Value("string"),
                        "sentence": datasets.Value("string"),
                        "label": datasets.Value("string"),
                        "instruction": datasets.Value("string"),
                        "ground_truth": datasets.Value("string")
                    }
                }
            ),
            supervised_keys=None
        )


    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # Parse task configs lazily here (not in CLConfig) because datasets
        # may copy/replace the config object, dropping non-field attributes.
        task_configs = CLConfig.parse_task_config(self.config.task_config_dir)

        if self.config.data_dir is None or task_configs is None:
            logger.error("Please provide right input: data_dir or task_config_dir!")

        split_dir = self.config.data_dir

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "path": split_dir,
                    "task_config": task_configs['train'],
                    "max_num_instances_per_task": self.config.max_num_instances_per_task,
                    "subset": "train"
                }),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "path": split_dir,
                    "task_config": task_configs['dev'],
                    "max_num_instances_per_task": self.config.max_num_instances_per_eval_task,
                    "subset": "dev"
                }),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "path": split_dir,
                    "task_config": task_configs['test'],
                    "max_num_instances_per_task": None,  # default load total test samples to test
                    "subset": "test"
                }),
        ]


    def _load_dataset(self, dataset_path):
        with open(dataset_path, encoding="utf-8") as task_f:
            s = task_f.read()
            instances = json.loads(s)
        
        return instances
    
    def load_LongSeq_dataset(self, dataset_path, labels_path, dataset_name, sampling_strategy, max_num_instances, subset):

        data = self._load_dataset(dataset_path)
        print(list(data.keys()))
        input_mode='zeroshot'
        definition = ""
        if len(data["Definition"]) > 0:
            if input_mode=='fewshot' or input_mode=='zeroshot':
                if isinstance(data["Definition"], list):
                    definition = data["Definition"][0].strip() # TODO: should we use <Definition>?
                else:
                    definition = data["Definition"].strip()
                definition += "\n"

        sample_template = {"Task": "CL", "Dataset": dataset_name, "Samples": [], "subset": subset}

        for idx, instance in enumerate(data['Instances']):
            example = sample_template.copy()
            instruction = ""
            # add the input first.
            instruction += "{0}"
            instruction += "\n"
            instruction += "Output: "
            pos_examples = []
            if input_mode=='fewshot':
                for idx, pos_example in enumerate(data["Positive Examples"][:1]):
                    pos_example_str = f"Positive Example {idx+1} -\n"
                    pos_example_str += f"Input: {pos_example['input'].strip()}"
                    pos_example_str += "\n"
                    pos_example_str += f"Output: {pos_example['output'].strip()}"
                    pos_example_str += "\n" 
                    pos_examples.append(pos_example_str)

            instruction = definition + "".join(pos_examples) + instruction

            # print('-------------------')
            # print(instruction)
            # print('-------------------')

            if isinstance(instance["output"], list):
                label=instance["output"][random.randint(0, len(instance["output"])-1)]
            else:
                label=instance["output"]

            example["Instance"] = {
                "id": str(idx),
                "sentence": instance['input'],
                "label": label,
                "ground_truth": label,
                "instruction": instruction
            }

            yield example

    def load_SuperNI_dataset(self, dataset_path, labels_path, dataset_name, sampling_strategy, max_num_instances, subset):

        data = self._load_dataset(dataset_path)
        print(list(data.keys()))
        input_mode='zeroshot'
        definition = ""
        if input_mode=='fewshot' or input_mode=='zeroshot':
            if isinstance(data["Definition"], list):
                definition = "Definition: " + data["Definition"][0].strip() # TODO: should we use <Definition>?
            else:
                definition = "Definition: " + data["Definition"].strip()
            definition += "\n\n"

        sample_template = {"Task": "CL", "Dataset": dataset_name, "Samples": [], "subset": subset}

        for idx, instance in enumerate(data['Instances']):
            example = sample_template.copy()
            instruction = ""
            # add the input first.
            if input_mode=='fewshot' or input_mode=='zeroshot':
                instruction += "Now complete the following example -\n"
            instruction += "Input: {0}"
            instruction += "\n"
            instruction += "Output: "
            pos_examples = []
            if input_mode=='fewshot':
                for idx, pos_example in enumerate(data["Positive Examples"][:1]):
                    pos_example_str = f"Positive Example {idx+1} -\n"
                    pos_example_str += f"Input: {pos_example['input'].strip()}"
                    pos_example_str += "\n"
                    pos_example_str += f"Output: {pos_example['output'].strip()}"
                    pos_example_str += "\n" 
                    pos_examples.append(pos_example_str)

            instruction = definition + "".join(pos_examples) + instruction

            # print('-------------------')
            # print(instruction)
            # print('-------------------')

            if isinstance(instance["output"], list):
                label=instance["output"][random.randint(0, len(instance["output"])-1)]
            else:
                label=instance["output"]

            example["Instance"] = {
                "id": str(idx),
                "sentence": instance['input'],
                "label": label,
                "ground_truth": label,
                "instruction": instruction
            }

            yield example


    def _generate_examples(self, path=None, task_config=None, max_num_instances_per_task=None, subset=None):
        """Yields examples."""
        logger.info(f"Generating tasks from = {path}")

        for task in task_config:
            if task == 'SuperNI':
                load_func = self.load_SuperNI_dataset
            elif task == "Long_Sequence":
                load_func = self.load_LongSeq_dataset
            elif task == "Unseen":
                load_func = self.load_SuperNI_dataset
            else:
                raise ValueError("Unsupport {} task, plz check {} task config!".format(task, subset))

            # load dataset
            for dataset in task_config[task]:
                ds_name = dataset["dataset name"]
                sampling_strategy = dataset.get("sampling strategy", "random")
                ds_path = os.path.join(path, task, ds_name, subset + '.json')
                print(ds_path)
                labels_path = None
                assert os.path.exists(ds_path)

                idx = -1
                instances = []
                for sample in load_func(ds_path, labels_path, ds_name, sampling_strategy, max_num_instances_per_task,
                                        subset):
                    idx += 1
                    instances.append(sample)
                    yield f"{task}##{ds_path}##{idx}", sample