10
from transformers import RobertaTokenizer, RobertaForMaskedLM, RobertaForSequenceClassification
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
26
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
27
datefmt = '%m/%d/%Y %H:%M:%S',
29
logger = logging.getLogger(__name__)
32
class InputFeatures(object):
33
"""A single set of features of data."""
35
def __init__(self, input_ids=None, attention_mask=None, segment_ids=None, label_id=None):
36
self.input_ids = input_ids
37
self.attention_mask = attention_mask
38
self.segment_ids = segment_ids
39
self.label_id = label_id
41
class InputExample(object):
42
"""A single training/test example for simple sequence classification."""
43
def __init__(self, guid, sentence, aspect, sentiment=None):
44
"""Constructs a InputExample.
47
guid: Unique id for the example.
48
text_a: string. The untokenized text of the first sequence. For single
49
sequence tasks, only this sequence must be specified.
50
text_b: (Optional) string. The untokenized text of the second sequence.
51
Only must be specified for sequence pair tasks.
52
label: (Optional) string. The label of the example. This should be
53
specified for train and dev examples, but not for test examples.
56
self.sentence = sentence
58
self.sentiment = sentiment
61
class DataProcessor(object):
62
"""Base class for data converters for sequence classification data sets."""
64
def get_train_examples(self, data_dir):
65
"""Gets a collection of `InputExample`s for the train set."""
66
raise NotImplementedError()
68
def get_dev_examples(self, data_dir):
69
"""Gets a collection of `InputExample`s for the dev set."""
70
raise NotImplementedError()
73
"""Gets the list of labels for this data set."""
74
raise NotImplementedError()
77
def _read_json(cls, input_file):
78
with open(input_file, "r", encoding='utf-8') as f:
79
return json.loads(f.read())
82
class Processor_1(DataProcessor):
83
"""Processor for the CoLA data set (GLUE version)."""
85
def get_train_examples(self, data_dir):
87
examples = self._create_examples(
88
self._read_json(os.path.join(data_dir, "train.json")), "train")
89
aspect = set([x.aspect for x in examples])
90
sentiment = set([x.sentiment for x in examples])
91
return examples, list(aspect), list(sentiment)
93
def get_dev_examples(self, data_dir):
95
examples = self._create_examples(
96
self._read_json(os.path.join(data_dir, "dev.json")), "dev")
97
aspect = set([x.aspect for x in examples])
98
sentiment = set([x.sentiment for x in examples])
99
return examples, list(aspect), list(sentiment)
101
def get_dev_examples(self, data_dir):
102
"""See base class."""
103
examples = self._create_examples(
104
self._read_json(os.path.join(data_dir, "test.json")), "test")
105
aspect = set([x.aspect for x in examples])
106
sentiment = set([x.sentiment for x in examples])
107
return examples, list(aspect), list(sentiment)
109
def get_labels(self):
113
def _create_examples(self, lines, set_type):
114
"""Creates examples for the training and dev sets."""
116
for (i, line) in enumerate(lines):
117
guid = "%s-%s" % (set_type, i)
119
sentence = line["sentence"]
120
aspect = line["aspect"]
121
sentiment = line["sentiment"]
124
InputExample(guid=guid, sentence=sentence, aspect=aspect, sentiment=sentiment))
127
def convert_examples_to_features(examples, aspect_list, sentiment_list, max_seq_length, tokenizer, task_n):
129
"""Loads a data file into a list of `InputBatch`s."""
134
label_list = sorted(aspect_list)
136
label_list = sorted(sentiment_list)
141
print(w,tokenizer.encode(w))
144
label_map = {label : i for i, label in enumerate(label_list)}
148
for (ex_index, example) in enumerate(examples):
152
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
153
model = GPT2Model.from_pretrained('gpt2')
154
special_tokens_dict = {'cls_token': '<CLS>'}
155
num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
156
print('We have added', num_added_toks, 'tokens')
157
model.resize_token_embeddings(len(tokenizer))
161
print(tokenizer.all_special_tokens)
162
print(tokenizer.encode(tokenizer.all_special_tokens))
163
#['[PAD]', '[SEP]', '[CLS]', '[MASK]', '[UNK]']
164
#[ 0, 102, 101, 103, 100]
190
input_ids = tokenizer.encode(example.sentence,add_special_tokens=True)
191
segment_ids = [0] * len(input_ids)
196
input_ids += input_ids + [102]
204
attention_mask = [1] * len(input_ids)
207
padding = [0] * (max_seq_length - len(input_ids))
209
attention_mask += padding
210
segment_ids += padding
212
assert len(input_ids) == max_seq_length
213
assert len(attention_mask) == max_seq_length
214
assert len(segment_ids) == max_seq_length
217
label_id = label_map[example.aspect]
219
label_id = label_map[example.sentiment]
226
InputFeatures(input_ids=input_ids,
227
attention_mask=attention_mask,
232
InputFeatures(input_ids=input_ids,
233
attention_mask=attention_mask,
234
segment_ids=segment_ids,
237
print("Wrong in convert_examples")
244
parser = argparse.ArgumentParser()
247
parser.add_argument("--data_dir",
251
help="The input data dir. Should contain the .tsv files (or other data files) for the task.")
252
parser.add_argument("--output_dir",
256
help="The output directory where the model predictions and checkpoints will be written.")
257
parser.add_argument("--pretrain_model",
258
default='bert-case-uncased',
261
help="Pre-trained model")
262
parser.add_argument("--num_labels_task",
263
default=None, type=int,
265
help="num_labels_task")
266
parser.add_argument("--max_seq_length",
269
help="The maximum total input sequence length after WordPiece tokenization. \n"
270
"Sequences longer than this will be truncated, and sequences shorter \n"
271
"than this will be padded.")
272
parser.add_argument("--do_train",
275
help="Whether to run training.")
276
parser.add_argument("--do_eval",
279
help="Whether to run eval on the dev set.")
280
parser.add_argument("--do_lower_case",
283
help="Set this flag if you are using an uncased model.")
284
parser.add_argument("--train_batch_size",
287
help="Total batch size for training.")
288
parser.add_argument("--learning_rate",
291
help="The initial learning rate for Adam.")
292
parser.add_argument("--num_train_epochs",
295
help="Total number of training epochs to perform.")
296
parser.add_argument("--warmup_proportion",
299
help="Proportion of training to perform linear learning rate warmup for. "
300
"E.g., 0.1 = 10%% of training.")
301
parser.add_argument("--no_cuda",
304
help="Whether not to use CUDA when available")
305
parser.add_argument("--local_rank",
308
help="local_rank for distributed training on gpus")
309
parser.add_argument('--seed',
312
help="random seed for initialization")
313
parser.add_argument('--gradient_accumulation_steps',
316
help="Number of updates steps to accumulate before performing a backward/update pass.")
317
parser.add_argument('--fp16',
320
help="Whether to use 16-bit float precision instead of 32-bit")
321
parser.add_argument('--loss_scale',
322
type=float, default=0,
323
help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
324
"0 (default value): dynamic loss scaling.\n"
325
"Positive power of 2: static loss scaling value.\n")
326
parser.add_argument("--weight_decay",
329
help="Weight decay if we apply some.")
330
parser.add_argument("--adam_epsilon",
333
help="Epsilon for Adam optimizer.")
334
parser.add_argument("--max_grad_norm",
337
help="Max gradient norm.")
338
parser.add_argument('--fp16_opt_level',
341
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
342
"See details at https://nvidia.github.io/apex/amp.html")
343
parser.add_argument("--task",
350
args = parser.parse_args()
352
processors = Processor_1
354
num_labels = args.num_labels_task
356
if args.local_rank == -1 or args.no_cuda:
357
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
358
n_gpu = torch.cuda.device_count()
360
torch.cuda.set_device(args.local_rank)
361
device = torch.device("cuda", args.local_rank)
364
torch.distributed.init_process_group(backend='nccl')
365
logger.info("device: {}, n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
366
device, n_gpu, bool(args.local_rank != -1), args.fp16))
370
if args.gradient_accumulation_steps < 1:
371
raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
372
args.gradient_accumulation_steps))
374
args.train_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps)
376
random.seed(args.seed)
377
np.random.seed(args.seed)
378
torch.manual_seed(args.seed)
380
torch.cuda.manual_seed_all(args.seed)
382
if not args.do_train:
383
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
385
if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:
386
raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
387
os.makedirs(args.output_dir, exist_ok=True)
390
tokenizer = RobertaTokenizer.from_pretrained(args.pretrain_model)
393
train_examples = None
394
num_train_steps = None
396
sentiment_list = None
397
processor = processors()
398
num_labels = num_labels
399
train_examples, aspect_list, sentiment_list = processor.get_train_examples(args.data_dir)
402
num_labels = len(aspect_list)
404
num_labels = len(sentiment_list)
406
print("What's task?")
409
num_train_steps = int(
410
len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
415
model = RobertaForSequenceClassification.from_pretrained(args.pretrain_model, num_labels=num_labels, output_hidden_states=False, output_attentions=False, return_dict=True)
419
t_total = num_train_steps
420
if args.local_rank != -1:
421
t_total = t_total // torch.distributed.get_world_size()
425
param_optimizer = list(model.named_parameters())
426
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
428
no_grad = ['bert.encoder.layer.11.output.dense_ent', 'bert.encoder.layer.11.output.LayerNorm_ent']
429
param_optimizer = [(n, p) for n, p in param_optimizer if not any(nd in n for nd in no_grad)]
430
optimizer_grouped_parameters = [
431
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
432
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
434
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
435
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(t_total*0.1), num_training_steps=t_total)
440
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
443
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
448
model = torch.nn.DataParallel(model)
451
if args.local_rank != -1:
452
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
453
output_device=args.local_rank,
454
find_unused_parameters=True)
459
train_features = convert_examples_to_features(
460
train_examples, aspect_list, sentiment_list, args.max_seq_length, tokenizer, args.task)
461
logger.info("***** Running training *****")
462
logger.info(" Num examples = %d", len(train_examples))
463
logger.info(" Batch size = %d", args.train_batch_size)
464
logger.info(" Num steps = %d", num_train_steps)
467
all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
468
all_attention_mask = torch.tensor([f.attention_mask for f in train_features], dtype=torch.long)
470
print("Excuting the task 1")
472
all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
476
all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)
479
train_data = TensorDataset(all_input_ids, all_attention_mask, all_label_ids)
481
train_data = TensorDataset(all_input_ids, all_attention_mask, all_segment_ids, all_label_ids)
485
if args.local_rank == -1:
486
train_sampler = RandomSampler(train_data)
488
train_sampler = DistributedSampler(train_data)
489
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
491
output_loss_file = os.path.join(args.output_dir, "loss")
492
loss_fout = open(output_loss_file, 'w')
500
for _ in trange(int(args.num_train_epochs), desc="Epoch"):
502
nb_tr_examples, nb_tr_steps = 0, 0
503
for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
504
batch = tuple(t.to(device) if i != 3 else t for i, t in enumerate(batch))
507
input_ids, attention_mask, label_ids = batch
509
input_ids, attention_mask, segment_ids, label_ids = batch
516
output = model(input_ids=input_ids, token_type_ids=None, attention_mask=attention_mask, labels=label_ids)
522
output = model(input_ids=input_ids, token_type_ids=None, attention_mask=attention_mask, labels=label_ids)
529
if args.gradient_accumulation_steps > 1:
530
loss = loss / args.gradient_accumulation_steps
535
with amp.scale_loss(loss, optimizer) as scaled_loss:
536
scaled_loss.backward()
541
loss_fout.write("{}\n".format(loss.item()))
542
tr_loss += loss.item()
543
nb_tr_examples += input_ids.size(0)
545
if (step + 1) % args.gradient_accumulation_steps == 0:
549
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
551
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
557
model_to_save = model.module if hasattr(model, 'module') else model
558
output_model_file = os.path.join(args.output_dir, "pytorch_model.bin_{}".format(global_step))
559
torch.save(model_to_save.state_dict(), output_model_file)
562
model_to_save = model.module if hasattr(model, 'module') else model
563
output_model_file = os.path.join(args.output_dir, "pytorch_model.bin")
564
torch.save(model_to_save.state_dict(), output_model_file)
567
if __name__ == "__main__":