Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

run_yesno.py 24 KB

You have to be logged in to leave a comment. Sign In
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import argparse
  17. import glob
  18. import logging
  19. import os
  20. import random
  21. import timeit
  22. import numpy as np
  23. import torch
  24. import torch.nn as nn
  25. from torch.nn import CrossEntropyLoss, BCELoss
  26. from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
  27. from tqdm import tqdm, trange
  28. from transformers import (
  29. WEIGHTS_NAME,
  30. AdamW,
  31. PreTrainedModel,
  32. AutoConfig,
  33. AutoModel,
  34. AutoTokenizer,
  35. get_linear_schedule_with_warmup,
  36. squad_convert_examples_to_features,
  37. )
  38. from utils_qa import transform_n2b_yesno, eval_bioasq_standard, read_squad_examples, write_predictions
  39. logger = logging.getLogger(__name__)
  40. def set_seed(args):
  41. random.seed(args.seed)
  42. np.random.seed(args.seed)
  43. torch.manual_seed(args.seed)
  44. torch.cuda.manual_seed_all(args.seed)
  45. def to_list(tensor):
  46. return tensor.detach().cpu().tolist()
  47. class YesNoResult(object):
  48. """
  49. Constructs a SquadResult which can be used to evaluate a model's output on the SQuAD dataset.
  50. Args:
  51. unique_id: The unique identifier corresponding to that example.
  52. logits: yes/no logit
  53. """
  54. def __init__(self, unique_id, logits):
  55. self.logits = logits
  56. self.unique_id = unique_id
  57. class AutoModelForYesno(PreTrainedModel):
  58. base_model_prefix = None
  59. def __init__(self, config, model_type):
  60. super().__init__(config)
  61. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  62. self.regressor = nn.Linear(config.hidden_size, 1) # self.classifier
  63. self.sigmoid = nn.Sigmoid()
  64. self.init_weights()
  65. self.model_type = model_type
  66. self.add_module(model_type, AutoModel.from_config(config))
  67. self._modules[model_type].init_weights()
  68. def _init_weights(self, module):
  69. """ Initialize the weights """
  70. if isinstance(module, (nn.Linear, nn.Embedding)):
  71. # Slightly different from the TF version which uses truncated_normal for initialization
  72. # cf https://github.com/pytorch/pytorch/pull/5617
  73. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  74. if isinstance(module, nn.Linear) and module.bias is not None:
  75. module.bias.data.zero_()
  76. def forward(
  77. self,
  78. input_ids=None,
  79. attention_mask=None,
  80. token_type_ids=None,
  81. position_ids=None,
  82. head_mask=None,
  83. inputs_embeds=None,
  84. labels=None,
  85. ):
  86. r"""
  87. labels (:obj:`torch.LongTensor` of shape :obj:`(
  88. ,)`, `optional`, defaults to :obj:`None`):
  89. Labels for computing the sequence classification/regression loss.
  90. Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
  91. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
  92. If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  93. Returns:
  94. :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
  95. loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):
  96. Classification (or regression if config.num_labels==1) loss.
  97. logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
  98. Classification (or regression if config.num_labels==1) scores (before SoftMax).
  99. hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
  100. Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
  101. of shape :obj:`(batch_size, sequence_length, hidden_size)`.
  102. Hidden-states of the model at the output of each layer plus the initial embedding outputs.
  103. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
  104. Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
  105. :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
  106. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  107. heads.
  108. Examples::
  109. from transformers import BertTokenizer, BertForSequenceClassification
  110. import torch
  111. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  112. model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
  113. input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
  114. labels = torch.tensor([1]).unsqueeze(0) # Batch size 1
  115. outputs = model(input_ids, labels=labels)
  116. loss, logits = outputs[:2]
  117. """
  118. outputs = self._modules[self.model_type](
  119. input_ids,
  120. attention_mask=attention_mask,
  121. token_type_ids=token_type_ids,
  122. position_ids=position_ids,
  123. head_mask=head_mask,
  124. inputs_embeds=inputs_embeds,
  125. )
  126. pooled_output = outputs[1] # use [CLS] pooled output
  127. pooled_output = self.dropout(pooled_output)
  128. logits = self.regressor(pooled_output)
  129. logits = self.sigmoid(logits)
  130. outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
  131. if labels is not None:
  132. loss_fct = BCELoss()
  133. labels = labels.to(torch.float)
  134. loss = loss_fct(logits.view(-1), labels.view(-1))
  135. outputs = (loss,) + outputs
  136. return outputs
  137. def train(args, train_dataset, model, tokenizer):
  138. """ Train the model """
  139. train_sampler = RandomSampler(train_dataset)
  140. train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.per_gpu_train_batch_size)
  141. if args.max_steps > 0:
  142. t_total = args.max_steps
  143. args.num_train_epochs = args.max_steps // len(train_dataloader) + 1
  144. else:
  145. t_total = len(train_dataloader) * args.num_train_epochs
  146. # Prepare optimizer and schedule (linear warmup and decay)
  147. no_decay = ["bias", "LayerNorm.weight"]
  148. optimizer_grouped_parameters = [
  149. {
  150. "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
  151. "weight_decay": args.weight_decay,
  152. },
  153. {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
  154. ]
  155. optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
  156. scheduler = get_linear_schedule_with_warmup(
  157. optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
  158. )
  159. # Check if saved optimizer or scheduler states exist
  160. if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
  161. os.path.join(args.model_name_or_path, "scheduler.pt")
  162. ):
  163. # Load in optimizer and scheduler states
  164. optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
  165. scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
  166. # Train!
  167. logger.info("***** Running training *****")
  168. logger.info(" Num examples = %d", len(train_dataset))
  169. logger.info(" Num Epochs = %d", args.num_train_epochs)
  170. logger.info(
  171. " Total train batch size = %d", args.per_gpu_train_batch_size
  172. )
  173. logger.info(" Total optimization steps = %d", t_total)
  174. global_step = 1
  175. epochs_trained = 0
  176. tr_loss, logging_loss = 0.0, 0.0
  177. model.zero_grad()
  178. train_iterator = trange(
  179. epochs_trained, int(args.num_train_epochs), desc="Epoch"
  180. )
  181. for _ in train_iterator:
  182. epoch_iterator = tqdm(train_dataloader, desc="Iteration")
  183. for step, batch in enumerate(epoch_iterator):
  184. model.train()
  185. batch = tuple(t.to(args.device) for t in batch)
  186. inputs = {
  187. "input_ids": batch[0],
  188. "attention_mask": batch[1],
  189. "token_type_ids": batch[2],
  190. "labels": (batch[7]==0.).to(torch.long), # is_impossible
  191. }
  192. outputs = model(**inputs)
  193. # model outputs are always tuple in transformers (see doc)
  194. loss = outputs[0]
  195. loss.backward()
  196. tr_loss += loss.item()
  197. torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
  198. optimizer.step()
  199. scheduler.step() # Update learning rate schedule
  200. model.zero_grad()
  201. global_step += 1
  202. # Log metrics
  203. if args.logging_steps > 0 and global_step % args.logging_steps == 0:
  204. logging_loss = tr_loss
  205. # Save model checkpoint
  206. if args.save_steps > 0 and global_step % args.save_steps == 0:
  207. output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
  208. if not os.path.exists(output_dir):
  209. os.makedirs(output_dir)
  210. model_to_save = model.module if hasattr(model, "module") else model
  211. model_to_save.save_pretrained(output_dir)
  212. tokenizer.save_pretrained(output_dir)
  213. torch.save(args, os.path.join(output_dir, "training_args.bin"))
  214. logger.info("Saving model checkpoint to %s", output_dir)
  215. torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
  216. torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
  217. logger.info("Saving optimizer and scheduler states to %s", output_dir)
  218. if args.max_steps > 0 and global_step > args.max_steps:
  219. epoch_iterator.close()
  220. break
  221. if args.max_steps > 0 and global_step > args.max_steps:
  222. train_iterator.close()
  223. break
  224. return global_step, tr_loss / global_step
  225. def evaluate(args, model, tokenizer, prefix=""):
  226. dataset, examples, features = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True)
  227. if not os.path.exists(args.output_dir):
  228. os.makedirs(args.output_dir)
  229. eval_sampler = SequentialSampler(dataset)
  230. eval_dataloader = DataLoader(dataset, sampler=eval_sampler, batch_size=args.per_gpu_eval_batch_size)
  231. # Eval!
  232. logger.info("***** Running evaluation {} *****".format(prefix))
  233. logger.info(" Num examples = %d", len(dataset))
  234. logger.info(" Batch size = %d", args.per_gpu_eval_batch_size)
  235. all_results = []
  236. start_time = timeit.default_timer()
  237. for batch in tqdm(eval_dataloader, desc="Evaluating"):
  238. model.eval()
  239. batch = tuple(t.to(args.device) for t in batch)
  240. with torch.no_grad():
  241. inputs = {
  242. "input_ids": batch[0],
  243. "attention_mask": batch[1],
  244. "token_type_ids": batch[2],
  245. }
  246. example_indices = batch[3]
  247. outputs = model(**inputs)
  248. for i, example_index in enumerate(example_indices):
  249. eval_feature = features[example_index.item()]
  250. unique_id = int(eval_feature.unique_id)
  251. logits = to_list(outputs[0][i])
  252. result = YesNoResult(unique_id, logits)
  253. all_results.append(result)
  254. evalTime = timeit.default_timer() - start_time
  255. logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(dataset))
  256. # Compute predictions
  257. output_prediction_file = os.path.join(args.output_dir, "predictions_{}.json".format(prefix))
  258. write_predictions(
  259. examples,
  260. features,
  261. all_results,
  262. output_prediction_file
  263. )
  264. ## Transform the prediction into the BioASQ format
  265. logger.info("***** Transform the prediction file into the BioASQ format {} *****".format(prefix))
  266. transform_n2b_yesno(output_prediction_file, args.output_dir)
  267. ## Evaluate with the BioASQ official evaluation code
  268. logger.info("***** Evaluate with the BioASQ official evaluation code *****")
  269. pred_file = os.path.join(args.output_dir, "BioASQform_BioASQ-answer.json")
  270. eval_score = eval_bioasq_standard(str(5), pred_file, args.golden_file, args.official_eval_dir)
  271. print("** BioASQ-yesno Evaluation Results ************************************")
  272. print(f" Accuracy = {float(eval_score[0])*100:.2f}")
  273. print(f" macro F1 = {float(eval_score[7])*100:.2f}")
  274. print(f" F1 - yes = {float(eval_score[8])*100:.2f}")
  275. print(f" F1 - no = {float(eval_score[9])*100:.2f}")
  276. def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
  277. # Load data features from cache or dataset file
  278. input_dir = args.output_dir if args.output_dir else "."
  279. if not os.path.exists(input_dir):
  280. os.makedirs(input_dir)
  281. cached_features_file = os.path.join(
  282. input_dir,
  283. "cached_{}_{}_{}".format(
  284. "dev" if evaluate else "train",
  285. list(filter(None, args.model_name_or_path.split("/"))).pop(),
  286. str(args.max_seq_length),
  287. ),
  288. )
  289. # Init features and dataset from cache if it exists
  290. if os.path.exists(cached_features_file) and not args.overwrite_cache:
  291. logger.info("Loading features from cached file %s", cached_features_file)
  292. features_and_dataset = torch.load(cached_features_file)
  293. features, dataset, examples = (
  294. features_and_dataset["features"],
  295. features_and_dataset["dataset"],
  296. features_and_dataset["examples"],
  297. )
  298. else:
  299. logger.info("Creating features from dataset file at %s", input_dir)
  300. if evaluate:
  301. examples = read_squad_examples(args.predict_file, is_training=False)
  302. else:
  303. examples = read_squad_examples(args.train_file, is_training=True)
  304. features, dataset = squad_convert_examples_to_features(
  305. examples=examples,
  306. tokenizer=tokenizer,
  307. max_seq_length=args.max_seq_length,
  308. doc_stride=args.doc_stride,
  309. max_query_length=args.max_query_length,
  310. is_training=not evaluate,
  311. return_dataset="pt"
  312. )
  313. logger.info("Saving features into cached file %s", cached_features_file)
  314. torch.save({"features": features, "dataset": dataset, "examples": examples}, cached_features_file)
  315. if output_examples:
  316. return dataset, examples, features
  317. return dataset
  318. def main():
  319. parser = argparse.ArgumentParser()
  320. # Required parameters
  321. parser.add_argument(
  322. "--model_type",
  323. default=None,
  324. type=str,
  325. required=True,
  326. help="Model type selected in the list: ",
  327. )
  328. parser.add_argument(
  329. "--model_name_or_path",
  330. default=None,
  331. type=str,
  332. required=True,
  333. help="Path to pre-trained model",
  334. )
  335. parser.add_argument(
  336. "--output_dir",
  337. default=None,
  338. type=str,
  339. required=True,
  340. help="The output directory where the model checkpoints will be written."
  341. )
  342. parser.add_argument(
  343. "--golden_file",
  344. default=None,
  345. type=str,
  346. help="BioASQ official golden answer file"
  347. )
  348. parser.add_argument(
  349. "--official_eval_dir",
  350. default='./scripts/bioasq_eval',
  351. type=str,
  352. help="BioASQ official golden answer file"
  353. )
  354. # Other parameters
  355. parser.add_argument(
  356. "--data_dir",
  357. default=None,
  358. type=str,
  359. help="The input data dir. Should contain the .json files for the task."
  360. + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
  361. )
  362. parser.add_argument(
  363. "--train_file",
  364. default=None,
  365. type=str,
  366. help="SQuAD json for training. E.g., train-v1.1.json"
  367. )
  368. parser.add_argument(
  369. "--predict_file",
  370. default=None,
  371. type=str,
  372. help="SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json"
  373. )
  374. parser.add_argument(
  375. "--do_lower_case",
  376. action="store_true",
  377. help="Whether to lower case the input text. Should be True for uncased "
  378. "models and False for cased models."
  379. )
  380. parser.add_argument(
  381. "--max_seq_length",
  382. default=384,
  383. type=int,
  384. help="The maximum total input sequence length after WordPiece tokenization. "
  385. "Sequences longer than this will be truncated, and sequences shorter "
  386. "than this will be padded."
  387. )
  388. parser.add_argument(
  389. "--cache_dir",
  390. default="",
  391. type=str,
  392. help="Where do you want to store the pre-trained models downloaded from s3",
  393. )
  394. parser.add_argument(
  395. "--doc_stride",
  396. default=128,
  397. type=int,
  398. help="When splitting up a long document into chunks, how much stride to "
  399. "take between chunks."
  400. )
  401. parser.add_argument(
  402. "--max_query_length",
  403. default=64,
  404. type=int,
  405. help="The maximum number of tokens for the question. Questions longer than "
  406. "this will be truncated to this length."
  407. )
  408. parser.add_argument(
  409. "--do_train",
  410. action="store_true",
  411. help="Whether to run training."
  412. )
  413. parser.add_argument(
  414. "--do_eval",
  415. action="store_true",
  416. help="Whether to run eval on the dev set."
  417. )
  418. parser.add_argument(
  419. "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets",
  420. )
  421. parser.add_argument(
  422. "--seed",
  423. default=0,
  424. type=int,
  425. help="Random seed"
  426. )
  427. parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
  428. parser.add_argument(
  429. "--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation."
  430. )
  431. parser.add_argument(
  432. "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name"
  433. )
  434. parser.add_argument(
  435. "--tokenizer_name",
  436. default="",
  437. type=str,
  438. help="Pretrained tokenizer name or path if not the same as model_name",
  439. )
  440. parser.add_argument(
  441. "--logging_steps",
  442. type=int,
  443. default=500,
  444. help="Log every X updates steps."
  445. )
  446. parser.add_argument(
  447. "--save_steps",
  448. type=int,
  449. default=500,
  450. help="Save checkpoint every X updates steps."
  451. )
  452. parser.add_argument(
  453. "--learning_rate",
  454. default=5e-5,
  455. type=float,
  456. help="The initial learning rate for Adam."
  457. )
  458. parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
  459. parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
  460. parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
  461. parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
  462. parser.add_argument(
  463. "--num_train_epochs",
  464. default=3.0,
  465. type=float,
  466. help="Total number of training epochs to perform."
  467. )
  468. parser.add_argument(
  469. "--max_steps",
  470. default=-1,
  471. type=int,
  472. help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
  473. )
  474. parser.add_argument(
  475. "--eval_all_checkpoints",
  476. action="store_true",
  477. help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
  478. )
  479. args = parser.parse_args()
  480. if args.doc_stride >= args.max_seq_length - args.max_query_length:
  481. logger.warning(
  482. "WARNING - You've set a doc stride which may be superior to the document length in some "
  483. "examples. This could result in errors when building features from the examples. Please reduce the doc "
  484. "stride or increase the maximum length to ensure the features are correctly built."
  485. )
  486. # Setup CUDA
  487. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  488. args.device = device
  489. # Setup logging
  490. logging.basicConfig(
  491. format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
  492. datefmt="%m/%d/%Y %H:%M:%S",
  493. level=logging.INFO
  494. )
  495. logger.warning(
  496. "Process device: %s", device
  497. )
  498. # Set seed
  499. set_seed(args)
  500. # Load pretrained model and tokenizer
  501. args.model_type = args.model_type.lower()
  502. AutoModelForYesno.base_model_prefix = args.model_type
  503. config = AutoConfig.from_pretrained(
  504. args.config_name if args.config_name else args.model_name_or_path,
  505. cache_dir=args.cache_dir if args.cache_dir else None,
  506. )
  507. tokenizer = AutoTokenizer.from_pretrained(
  508. args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
  509. do_lower_case=args.do_lower_case,
  510. cache_dir=args.cache_dir if args.cache_dir else None,
  511. )
  512. model = AutoModelForYesno.from_pretrained(
  513. args.model_name_or_path,
  514. config = config,
  515. model_type = args.model_type
  516. )
  517. model.to(args.device)
  518. logger.info("Training/evaluation parameters %s", args)
  519. # Training
  520. if args.do_train:
  521. train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False)
  522. global_step, tr_loss = train(args, train_dataset, model, tokenizer)
  523. logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
  524. # Save the trained model and the tokenizer
  525. if args.do_train:
  526. # Create output directory if needed
  527. if not os.path.exists(args.output_dir):
  528. os.makedirs(args.output_dir)
  529. logger.info("Saving model checkpoint to %s", args.output_dir)
  530. # Save a trained model, configuration and tokenizer using `save_pretrained()`.
  531. # They can then be reloaded using `from_pretrained()`
  532. model_to_save = model.module if hasattr(model, "module") else model
  533. model_to_save.save_pretrained(args.output_dir)
  534. tokenizer.save_pretrained(args.output_dir)
  535. # Good practice: save your training arguments together with the trained model
  536. torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
  537. # Evaluation - we can ask to evaluate all the checkpoints (sub-directories) in a directory
  538. if args.do_eval:
  539. if args.do_train or True:
  540. logger.info("Loading checkpoints saved during training for evaluation")
  541. checkpoints = [args.output_dir]
  542. if args.eval_all_checkpoints:
  543. checkpoints = list(
  544. os.path.dirname(c)
  545. for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
  546. )
  547. logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce model loading logs
  548. else:
  549. logger.info("Loading checkpoint %s for evaluation", args.model_name_or_path)
  550. checkpoints = [args.model_name_or_path]
  551. logger.info("Evaluate the following checkpoints: %s", checkpoints)
  552. for checkpoint in checkpoints:
  553. # Reload the model
  554. if 'checkpoint' in checkpoint:
  555. global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
  556. else:
  557. global_step = ""
  558. model = AutoModelForYesno.from_pretrained(
  559. checkpoint,
  560. config=config,
  561. model_type=args.model_type
  562. )
  563. model.to(args.device)
  564. # Evaluate
  565. evaluate(args, model, tokenizer, prefix=global_step)
  566. if __name__ == "__main__":
  567. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...