joseangelatm commited on
Commit
c877a65
1 Parent(s): 278690b

First Commit

Browse files
Files changed (39) hide show
  1. .gitattributes +2 -0
  2. README.md +1 -0
  3. data/dataset.txt +3 -0
  4. data/dev.txt +3 -0
  5. data/roberta_cached_lm_510_dev.txt +3 -0
  6. data/roberta_cached_lm_510_train.txt +3 -0
  7. data/train.txt +3 -0
  8. models/roberta/config.json +1 -0
  9. models/roberta/merges.txt +3 -0
  10. models/roberta/output/checkpoint-10/config.json +55 -0
  11. models/roberta/output/checkpoint-10/merges.txt +3 -0
  12. models/roberta/output/checkpoint-10/optimizer.pt +3 -0
  13. models/roberta/output/checkpoint-10/pytorch_model.bin +3 -0
  14. models/roberta/output/checkpoint-10/scheduler.pt +3 -0
  15. models/roberta/output/checkpoint-10/special_tokens_map.json +1 -0
  16. models/roberta/output/checkpoint-10/tokenizer_config.json +1 -0
  17. models/roberta/output/checkpoint-10/training_args.bin +3 -0
  18. models/roberta/output/checkpoint-10/vocab.json +0 -0
  19. models/roberta/output/checkpoint-20/config.json +55 -0
  20. models/roberta/output/checkpoint-20/merges.txt +3 -0
  21. models/roberta/output/checkpoint-20/optimizer.pt +3 -0
  22. models/roberta/output/checkpoint-20/pytorch_model.bin +3 -0
  23. models/roberta/output/checkpoint-20/scheduler.pt +3 -0
  24. models/roberta/output/checkpoint-20/special_tokens_map.json +1 -0
  25. models/roberta/output/checkpoint-20/tokenizer_config.json +1 -0
  26. models/roberta/output/checkpoint-20/training_args.bin +3 -0
  27. models/roberta/output/checkpoint-20/vocab.json +0 -0
  28. models/roberta/output/config.json +55 -0
  29. models/roberta/output/eval_results.txt +3 -0
  30. models/roberta/output/merges.txt +3 -0
  31. models/roberta/output/pytorch_model.bin +3 -0
  32. models/roberta/output/special_tokens_map.json +1 -0
  33. models/roberta/output/tokenizer_config.json +1 -0
  34. models/roberta/output/training_args.bin +3 -0
  35. models/roberta/output/vocab.json +0 -0
  36. models/roberta/tokenizer_config.json +1 -0
  37. models/roberta/vocab.json +0 -0
  38. run_language_modeling.py +783 -0
  39. runs/Dec15_14-18-19_2c94adf95c33/events.out.tfevents.1608041899.2c94adf95c33.522.0 +0 -0
.gitattributes CHANGED
@@ -6,3 +6,5 @@
6
  *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
  *.ot filter=lfs diff=lfs merge=lfs -text
8
  *.onnx filter=lfs diff=lfs merge=lfs -text
 
 
6
  *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
  *.ot filter=lfs diff=lfs merge=lfs -text
8
  *.onnx filter=lfs diff=lfs merge=lfs -text
9
+ *.pt filter=lfs diff=lfs merge=lfs -text
10
+ *.txt filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1 @@
 
