9
from transformers import RobertaTokenizer, RobertaForMaskedLM, RobertaForSequenceClassification
10
from transformers.modeling_roberta import RobertaForMaskedLMDomainTask
11
from tqdm import tqdm, trange
12
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
13
from torch.utils.data.distributed import DistributedSampler
14
from transformers.file_utils import PYTORCH_PRETRAINED_BERT_CACHE
15
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
19
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
20
datefmt = '%m/%d/%Y %H:%M:%S',
22
logger = logging.getLogger(__name__)
24
def accuracy(out, labels):
25
outputs = np.argmax(out, axis=1)
26
return np.sum(outputs == labels), outputs
28
class InputFeatures(object):
29
"""A single set of features of data."""
31
def __init__(self, input_ids=None, attention_mask=None, segment_ids=None, label_id=None):
32
self.input_ids = input_ids
33
self.attention_mask = attention_mask
34
self.segment_ids = segment_ids
35
self.label_id = label_id
37
class InputExample(object):
38
"""A single training/test example for simple sequence classification."""
39
def __init__(self, guid, sentence, aspect, sentiment=None):
40
"""Constructs a InputExample.
43
guid: Unique id for the example.
44
text_a: string. The untokenized text of the first sequence. For single
45
sequence tasks, only this sequence must be specified.
46
text_b: (Optional) string. The untokenized text of the second sequence.
47
Only must be specified for sequence pair tasks.
48
label: (Optional) string. The label of the example. This should be
49
specified for train and dev examples, but not for test examples.
52
self.sentence = sentence
54
self.sentiment = sentiment
57
class DataProcessor(object):
58
"""Base class for data converters for sequence classification data sets."""
60
def get_train_examples(self, data_dir):
61
"""Gets a collection of `InputExample`s for the train set."""
62
raise NotImplementedError()
64
def get_dev_examples(self, data_dir):
65
"""Gets a collection of `InputExample`s for the dev set."""
66
raise NotImplementedError()
69
"""Gets the list of labels for this data set."""
70
raise NotImplementedError()
73
def _read_json(cls, input_file):
74
with open(input_file, "r", encoding='utf-8') as f:
75
return json.loads(f.read())
78
class Processor_1(DataProcessor):
79
"""Processor for the CoLA data set (GLUE version)."""
81
def get_train_examples(self, data_dir):
83
examples = self._create_examples(
84
self._read_json(os.path.join(data_dir, "train.json")), "train")
85
aspect = set([x.aspect for x in examples])
86
sentiment = set([x.sentiment for x in examples])
87
return examples, list(aspect), list(sentiment)
89
def get_dev_examples(self, data_dir):
91
examples = self._create_examples(
92
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
93
aspect = set([x.aspect for x in examples])
94
sentiment = set([x.sentiment for x in examples])
95
return examples, list(aspect), list(sentiment)
97
def get_test_examples(self, data_dir):
99
examples = self._create_examples(
100
self._read_json(os.path.join(data_dir, "test.json")), "test")
101
aspect = set([x.aspect for x in examples])
102
sentiment = set([x.sentiment for x in examples])
103
return examples, list(aspect), list(sentiment)
105
def get_labels(self):
109
def _create_examples(self, lines, set_type):
110
"""Creates examples for the training and dev sets."""
112
for (i, line) in enumerate(lines):
113
guid = "%s-%s" % (set_type, i)
115
sentence = line["sentence"]
116
aspect = line["aspect"]
117
sentiment = line["sentiment"]
120
InputExample(guid=guid, sentence=sentence, aspect=aspect, sentiment=sentiment))
123
def convert_examples_to_features(examples, aspect_list, sentiment_list, max_seq_length, tokenizer, task_n):
125
"""Loads a data file into a list of `InputBatch`s."""
130
label_list = sorted(aspect_list)
132
label_list = sorted(sentiment_list)
137
print(w,tokenizer.encode(w))
140
label_map = {label : i for i, label in enumerate(label_list)}
144
for (ex_index, example) in enumerate(examples):
148
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
149
model = GPT2Model.from_pretrained('gpt2')
150
special_tokens_dict = {'cls_token': '<CLS>'}
151
num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
152
print('We have added', num_added_toks, 'tokens')
153
model.resize_token_embeddings(len(tokenizer))
157
print(tokenizer.all_special_tokens)
158
print(tokenizer.encode(tokenizer.all_special_tokens))
159
#['[PAD]', '[SEP]', '[CLS]', '[MASK]', '[UNK]']
160
#[ 0, 102, 101, 103, 100]
186
input_ids = tokenizer.encode(example.sentence,add_special_tokens=True)
188
next_input = tokenizer.encode(example.aspect,add_special_tokens=False)
190
next_input = [3] + next_input + [2]
191
input_ids+=next_input
193
segment_ids = [0] * len(input_ids)
198
input_ids += input_ids + [102]
199
#sentiment: word (Next sentence)
200
#segment_ids += [1] * (len(tokens_b) + 1)
207
attention_mask = [1] * len(input_ids)
210
padding = [0] * (max_seq_length - len(input_ids))
212
attention_mask += padding
213
segment_ids += padding
215
if len(input_ids) != max_seq_length:
216
print("input_ids more than max_seq_length")
218
assert len(input_ids) == max_seq_length
219
if len(attention_mask) != max_seq_length:
220
print("attention_mask more than max_seq_length")
222
assert len(attention_mask) == max_seq_length
223
if len(segment_ids) != max_seq_length:
224
print("segment_ids more than max_seq_length")
226
assert len(segment_ids) == max_seq_length
230
label_id = label_map[example.aspect]
232
label_id = label_map[example.sentiment]
239
InputFeatures(input_ids=input_ids,
240
attention_mask=attention_mask,
245
InputFeatures(input_ids=input_ids,
246
attention_mask=attention_mask,
247
segment_ids=segment_ids,
250
print("Wrong in convert_examples")
257
parser = argparse.ArgumentParser()
260
parser.add_argument("--data_dir",
264
help="The input data dir. Should contain the .tsv files (or other data files) for the task.")
265
parser.add_argument("--output_dir",
269
help="The output directory where the model predictions and checkpoints will be written.")
270
parser.add_argument("--pretrain_model",
271
default='bert-case-uncased',
274
help="Pre-trained model")
275
parser.add_argument("--num_labels_task",
276
default=None, type=int,
278
help="num_labels_task")
279
parser.add_argument("--max_seq_length",
282
help="The maximum total input sequence length after WordPiece tokenization. \n"
283
"Sequences longer than this will be truncated, and sequences shorter \n"
284
"than this will be padded.")
285
parser.add_argument("--do_train",
288
help="Whether to run training.")
289
parser.add_argument("--do_eval",
292
help="Whether to run eval on the dev set.")
293
parser.add_argument("--do_lower_case",
296
help="Set this flag if you are using an uncased model.")
297
parser.add_argument("--eval_batch_size",
300
help="Total batch size for training.")
301
parser.add_argument("--learning_rate",
304
help="The initial learning rate for Adam.")
305
parser.add_argument("--num_train_epochs",
308
help="Total number of training epochs to perform.")
309
parser.add_argument("--warmup_proportion",
312
help="Proportion of training to perform linear learning rate warmup for. "
313
"E.g., 0.1 = 10%% of training.")
314
parser.add_argument("--no_cuda",
317
help="Whether not to use CUDA when available")
318
parser.add_argument("--local_rank",
321
help="local_rank for distributed training on gpus")
322
parser.add_argument('--seed',
325
help="random seed for initialization")
326
parser.add_argument('--gradient_accumulation_steps',
329
help="Number of updates steps to accumulate before performing a backward/update pass.")
330
parser.add_argument('--fp16',
333
help="Whether to use 16-bit float precision instead of 32-bit")
334
parser.add_argument('--loss_scale',
335
type=float, default=0,
336
help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
337
"0 (default value): dynamic loss scaling.\n"
338
"Positive power of 2: static loss scaling value.\n")
339
parser.add_argument("--weight_decay",
342
help="Weight decay if we apply some.")
343
parser.add_argument("--adam_epsilon",
346
help="Epsilon for Adam optimizer.")
347
parser.add_argument("--max_grad_norm",
350
help="Max gradient norm.")
351
parser.add_argument('--fp16_opt_level',
354
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
355
"See details at https://nvidia.github.io/apex/amp.html")
356
parser.add_argument("--task",
363
args = parser.parse_args()
367
processors = Processor_1
369
num_labels = args.num_labels_task
371
if args.local_rank == -1 or args.no_cuda:
372
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
373
n_gpu = torch.cuda.device_count()
375
torch.cuda.set_device(args.local_rank)
376
device = torch.device("cuda", args.local_rank)
379
torch.distributed.init_process_group(backend='nccl')
380
logger.info("device: {}, n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
381
device, n_gpu, bool(args.local_rank != -1), args.fp16))
385
if args.gradient_accumulation_steps < 1:
386
raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
387
args.gradient_accumulation_steps))
391
random.seed(args.seed)
392
np.random.seed(args.seed)
393
torch.manual_seed(args.seed)
395
torch.cuda.manual_seed_all(args.seed)
398
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
401
if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:
402
raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
404
os.makedirs(args.output_dir, exist_ok=True)
408
tokenizer = RobertaTokenizer.from_pretrained(args.pretrain_model)
411
train_examples = None
412
num_train_steps = None
414
sentiment_list = None
415
processor = processors()
416
num_labels = num_labels
419
filenames = os.listdir(args.output_dir)
420
filenames = [x for x in filenames if "pytorch_model.bin_" in x]
424
file_mark.append([x, True])
425
file_mark.append([x, False])
429
test_examples, aspect_list, sentiment_list = processor.get_test_examples(args.data_dir)
431
num_labels = len(aspect_list)
433
num_labels = len(sentiment_list)
435
print("What's task?")
437
test = convert_examples_to_features(
438
test_examples, aspect_list, sentiment_list, args.max_seq_length, tokenizer, args.task)
439
eval_examples = test_examples
443
for x, mark in file_mark:
445
output_model_file = os.path.join(args.output_dir, x)
446
print(output_model_file)
448
model = RobertaForSequenceClassification.from_pretrained(args.pretrain_model, num_labels=num_labels, output_hidden_states=False, output_attentions=False, return_dict=True)
449
model.load_state_dict(torch.load(output_model_file), strict=False)
463
logger.info("***** Running evaluation *****")
464
logger.info(" Num examples = %d", len(eval_examples))
465
logger.info(" Batch size = %d", args.eval_batch_size)
468
all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
469
all_attention_mask = torch.tensor([f.attention_mask for f in eval_features], dtype=torch.long)
471
print("Excuting the task 1")
473
all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
477
all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)
480
eval_data = TensorDataset(all_input_ids, all_attention_mask, all_label_ids)
482
eval_data = TensorDataset(all_input_ids, all_attention_mask, all_segment_ids, all_label_ids)
486
if args.local_rank == -1:
487
eval_sampler = RandomSampler(eval_data)
489
eval_sampler = DistributedSampler(eval_data)
490
eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
493
output_eval_file = os.path.join(args.output_dir, "eval_results_{}.txt".format(x.split("_")[-1]))
494
output_file_pred = os.path.join(args.output_dir, "eval_pred_{}.txt".format(x.split("_")[-1]))
495
output_file_glod = os.path.join(args.output_dir, "eval_gold_{}.txt".format(x.split("_")[-1]))
497
output_eval_file = os.path.join(args.output_dir, "test_results_{}.txt".format(x.split("_")[-1]))
498
output_file_pred = os.path.join(args.output_dir, "test_pred_{}.txt".format(x.split("_")[-1]))
499
output_file_glod = os.path.join(args.output_dir, "test_gold_{}.txt".format(x.split("_")[-1]))
501
fpred = open(output_file_pred, "w")
502
fgold = open(output_file_glod, "w")
505
eval_loss, eval_accuracy = 0, 0
506
nb_eval_steps, nb_eval_examples = 0, 0
509
for step, batch in enumerate(tqdm(eval_dataloader, desc="Iteration")):
511
batch = tuple(t.to(device) for i, t in enumerate(batch))
514
input_ids, attention_mask, label_ids = batch
516
input_ids, attention_mask, segment_ids, label_ids = batch
523
output = model(input_ids=input_ids, token_type_ids=None, attention_mask=attention_mask, labels=label_ids)
524
logits = output.logits
525
tmp_eval_loss = output.loss
528
output = model(input_ids=input_ids, token_type_ids=segment_ids, attention_mask=attention_mask, labels=label_ids)
529
logits = output.logits
530
tmp_eval_loss = output.loss
535
logits = logits.detach().cpu().numpy()
536
label_ids = label_ids.to('cpu').numpy()
537
tmp_eval_accuracy, pred = accuracy(logits, label_ids)
538
for a, b in zip(pred, label_ids):
539
fgold.write("{}\n".format(b))
540
fpred.write("{}\n".format(a))
542
eval_loss += tmp_eval_loss.mean().item()
543
eval_accuracy += tmp_eval_accuracy
545
nb_eval_examples += input_ids.size(0)
548
eval_loss = eval_loss / nb_eval_steps
549
eval_accuracy = eval_accuracy / nb_eval_examples
551
result = {'eval_loss': eval_loss,
552
'eval_accuracy': eval_accuracy
555
with open(output_eval_file, "w") as writer:
556
logger.info("***** Eval results *****")
557
for key in sorted(result.keys()):
558
logger.info(" %s = %s", key, str(result[key]))
559
writer.write("%s = %s\n" % (key, str(result[key])))
563
if __name__ == "__main__":