|
| 1 | +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import argparse |
| 16 | +# import logging |
| 17 | +import os |
| 18 | +import sys |
| 19 | +import random |
| 20 | +import time |
| 21 | +import math |
| 22 | +import json |
| 23 | +from functools import partial |
| 24 | + |
| 25 | +import numpy as np |
| 26 | +import paddle |
| 27 | +from paddle.io import DataLoader |
| 28 | +import paddle.nn as nn |
| 29 | +import paddle.nn.functional as F |
| 30 | +from paddle.metric import Metric, Accuracy, Precision, Recall |
| 31 | + |
| 32 | +from paddlenlp.datasets import load_dataset |
| 33 | +from paddlenlp.data import Stack, Tuple, Pad, Dict |
| 34 | +from paddlenlp.transformers import BertForSequenceClassification, BertTokenizer |
| 35 | +from paddlenlp.transformers import ErnieForSequenceClassification, ErnieTokenizer |
| 36 | +from paddlenlp.transformers import RobertaForSequenceClassification, RobertaTokenizer |
| 37 | + |
| 38 | +METRIC_CLASSES = { |
| 39 | + "afqmc": Accuracy, |
| 40 | + "tnews": Accuracy, |
| 41 | + "iflytek": Accuracy, |
| 42 | + "ocnli": Accuracy, |
| 43 | + "cmnli": Accuracy, |
| 44 | + "cluewsc2020": Accuracy, |
| 45 | + "csl": Accuracy, |
| 46 | +} |
| 47 | + |
| 48 | +MODEL_CLASSES = { |
| 49 | + "bert": (BertForSequenceClassification, BertTokenizer), |
| 50 | + "ernie": (ErnieForSequenceClassification, ErnieTokenizer), |
| 51 | + "roberta": (RobertaForSequenceClassification, RobertaTokenizer), |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +def parse_args(): |
| 56 | + parser = argparse.ArgumentParser() |
| 57 | + |
| 58 | + # Required parameters |
| 59 | + parser.add_argument( |
| 60 | + "--task_name", |
| 61 | + default=None, |
| 62 | + type=str, |
| 63 | + required=True, |
| 64 | + help="The name of the task to train selected in the list: " + |
| 65 | + ", ".join(METRIC_CLASSES.keys()), ) |
| 66 | + parser.add_argument( |
| 67 | + "--model_type", |
| 68 | + default="ernie", |
| 69 | + type=str, |
| 70 | + help="Model type selected in the list: " + |
| 71 | + ", ".join(MODEL_CLASSES.keys()), ) |
| 72 | + parser.add_argument( |
| 73 | + "--model_name_or_path", |
| 74 | + default=None, |
| 75 | + type=str, |
| 76 | + required=True, |
| 77 | + help="Path to pre-trained model or shortcut name selected in the list: " |
| 78 | + + ", ".join( |
| 79 | + sum([ |
| 80 | + list(classes[-1].pretrained_init_configuration.keys()) |
| 81 | + for classes in MODEL_CLASSES.values() |
| 82 | + ], [])), ) |
| 83 | + parser.add_argument( |
| 84 | + "--output_dir", |
| 85 | + default="tmp", |
| 86 | + type=str, |
| 87 | + help="The output directory where the model predictions and checkpoints will be written.", |
| 88 | + ) |
| 89 | + |
| 90 | + parser.add_argument( |
| 91 | + "--max_seq_length", |
| 92 | + default=128, |
| 93 | + type=int, |
| 94 | + help="The maximum total input sequence length after tokenization. Sequences longer " |
| 95 | + "than this will be truncated, sequences shorter will be padded.", ) |
| 96 | + |
| 97 | + parser.add_argument( |
| 98 | + "--batch_size", |
| 99 | + default=128, |
| 100 | + type=int, |
| 101 | + help="Batch size per GPU/CPU for training.", ) |
| 102 | + |
| 103 | + parser.add_argument( |
| 104 | + "--device", |
| 105 | + default="gpu", |
| 106 | + type=str, |
| 107 | + help="The device to select to train the model, is must be cpu/gpu/xpu.") |
| 108 | + args = parser.parse_args() |
| 109 | + return args |
| 110 | + |
| 111 | + |
| 112 | +def convert_example(example, |
| 113 | + tokenizer, |
| 114 | + label_list, |
| 115 | + max_seq_length=512, |
| 116 | + is_test=False): |
| 117 | + """convert a glue example into necessary features""" |
| 118 | + if not is_test: |
| 119 | + # `label_list == None` is for regression task |
| 120 | + label_dtype = "int64" if label_list else "float32" |
| 121 | + # Get the label |
| 122 | + label = example['label'] |
| 123 | + label = np.array([label], dtype=label_dtype) |
| 124 | + # Convert raw text to feature |
| 125 | + if 'sentence' in example: |
| 126 | + example = tokenizer(example['sentence'], max_seq_len=max_seq_length) |
| 127 | + elif 'sentence1' in example: |
| 128 | + example = tokenizer( |
| 129 | + example['sentence1'], |
| 130 | + text_pair=example['sentence2'], |
| 131 | + max_seq_len=max_seq_length) |
| 132 | + elif 'keyword' in example: # CSL |
| 133 | + sentence1 = " ".join(example['keyword']) |
| 134 | + example = tokenizer( |
| 135 | + sentence1, text_pair=example['abst'], max_seq_len=max_seq_length) |
| 136 | + elif 'target' in example: # wsc |
| 137 | + text, query, pronoun, query_idx, pronoun_idx = example['text'], example[ |
| 138 | + 'target']['span1_text'], example['target']['span2_text'], example[ |
| 139 | + 'target']['span1_index'], example['target']['span2_index'] |
| 140 | + text_list = list(text) |
| 141 | + assert text[pronoun_idx:(pronoun_idx + len(pronoun) |
| 142 | + )] == pronoun, "pronoun: {}".format(pronoun) |
| 143 | + assert text[query_idx:(query_idx + len(query) |
| 144 | + )] == query, "query: {}".format(query) |
| 145 | + if pronoun_idx > query_idx: |
| 146 | + text_list.insert(query_idx, "_") |
| 147 | + text_list.insert(query_idx + len(query) + 1, "_") |
| 148 | + text_list.insert(pronoun_idx + 2, "[") |
| 149 | + text_list.insert(pronoun_idx + len(pronoun) + 2 + 1, "]") |
| 150 | + else: |
| 151 | + text_list.insert(pronoun_idx, "[") |
| 152 | + text_list.insert(pronoun_idx + len(pronoun) + 1, "]") |
| 153 | + text_list.insert(query_idx + 2, "_") |
| 154 | + text_list.insert(query_idx + len(query) + 2 + 1, "_") |
| 155 | + text = "".join(text_list) |
| 156 | + example = tokenizer(text, max_seq_len=max_seq_length) |
| 157 | + |
| 158 | + if not is_test: |
| 159 | + return example['input_ids'], example['token_type_ids'], label |
| 160 | + else: |
| 161 | + return example['input_ids'], example['token_type_ids'] |
| 162 | + |
| 163 | + |
| 164 | +def do_test(args): |
| 165 | + paddle.set_device(args.device) |
| 166 | + |
| 167 | + args.task_name = args.task_name.lower() |
| 168 | + metric_class = METRIC_CLASSES[args.task_name] |
| 169 | + args.model_type = args.model_type.lower() |
| 170 | + model_class, tokenizer_class = MODEL_CLASSES[args.model_type] |
| 171 | + train_ds, test_ds = load_dataset( |
| 172 | + 'clue', args.task_name, splits=('train', 'test')) |
| 173 | + tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) |
| 174 | + |
| 175 | + trans_func = partial( |
| 176 | + convert_example, |
| 177 | + tokenizer=tokenizer, |
| 178 | + label_list=train_ds.label_list, |
| 179 | + max_seq_length=args.max_seq_length, |
| 180 | + is_test=True) |
| 181 | + |
| 182 | + batchify_fn = lambda samples, fn=Tuple( |
| 183 | + Pad(axis=0, pad_val=tokenizer.pad_token_id), # input |
| 184 | + Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # segment |
| 185 | + ): fn(samples) |
| 186 | + |
| 187 | + test_ds = test_ds.map(trans_func, lazy=True) |
| 188 | + test_batch_sampler = paddle.io.BatchSampler( |
| 189 | + test_ds, batch_size=args.batch_size, shuffle=False) |
| 190 | + test_data_loader = DataLoader( |
| 191 | + dataset=test_ds, |
| 192 | + batch_sampler=test_batch_sampler, |
| 193 | + collate_fn=batchify_fn, |
| 194 | + num_workers=0, |
| 195 | + return_list=True) |
| 196 | + |
| 197 | + num_classes = 1 if train_ds.label_list == None else len(train_ds.label_list) |
| 198 | + model_class, _ = MODEL_CLASSES[args.model_type] |
| 199 | + model = model_class.from_pretrained( |
| 200 | + args.model_name_or_path, num_classes=num_classes) |
| 201 | + |
| 202 | + if not os.path.exists(args.output_dir): |
| 203 | + os.makedirs(args.output_dir) |
| 204 | + if args.task_name == 'ocnli': |
| 205 | + args.task_name = 'ocnli_50k' |
| 206 | + f = open( |
| 207 | + os.path.join(args.output_dir, args.task_name + "_predict.json"), 'w') |
| 208 | + |
| 209 | + for step, batch in enumerate(test_data_loader): |
| 210 | + input_ids, segment_ids = batch |
| 211 | + |
| 212 | + with paddle.no_grad(): |
| 213 | + logits = model(input_ids, segment_ids) |
| 214 | + |
| 215 | + preds = paddle.argmax(logits, axis=1) |
| 216 | + for idx, pred in enumerate(preds): |
| 217 | + j = json.dumps({"id": idx, "label": train_ds.label_list[pred]}) |
| 218 | + f.write(j + "\n") |
| 219 | + |
| 220 | + |
| 221 | +if __name__ == "__main__": |
| 222 | + args = parse_args() |
| 223 | + do_test(args) |
0 commit comments