1
+ Ojalá funcione
data/dataset.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d7fd017b3523613e16ac79dfe8713c6a52ee6ffc13d10504666e121f37298a9
3
+ size 114354869
data/dev.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:822cdc6afa8134ea58ef1211a26c008cb19d961f16b3d712d6dca816c2a6cd6e
3
+ size 616146
data/roberta_cached_lm_510_dev.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1af6d44f857cf723a256e3ff6a5f35d3fcba4b6540f0ccb661d469bd461c191e
3
+ size 381593
data/roberta_cached_lm_510_train.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eeb4e7cb3ad81fa73be33d4b6931ff999574d8ea58284cbb80eb746b70413100
3
+ size 43764725
data/train.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25103781d2d1f350cf3c1d9b375f275380a9e1b49381e7c75e02379a016ef0e4
3
+ size 71099261
models/roberta/config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"architectures": ["RobertaForMaskedLM"], "attention_probs_dropout_prob": 0.1, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "max_position_embeddings": 514, "model_type": "roberta", "num_attention_heads": 12, "num_hidden_layers": 12, "type_vocab_size": 1, "vocab_size": 50265}
models/roberta/merges.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95c856ebae37de8257392fbb140bcda36151bf65eabeb5b9a64beecfac343193
3
+ size 536544
models/roberta/output/checkpoint-10/config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_num_labels": 2,
3
+ "architectures": [
4
+ "RobertaForMaskedLM"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bad_words_ids": null,
8
+ "bos_token_id": 0,
9
+ "decoder_start_token_id": null,
10
+ "do_sample": false,
11
+ "early_stopping": false,
12
+ "eos_token_id": 2,
13
+ "finetuning_task": null,
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "hidden_size": 768,
17
+ "id2label": {
18
+ "0": "LABEL_0",
19
+ "1": "LABEL_1"
20
+ },
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 3072,
23
+ "is_decoder": false,
24
+ "is_encoder_decoder": false,
25
+ "label2id": {
26
+ "LABEL_0": 0,
27
+ "LABEL_1": 1
28
+ },
29
+ "layer_norm_eps": 1e-05,
30
+ "length_penalty": 1.0,
31
+ "max_length": 20,
32
+ "max_position_embeddings": 514,
33
+ "min_length": 0,
34
+ "model_type": "roberta",
35
+ "no_repeat_ngram_size": 0,
36
+ "num_attention_heads": 12,
37
+ "num_beams": 1,
38
+ "num_hidden_layers": 12,
39
+ "num_return_sequences": 1,
40
+ "output_attentions": false,
41
+ "output_hidden_states": false,
42
+ "output_past": true,
43
+ "pad_token_id": 1,
44
+ "prefix": null,
45
+ "pruned_heads": {},
46
+ "repetition_penalty": 1.0,
47
+ "task_specific_params": null,
48
+ "temperature": 1.0,
49
+ "top_k": 50,
50
+ "top_p": 1.0,
51
+ "torchscript": false,
52
+ "type_vocab_size": 1,
53
+ "use_bfloat16": false,
54
+ "vocab_size": 50265
55
+ }
models/roberta/output/checkpoint-10/merges.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:babb3dc0405f9d288cc8e6205943f9f3ba1ee91cfadd9d89d1a85972890aa95b
3
+ size 536506
models/roberta/output/checkpoint-10/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2906549a1c8be7c09d9777124a1fc0afcf0b1b0b1206ef6b201cd978409f894
3
+ size 997701959
models/roberta/output/checkpoint-10/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e01a6671f9f0124a8323ea36af6d9c58ee663644b53031e23edbce4dceba701b
3
+ size 501237143
models/roberta/output/checkpoint-10/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f9cb9a2f68ceffad1228c2a6158aa67d57eca6d08f4ad6996c971cf59374fd5
3
+ size 623
models/roberta/output/checkpoint-10/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": "<mask>"}
models/roberta/output/checkpoint-10/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"max_len": 512}
models/roberta/output/checkpoint-10/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64268a85c10e9bcbe053aa9baedfdf45adab1e94a1d25d742604cab763792940
3
+ size 1519
models/roberta/output/checkpoint-10/vocab.json ADDED
The diff for this file is too large to render. See raw diff
models/roberta/output/checkpoint-20/config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_num_labels": 2,
3
+ "architectures": [
4
+ "RobertaForMaskedLM"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bad_words_ids": null,
8
+ "bos_token_id": 0,
9
+ "decoder_start_token_id": null,
10
+ "do_sample": false,
11
+ "early_stopping": false,
12
+ "eos_token_id": 2,
13
+ "finetuning_task": null,
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "hidden_size": 768,
17
+ "id2label": {
18
+ "0": "LABEL_0",
19
+ "1": "LABEL_1"
20
+ },
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 3072,
23
+ "is_decoder": false,
24
+ "is_encoder_decoder": false,
25
+ "label2id": {
26
+ "LABEL_0": 0,
27
+ "LABEL_1": 1
28
+ },
29
+ "layer_norm_eps": 1e-05,
30
+ "length_penalty": 1.0,
31
+ "max_length": 20,
32
+ "max_position_embeddings": 514,
33
+ "min_length": 0,
34
+ "model_type": "roberta",
35
+ "no_repeat_ngram_size": 0,
36
+ "num_attention_heads": 12,
37
+ "num_beams": 1,
38
+ "num_hidden_layers": 12,
39
+ "num_return_sequences": 1,
40
+ "output_attentions": false,
41
+ "output_hidden_states": false,
42
+ "output_past": true,
43
+ "pad_token_id": 1,
44
+ "prefix": null,
45
+ "pruned_heads": {},
46
+ "repetition_penalty": 1.0,
47
+ "task_specific_params": null,
48
+ "temperature": 1.0,
49
+ "top_k": 50,
50
+ "top_p": 1.0,
51
+ "torchscript": false,
52
+ "type_vocab_size": 1,
53
+ "use_bfloat16": false,
54
+ "vocab_size": 50265
55
+ }
models/roberta/output/checkpoint-20/merges.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:babb3dc0405f9d288cc8e6205943f9f3ba1ee91cfadd9d89d1a85972890aa95b
3
+ size 536506
models/roberta/output/checkpoint-20/optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:007e9598f42cdd29c37a8f1890047f1c9d42f9ce8e93a277fb3a7c9eacc8aaef
3
+ size 997701959
models/roberta/output/checkpoint-20/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9715fa8018cd96e53c7ea8bb4192c131ac64bfebdd93112e2820ecf6a4475d9
3
+ size 501237143
models/roberta/output/checkpoint-20/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed147c3577ee87e1d3f66769b4fff18b4ad0c6ec05d56bb6878413771b706293
3
+ size 623
models/roberta/output/checkpoint-20/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": "<mask>"}
models/roberta/output/checkpoint-20/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"max_len": 512}
models/roberta/output/checkpoint-20/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64268a85c10e9bcbe053aa9baedfdf45adab1e94a1d25d742604cab763792940
3
+ size 1519
models/roberta/output/checkpoint-20/vocab.json ADDED
The diff for this file is too large to render. See raw diff
models/roberta/output/config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_num_labels": 2,
3
+ "architectures": [
4
+ "RobertaForMaskedLM"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bad_words_ids": null,
8
+ "bos_token_id": 0,
9
+ "decoder_start_token_id": null,
10
+ "do_sample": false,
11
+ "early_stopping": false,
12
+ "eos_token_id": 2,
13
+ "finetuning_task": null,
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "hidden_size": 768,
17
+ "id2label": {
18
+ "0": "LABEL_0",
19
+ "1": "LABEL_1"
20
+ },
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 3072,
23
+ "is_decoder": false,
24
+ "is_encoder_decoder": false,
25
+ "label2id": {
26
+ "LABEL_0": 0,
27
+ "LABEL_1": 1
28
+ },
29
+ "layer_norm_eps": 1e-05,
30
+ "length_penalty": 1.0,
31
+ "max_length": 20,
32
+ "max_position_embeddings": 514,
33
+ "min_length": 0,
34
+ "model_type": "roberta",
35
+ "no_repeat_ngram_size": 0,
36
+ "num_attention_heads": 12,
37
+ "num_beams": 1,
38
+ "num_hidden_layers": 12,
39
+ "num_return_sequences": 1,
40
+ "output_attentions": false,
41
+ "output_hidden_states": false,
42
+ "output_past": true,
43
+ "pad_token_id": 1,
44
+ "prefix": null,
45
+ "pruned_heads": {},
46
+ "repetition_penalty": 1.0,
47
+ "task_specific_params": null,
48
+ "temperature": 1.0,
49
+ "top_k": 50,
50
+ "top_p": 1.0,
51
+ "torchscript": false,
52
+ "type_vocab_size": 1,
53
+ "use_bfloat16": false,
54
+ "vocab_size": 50265
55
+ }
models/roberta/output/eval_results.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7206c5471e7c697fbb01e10dacd4517ce2ea62aa78f1e1800e67e7c5865a741f
3
+ size 31
models/roberta/output/merges.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:babb3dc0405f9d288cc8e6205943f9f3ba1ee91cfadd9d89d1a85972890aa95b
3
+ size 536506
models/roberta/output/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40827c152b9a025377ceb13b97b0bd1e3ad6c210864e93f271deaf9584d95eb0
3
+ size 501237143
models/roberta/output/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": "<mask>"}
models/roberta/output/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"max_len": 512}
models/roberta/output/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64268a85c10e9bcbe053aa9baedfdf45adab1e94a1d25d742604cab763792940
3
+ size 1519
models/roberta/output/vocab.json ADDED
The diff for this file is too large to render. See raw diff
models/roberta/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"max_len": 512}
models/roberta/vocab.json ADDED
The diff for this file is too large to render. See raw diff
run_language_modeling.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
17
+ Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa).
18
+ GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned
19
+ using a masked language modeling (MLM) loss.
20
+ """
21
+
22
+
23
+ import argparse
24
+ import glob
25
+ import logging
26
+ import os
27
+ import pickle
28
+ import random
29
+ import re
30
+ import shutil
31
+ from typing import Dict, List, Tuple
32
+
33
+ import numpy as np
34
+ import torch
35
+ from torch.nn.utils.rnn import pad_sequence
36
+ from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler
37
+ from torch.utils.data.distributed import DistributedSampler
38
+ from tqdm import tqdm, trange
39
+
40
+ from transformers import (
41
+ MODEL_WITH_LM_HEAD_MAPPING,
42
+ WEIGHTS_NAME,
43
+ AdamW,
44
+ AutoConfig,
45
+ AutoModelWithLMHead,
46
+ AutoTokenizer,
47
+ PreTrainedModel,
48
+ PreTrainedTokenizer,
49
+ get_linear_schedule_with_warmup,
50
+ )
51
+
52
+
53
+ try:
54
+ from torch.utils.tensorboard import SummaryWriter
55
+ except ImportError:
56
+ from tensorboardX import SummaryWriter
57
+
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
63
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
64
+
65
+
66
+ class TextDataset(Dataset):
67
+ def __init__(self, tokenizer: PreTrainedTokenizer, args, file_path: str, block_size=512):
68
+ assert os.path.isfile(file_path)
69
+
70
+ block_size = block_size - (tokenizer.max_len - tokenizer.max_len_single_sentence)
71
+
72
+ directory, filename = os.path.split(file_path)
73
+ cached_features_file = os.path.join(
74
+ directory, args.model_type + "_cached_lm_" + str(block_size) + "_" + filename
75
+ )
76
+
77
+ if os.path.exists(cached_features_file) and not args.overwrite_cache:
78
+ logger.info("Loading features from cached file %s", cached_features_file)
79
+ with open(cached_features_file, "rb") as handle:
80
+ self.examples = pickle.load(handle)
81
+ else:
82
+ logger.info("Creating features from dataset file at %s", directory)
83
+
84
+ self.examples = []
85
+ with open(file_path, encoding="utf-8") as f:
86
+ text = f.read()
87
+
88
+ tokenized_text = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))
89
+
90
+ for i in range(0, len(tokenized_text) - block_size + 1, block_size): # Truncate in block of block_size
91
+ self.examples.append(tokenizer.build_inputs_with_special_tokens(tokenized_text[i : i + block_size]))
92
+ # Note that we are loosing the last truncated example here for the sake of simplicity (no padding)
93
+ # If your dataset is small, first you should loook for a bigger one :-) and second you
94
+ # can change this behavior by adding (model specific) padding.
95
+
96
+ logger.info("Saving features into cached file %s", cached_features_file)
97
+ with open(cached_features_file, "wb") as handle:
98
+ pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
99
+
100
+ def __len__(self):
101
+ return len(self.examples)
102
+
103
+ def __getitem__(self, item):
104
+ return torch.tensor(self.examples[item], dtype=torch.long)
105
+
106
+
107
+ class LineByLineTextDataset(Dataset):
108
+ def __init__(self, tokenizer: PreTrainedTokenizer, args, file_path: str, block_size=512):
109
+ assert os.path.isfile(file_path)
110
+ # Here, we do not cache the features, operating under the assumption
111
+ # that we will soon use fast multithreaded tokenizers from the
112
+ # `tokenizers` repo everywhere =)
113
+ logger.info("Creating features from dataset file at %s", file_path)
114
+
115
+ with open(file_path, encoding="utf-8") as f:
116
+ lines = [line for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]
117
+
118
+ self.examples = tokenizer.batch_encode_plus(lines, add_special_tokens=True, max_length=block_size)["input_ids"]
119
+
120
+ def __len__(self):
121
+ return len(self.examples)
122
+
123
+ def __getitem__(self, i):
124
+ return torch.tensor(self.examples[i], dtype=torch.long)
125
+
126
+
127
+ def load_and_cache_examples(args, tokenizer, evaluate=False):
128
+ file_path = args.eval_data_file if evaluate else args.train_data_file
129
+ if args.line_by_line:
130
+ return LineByLineTextDataset(tokenizer, args, file_path=file_path, block_size=args.block_size)
131
+ else:
132
+ return TextDataset(tokenizer, args, file_path=file_path, block_size=args.block_size)
133
+
134
+
135
+ def set_seed(args):
136
+ random.seed(args.seed)
137
+ np.random.seed(args.seed)
138
+ torch.manual_seed(args.seed)
139
+ if args.n_gpu > 0:
140
+ torch.cuda.manual_seed_all(args.seed)
141
+
142
+
143
+ def _sorted_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> List[str]:
144
+ ordering_and_checkpoint_path = []
145
+
146
+ glob_checkpoints = glob.glob(os.path.join(args.output_dir, "{}-*".format(checkpoint_prefix)))
147
+
148
+ for path in glob_checkpoints:
149
+ if use_mtime:
150
+ ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
151
+ else:
152
+ regex_match = re.match(".*{}-([0-9]+)".format(checkpoint_prefix), path)
153
+ if regex_match and regex_match.groups():
154
+ ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
155
+
156
+ checkpoints_sorted = sorted(ordering_and_checkpoint_path)
157
+ checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
158
+ return checkpoints_sorted
159
+
160
+
161
+ def _rotate_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> None:
162
+ if not args.save_total_limit:
163
+ return
164
+ if args.save_total_limit <= 0:
165
+ return
166
+
167
+ # Check if we should delete older checkpoint(s)
168
+ checkpoints_sorted = _sorted_checkpoints(args, checkpoint_prefix, use_mtime)
169
+ if len(checkpoints_sorted) <= args.save_total_limit:
170
+ return
171
+
172
+ number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit)
173
+ checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
174
+ for checkpoint in checkpoints_to_be_deleted:
175
+ logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint))
176
+ shutil.rmtree(checkpoint)
177
+
178
+
179
+ def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[torch.Tensor, torch.Tensor]:
180
+ """ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """
181
+
182
+ if tokenizer.mask_token is None:
183
+ raise ValueError(
184
+ "This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the --mlm flag if you want to use this tokenizer."
185
+ )
186
+
187
+ labels = inputs.clone()
188
+ # We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
189
+ probability_matrix = torch.full(labels.shape, args.mlm_probability)
190
+ special_tokens_mask = [
191
+ tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
192
+ ]
193
+ probability_matrix.masked_fill_(torch.tensor(special_tokens_mask, dtype=torch.bool), value=0.0)
194
+ if tokenizer._pad_token is not None:
195
+ padding_mask = labels.eq(tokenizer.pad_token_id)
196
+ probability_matrix.masked_fill_(padding_mask, value=0.0)
197
+ masked_indices = torch.bernoulli(probability_matrix).bool()
198
+ labels[~masked_indices] = -100 # We only compute loss on masked tokens
199
+
200
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
201
+ indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
202
+ inputs[indices_replaced] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token)
203
+
204
+ # 10% of the time, we replace masked input tokens with random word
205
+ indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
206
+ random_words = torch.randint(len(tokenizer), labels.shape, dtype=torch.long)
207
+ inputs[indices_random] = random_words[indices_random]
208
+
209
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
210
+ return inputs, labels
211
+
212
+
213
+ def train(args, train_dataset, model: PreTrainedModel, tokenizer: PreTrainedTokenizer) -> Tuple[int, float]:
214
+ """ Train the model """
215
+ if args.local_rank in [-1, 0]:
216
+ tb_writer = SummaryWriter()
217
+
218
+ args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
219
+
220
+ def collate(examples: List[torch.Tensor]):
221
+ if tokenizer._pad_token is None:
222
+ return pad_sequence(examples, batch_first=True)
223
+ return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
224
+
225
+ train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
226
+ train_dataloader = DataLoader(
227
+ train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=collate
228
+ )
229
+
230
+ if args.max_steps > 0:
231
+ t_total = args.max_steps
232
+ args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
233
+ else:
234
+ t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
235
+
236
+ model = model.module if hasattr(model, "module") else model # Take care of distributed/parallel training
237
+ model.resize_token_embeddings(len(tokenizer))
238
+
239
+ # Prepare optimizer and schedule (linear warmup and decay)
240
+ no_decay = ["bias", "LayerNorm.weight"]
241
+ optimizer_grouped_parameters = [
242
+ {
243
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
244
+ "weight_decay": args.weight_decay,
245
+ },
246
+ {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
247
+ ]
248
+ optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
249
+ scheduler = get_linear_schedule_with_warmup(
250
+ optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
251
+ )
252
+
253
+ # Check if saved optimizer or scheduler states exist
254
+ if (
255
+ args.model_name_or_path
256
+ and os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt"))
257
+ and os.path.isfile(os.path.join(args.model_name_or_path, "scheduler.pt"))
258
+ ):
259
+ # Load in optimizer and scheduler states
260
+ optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
261
+ scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
262
+
263
+ if args.fp16:
264
+ try:
265
+ from apex import amp
266
+ except ImportError:
267
+ raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
268
+ model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
269
+
270
+ # multi-gpu training (should be after apex fp16 initialization)
271
+ if args.n_gpu > 1:
272
+ model = torch.nn.DataParallel(model)
273
+
274
+ # Distributed training (should be after apex fp16 initialization)
275
+ if args.local_rank != -1:
276
+ model = torch.nn.parallel.DistributedDataParallel(
277
+ model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
278
+ )
279
+
280
+ # Train!
281
+ logger.info("***** Running training *****")
282
+ logger.info(" Num examples = %d", len(train_dataset))
283
+ logger.info(" Num Epochs = %d", args.num_train_epochs)
284
+ logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
285
+ logger.info(
286
+ " Total train batch size (w. parallel, distributed & accumulation) = %d",
287
+ args.train_batch_size
288
+ * args.gradient_accumulation_steps
289
+ * (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
290
+ )
291
+ logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
292
+ logger.info(" Total optimization steps = %d", t_total)
293
+
294
+ global_step = 0
295
+ epochs_trained = 0
296
+ steps_trained_in_current_epoch = 0
297
+ # Check if continuing training from a checkpoint
298
+ if args.model_name_or_path and os.path.exists(args.model_name_or_path):
299
+ try:
300
+ # set global_step to gobal_step of last saved checkpoint from model path
301
+ checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0]
302
+ global_step = int(checkpoint_suffix)
303
+ epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
304
+ steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
305
+
306
+ logger.info(" Continuing training from checkpoint, will skip to saved global_step")
307
+ logger.info(" Continuing training from epoch %d", epochs_trained)
308
+ logger.info(" Continuing training from global step %d", global_step)
309
+ logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
310
+ except ValueError:
311
+ logger.info(" Starting fine-tuning.")
312
+
313
+ tr_loss, logging_loss = 0.0, 0.0
314
+
315
+ model.zero_grad()
316
+ train_iterator = trange(
317
+ epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
318
+ )
319
+ set_seed(args) # Added here for reproducibility
320
+ for _ in train_iterator:
321
+ epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
322
+ for step, batch in enumerate(epoch_iterator):
323
+
324
+ # Skip past any already trained steps if resuming training
325
+ if steps_trained_in_current_epoch > 0:
326
+ steps_trained_in_current_epoch -= 1
327
+ continue
328
+
329
+ inputs, labels = mask_tokens(batch, tokenizer, args) if args.mlm else (batch, batch)
330
+ inputs = inputs.to(args.device)
331
+ labels = labels.to(args.device)
332
+ model.train()
333
+ outputs = model(inputs, masked_lm_labels=labels) if args.mlm else model(inputs, labels=labels)
334
+ loss = outputs[0] # model outputs are always tuple in transformers (see doc)
335
+
336
+ if args.n_gpu > 1:
337
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
338
+ if args.gradient_accumulation_steps > 1:
339
+ loss = loss / args.gradient_accumulation_steps
340
+
341
+ if args.fp16:
342
+ with amp.scale_loss(loss, optimizer) as scaled_loss:
343
+ scaled_loss.backward()
344
+ else:
345
+ loss.backward()
346
+
347
+ tr_loss += loss.item()
348
+ if (step + 1) % args.gradient_accumulation_steps == 0:
349
+ if args.fp16:
350
+ torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
351
+ else:
352
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
353
+ optimizer.step()
354
+ scheduler.step() # Update learning rate schedule
355
+ model.zero_grad()
356
+ global_step += 1
357
+
358
+ if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
359
+ # Log metrics
360
+ if (
361
+ args.local_rank == -1 and args.evaluate_during_training
362
+ ): # Only evaluate when single GPU otherwise metrics may not average well
363
+ results = evaluate(args, model, tokenizer)
364
+ for key, value in results.items():
365
+ tb_writer.add_scalar("eval_{}".format(key), value, global_step)
366
+ tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
367
+ tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
368
+ logging_loss = tr_loss
369
+
370
+ if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
371
+ checkpoint_prefix = "checkpoint"
372
+ # Save model checkpoint
373
+ output_dir = os.path.join(args.output_dir, "{}-{}".format(checkpoint_prefix, global_step))
374
+ os.makedirs(output_dir, exist_ok=True)
375
+ model_to_save = (
376
+ model.module if hasattr(model, "module") else model
377
+ ) # Take care of distributed/parallel training
378
+ model_to_save.save_pretrained(output_dir)
379
+ tokenizer.save_pretrained(output_dir)
380
+
381
+ torch.save(args, os.path.join(output_dir, "training_args.bin"))
382
+ logger.info("Saving model checkpoint to %s", output_dir)
383
+
384
+ _rotate_checkpoints(args, checkpoint_prefix)
385
+
386
+ torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
387
+ torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
388
+ logger.info("Saving optimizer and scheduler states to %s", output_dir)
389
+
390
+ if args.max_steps > 0 and global_step > args.max_steps:
391
+ epoch_iterator.close()
392
+ break
393
+ if args.max_steps > 0 and global_step > args.max_steps:
394
+ train_iterator.close()
395
+ break
396
+
397
+ if args.local_rank in [-1, 0]:
398
+ tb_writer.close()
399
+
400
+ return global_step, tr_loss / global_step
401
+
402
+
403
+ def evaluate(args, model: PreTrainedModel, tokenizer: PreTrainedTokenizer, prefix="") -> Dict:
404
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
405
+ eval_output_dir = args.output_dir
406
+
407
+ eval_dataset = load_and_cache_examples(args, tokenizer, evaluate=True)
408
+
409
+ if args.local_rank in [-1, 0]:
410
+ os.makedirs(eval_output_dir, exist_ok=True)
411
+
412
+ args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
413
+ # Note that DistributedSampler samples randomly
414
+
415
+ def collate(examples: List[torch.Tensor]):
416
+ if tokenizer._pad_token is None:
417
+ return pad_sequence(examples, batch_first=True)
418
+ return pad_sequence(examples, batch_first=True, padding_value=tokenizer.pad_token_id)
419
+
420
+ eval_sampler = SequentialSampler(eval_dataset)
421
+ eval_dataloader = DataLoader(
422
+ eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size, collate_fn=collate
423
+ )
424
+
425
+ # multi-gpu evaluate
426
+ if args.n_gpu > 1:
427
+ model = torch.nn.DataParallel(model)
428
+
429
+ # Eval!
430
+ logger.info("***** Running evaluation {} *****".format(prefix))
431
+ logger.info(" Num examples = %d", len(eval_dataset))
432
+ logger.info(" Batch size = %d", args.eval_batch_size)
433
+ eval_loss = 0.0
434
+ nb_eval_steps = 0
435
+ model.eval()
436
+
437
+ for batch in tqdm(eval_dataloader, desc="Evaluating"):
438
+ inputs, labels = mask_tokens(batch, tokenizer, args) if args.mlm else (batch, batch)
439
+ inputs = inputs.to(args.device)
440
+ labels = labels.to(args.device)
441
+
442
+ with torch.no_grad():
443
+ outputs = model(inputs, masked_lm_labels=labels) if args.mlm else model(inputs, labels=labels)
444
+ lm_loss = outputs[0]
445
+ eval_loss += lm_loss.mean().item()
446
+ nb_eval_steps += 1
447
+
448
+ eval_loss = eval_loss / nb_eval_steps
449
+ perplexity = torch.exp(torch.tensor(eval_loss))
450
+
451
+ result = {"perplexity": perplexity}
452
+
453
+ output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt")
454
+ with open(output_eval_file, "w") as writer:
455
+ logger.info("***** Eval results {} *****".format(prefix))
456
+ for key in sorted(result.keys()):
457
+ logger.info(" %s = %s", key, str(result[key]))
458
+ writer.write("%s = %s\n" % (key, str(result[key])))
459
+
460
+ return result
461
+
462
+
463
+ def main():
464
+ parser = argparse.ArgumentParser()
465
+
466
+ # Required parameters
467
+ parser.add_argument(
468
+ "--train_data_file", default=None, type=str, required=True, help="The input training data file (a text file)."
469
+ )
470
+ parser.add_argument(
471
+ "--output_dir",
472
+ type=str,
473
+ required=True,
474
+ help="The output directory where the model predictions and checkpoints will be written.",
475
+ )
476
+ parser.add_argument(
477
+ "--model_type", type=str, required=True, help="The model architecture to be trained or fine-tuned.",
478
+ )
479
+
480
+ # Other parameters
481
+ parser.add_argument(
482
+ "--eval_data_file",
483
+ default=None,
484
+ type=str,
485
+ help="An optional input evaluation data file to evaluate the perplexity on (a text file).",
486
+ )
487
+ parser.add_argument(
488
+ "--line_by_line",
489
+ action="store_true",
490
+ help="Whether distinct lines of text in the dataset are to be handled as distinct sequences.",
491
+ )
492
+ parser.add_argument(
493
+ "--should_continue", action="store_true", help="Whether to continue from latest checkpoint in output_dir"
494
+ )
495
+ parser.add_argument(
496
+ "--model_name_or_path",
497
+ default=None,
498
+ type=str,
499
+ help="The model checkpoint for weights initialization. Leave None if you want to train a model from scratch.",
500
+ )
501
+
502
+ parser.add_argument(
503
+ "--mlm", action="store_true", help="Train with masked-language modeling loss instead of language modeling."
504
+ )
505
+ parser.add_argument(
506
+ "--mlm_probability", type=float, default=0.15, help="Ratio of tokens to mask for masked language modeling loss"
507
+ )
508
+
509
+ parser.add_argument(
510
+ "--config_name",
511
+ default=None,
512
+ type=str,
513
+ help="Optional pretrained config name or path if not the same as model_name_or_path. If both are None, initialize a new config.",
514
+ )
515
+ parser.add_argument(
516
+ "--tokenizer_name",
517
+ default=None,
518
+ type=str,
519
+ help="Optional pretrained tokenizer name or path if not the same as model_name_or_path. If both are None, initialize a new tokenizer.",
520
+ )
521
+ parser.add_argument(
522
+ "--cache_dir",
523
+ default=None,
524
+ type=str,
525
+ help="Optional directory to store the pre-trained models downloaded from s3 (instead of the default one)",
526
+ )
527
+ parser.add_argument(
528
+ "--block_size",
529
+ default=-1,
530
+ type=int,
531
+ help="Optional input sequence length after tokenization."
532
+ "The training dataset will be truncated in block of this size for training."
533
+ "Default to the model max input length for single sentence inputs (take into account special tokens).",
534
+ )
535
+ parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
536
+ parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.")
537
+ parser.add_argument(
538
+ "--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step."
539
+ )
540
+
541
+ parser.add_argument("--per_gpu_train_batch_size", default=4, type=int, help="Batch size per GPU/CPU for training.")
542
+ parser.add_argument(
543
+ "--per_gpu_eval_batch_size", default=4, type=int, help="Batch size per GPU/CPU for evaluation."
544
+ )
545
+ parser.add_argument(
546
+ "--gradient_accumulation_steps",
547
+ type=int,
548
+ default=1,
549
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
550
+ )
551
+ parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
552
+ parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
553
+ parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
554
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
555
+ parser.add_argument(
556
+ "--num_train_epochs", default=1.0, type=float, help="Total number of training epochs to perform."
557
+ )
558
+ parser.add_argument(
559
+ "--max_steps",
560
+ default=-1,
561
+ type=int,
562
+ help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
563
+ )
564
+ parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
565
+
566
+ parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.")
567
+ parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint every X updates steps.")
568
+ parser.add_argument(
569
+ "--save_total_limit",
570
+ type=int,
571
+ default=None,
572
+ help="Limit the total amount of checkpoints, delete the older checkpoints in the output_dir, does not delete by default",
573
+ )
574
+ parser.add_argument(
575
+ "--eval_all_checkpoints",
576
+ action="store_true",
577
+ help="Evaluate all checkpoints starting with the same prefix as model_name_or_path ending and ending with step number",
578
+ )
579
+ parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
580
+ parser.add_argument(
581
+ "--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory"
582
+ )
583
+ parser.add_argument(
584
+ "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
585
+ )
586
+ parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
587
+
588
+ parser.add_argument(
589
+ "--fp16",
590
+ action="store_true",
591
+ help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
592
+ )
593
+ parser.add_argument(
594
+ "--fp16_opt_level",
595
+ type=str,
596
+ default="O1",
597
+ help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
598
+ "See details at https://nvidia.github.io/apex/amp.html",
599
+ )
600
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
601
+ parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.")
602
+ parser.add_argument("--server_port", type=str, default="", help="For distant debugging.")
603
+ args = parser.parse_args()
604
+
605
+ if args.model_type in ["bert", "roberta", "distilbert", "camembert"] and not args.mlm:
606
+ raise ValueError(
607
+ "BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the --mlm "
608
+ "flag (masked language modeling)."
609
+ )
610
+ if args.eval_data_file is None and args.do_eval:
611
+ raise ValueError(
612
+ "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file "
613
+ "or remove the --do_eval argument."
614
+ )
615
+ if args.should_continue:
616
+ sorted_checkpoints = _sorted_checkpoints(args)
617
+ if len(sorted_checkpoints) == 0:
618
+ raise ValueError("Used --should_continue but no checkpoint was found in --output_dir.")
619
+ else:
620
+ args.model_name_or_path = sorted_checkpoints[-1]
621
+
622
+ if (
623
+ os.path.exists(args.output_dir)
624
+ and os.listdir(args.output_dir)
625
+ and args.do_train
626
+ and not args.overwrite_output_dir
627
+ and not args.should_continue
628
+ ):
629
+ raise ValueError(
630
+ "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
631
+ args.output_dir
632
+ )
633
+ )
634
+
635
+ # Setup distant debugging if needed
636
+ if args.server_ip and args.server_port:
637
+ # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
638
+ import ptvsd
639
+
640
+ print("Waiting for debugger attach")
641
+ ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
642
+ ptvsd.wait_for_attach()
643
+
644
+ # Setup CUDA, GPU & distributed training
645
+ if args.local_rank == -1 or args.no_cuda:
646
+ device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
647
+ args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
648
+ else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
649
+ torch.cuda.set_device(args.local_rank)
650
+ device = torch.device("cuda", args.local_rank)
651
+ torch.distributed.init_process_group(backend="nccl")
652
+ args.n_gpu = 1
653
+ args.device = device
654
+
655
+ # Setup logging
656
+ logging.basicConfig(
657
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
658
+ datefmt="%m/%d/%Y %H:%M:%S",
659
+ level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
660
+ )
661
+ logger.warning(
662
+ "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
663
+ args.local_rank,
664
+ device,
665
+ args.n_gpu,
666
+ bool(args.local_rank != -1),
667
+ args.fp16,
668
+ )
669
+
670
+ # Set seed
671
+ set_seed(args)
672
+
673
+ # Load pretrained model and tokenizer
674
+ if args.local_rank not in [-1, 0]:
675
+ torch.distributed.barrier() # Barrier to make sure only the first process in distributed training download model & vocab
676
+
677
+ if args.config_name:
678
+ config = AutoConfig.from_pretrained(args.config_name, cache_dir=args.cache_dir)
679
+ elif args.model_name_or_path:
680
+ config = AutoConfig.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir)
681
+ else:
682
+ # When we release a pip version exposing CONFIG_MAPPING,
683
+ # we can do `config = CONFIG_MAPPING[args.model_type]()`.
684
+ raise ValueError(
685
+ "You are instantiating a new config instance from scratch. This is not supported, but you can do it from another script, save it,"
686
+ "and load it from here, using --config_name"
687
+ )
688
+
689
+ if args.tokenizer_name:
690
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, cache_dir=args.cache_dir)
691
+ elif args.model_name_or_path:
692
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir)
693
+ else:
694
+ raise ValueError(
695
+ "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another script, save it,"
696
+ "and load it from here, using --tokenizer_name"
697
+ )
698
+
699
+ if args.block_size <= 0:
700
+ args.block_size = tokenizer.max_len
701
+ # Our input block size will be the max possible for the model
702
+ else:
703
+ args.block_size = min(args.block_size, tokenizer.max_len)
704
+
705
+ if args.model_name_or_path:
706
+ model = AutoModelWithLMHead.from_pretrained(
707
+ args.model_name_or_path,
708
+ from_tf=bool(".ckpt" in args.model_name_or_path),
709
+ config=config,
710
+ cache_dir=args.cache_dir,
711
+ )
712
+ else:
713
+ logger.info("Training new model from scratch")
714
+ model = AutoModelWithLMHead.from_config(config)
715
+
716
+ model.to(args.device)
717
+
718
+ if args.local_rank == 0:
719
+ torch.distributed.barrier() # End of barrier to make sure only the first process in distributed training download model & vocab
720
+
721
+ logger.info("Training/evaluation parameters %s", args)
722
+
723
+ # Training
724
+ if args.do_train:
725
+ if args.local_rank not in [-1, 0]:
726
+ torch.distributed.barrier() # Barrier to make sure only the first process in distributed training process the dataset, and the others will use the cache
727
+
728
+ train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False)
729
+
730
+ if args.local_rank == 0:
731
+ torch.distributed.barrier()
732
+
733
+ global_step, tr_loss = train(args, train_dataset, model, tokenizer)
734
+ logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
735
+
736
+ # Saving best-practices: if you use save_pretrained for the model and tokenizer, you can reload them using from_pretrained()
737
+ if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
738
+ # Create output directory if needed
739
+ if args.local_rank in [-1, 0]:
740
+ os.makedirs(args.output_dir, exist_ok=True)
741
+
742
+ logger.info("Saving model checkpoint to %s", args.output_dir)
743
+ # Save a trained model, configuration and tokenizer using `save_pretrained()`.
744
+ # They can then be reloaded using `from_pretrained()`
745
+ model_to_save = (
746
+ model.module if hasattr(model, "module") else model
747
+ ) # Take care of distributed/parallel training
748
+ model_to_save.save_pretrained(args.output_dir)
749
+ tokenizer.save_pretrained(args.output_dir)
750
+
751
+ # Good practice: save your training arguments together with the trained model
752
+ torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
753
+
754
+ # Load a trained model and vocabulary that you have fine-tuned
755
+ model = AutoModelWithLMHead.from_pretrained(args.output_dir)
756
+ tokenizer = AutoTokenizer.from_pretrained(args.output_dir)
757
+ model.to(args.device)
758
+
759
+ # Evaluation
760
+ results = {}
761
+ if args.do_eval and args.local_rank in [-1, 0]:
762
+ checkpoints = [args.output_dir]
763
+ if args.eval_all_checkpoints:
764
+ checkpoints = list(
765
+ os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
766
+ )
767
+ logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging
768
+ logger.info("Evaluate the following checkpoints: %s", checkpoints)
769
+ for checkpoint in checkpoints:
770
+ global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
771
+ prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else ""
772
+
773
+ model = AutoModelWithLMHead.from_pretrained(checkpoint)
774
+ model.to(args.device)
775
+ result = evaluate(args, model, tokenizer, prefix=prefix)
776
+ result = dict((k + "_{}".format(global_step), v) for k, v in result.items())
777
+ results.update(result)
778
+
779
+ return results
780
+
781
+
782
+ if __name__ == "__main__":
783
+ main()
runs/Dec15_14-18-19_2c94adf95c33/events.out.tfevents.1608041899.2c94adf95c33.522.0 ADDED
Binary file (1.11 kB). View file