versae commited on
Commit
f4133c7
1 Parent(s): d986e5d

First of version Alberti 📜🖊️

Browse files
Files changed (45) hide show
  1. README.md +82 -0
  2. config.json +29 -0
  3. config.py +7 -0
  4. convert.py +25 -0
  5. evals/alberti/eval_results_arabic.json +5 -0
  6. evals/alberti/eval_results_chinese.json +5 -0
  7. evals/alberti/eval_results_czech.json +5 -0
  8. evals/alberti/eval_results_english.json +5 -0
  9. evals/alberti/eval_results_finnish.json +5 -0
  10. evals/alberti/eval_results_french.json +5 -0
  11. evals/alberti/eval_results_german.json +5 -0
  12. evals/alberti/eval_results_hindi.json +5 -0
  13. evals/alberti/eval_results_hungarian.json +5 -0
  14. evals/alberti/eval_results_italian.json +5 -0
  15. evals/alberti/eval_results_portuguese.json +5 -0
  16. evals/alberti/eval_results_russian.json +5 -0
  17. evals/alberti/eval_results_spanish.json +5 -0
  18. evals/eval_results_alberti.json +5 -0
  19. evals/eval_results_mbert.json +5 -0
  20. evals/mbert/eval_results_arabic.json +5 -0
  21. evals/mbert/eval_results_chinese.json +5 -0
  22. evals/mbert/eval_results_czech.json +5 -0
  23. evals/mbert/eval_results_english.json +5 -0
  24. evals/mbert/eval_results_finnish.json +5 -0
  25. evals/mbert/eval_results_french.json +5 -0
  26. evals/mbert/eval_results_german.json +5 -0
  27. evals/mbert/eval_results_hindi.json +5 -0
  28. evals/mbert/eval_results_hungarian.json +5 -0
  29. evals/mbert/eval_results_italian.json +5 -0
  30. evals/mbert/eval_results_portuguese.json +5 -0
  31. evals/mbert/eval_results_russian.json +5 -0
  32. evals/mbert/eval_results_spanish.json +5 -0
  33. flax_model.msgpack +3 -0
  34. model.safetensors +3 -0
  35. pytorch_model.bin +3 -0
  36. run.sh +27 -0
  37. run_eval.sh +27 -0
  38. run_evals.sh +31 -0
  39. run_mlm_flax.py +745 -0
  40. run_mlm_flax_eval.py +828 -0
  41. special_tokens_map.json +1 -0
  42. tokenizer.json +0 -0
  43. tokenizer_config.json +1 -0
  44. training_state.json +1 -0
  45. vocab.txt +0 -0
README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: es
3
+ license: cc-by-4.0
4
+ tags:
5
+ - multilingual
6
+ - bert
7
+ pipeline_tag: fill-mask
8
+ widget:
9
+ - text: ¿Qué es la vida? Un [MASK].
10
+ ---
11
+
12
+ # ALBERTI
13
+
14
+ ALBERTI is a set of two BERT-based multilingual model for poetry. One for verses and another one for stanzas. This model has been further trained with the PULPO corpus for verses using [Flax](https://github.com/google/flax), including training scripts.
15
+
16
+ This is part of the
17
+ [Flax/Jax Community Week](https://discuss.huggingface.co/t/open-to-the-community-community-week-using-jax-flax-for-nlp-cv/7104), organised by [HuggingFace](https://huggingface.co/) and TPU usage sponsored by Google.
18
+
19
+ ## PULPO
20
+
21
+ PULPO, the Prodigious Unannotated Literary Poetry Corpus, is a set of multilingual corpora of verses and stanzas with over 95M words.
22
+
23
+ The following corpora has been downloaded using the [Averell](https://github.com/linhd-postdata/averell/) tool, developed by the [POSTDATA](https://postdata.linhd.uned.es/) team:
24
+
25
+ ### Spanish
26
+ - [Disco v3](https://github.com/pruizf/disco)
27
+ - [Corpus of Spanish Golden-Age Sonnets](https://github.com/bncolorado/CorpusSonetosSigloDeOro)
28
+ - [Corpus general de poesía lírica castellana del Siglo de Oro](https://github.com/bncolorado/CorpusGeneralPoesiaLiricaCastellanaDelSigloDeOro)
29
+ - [Gongocorpus](https://github.com/linhd-postdata/gongocorpus) - [source](http://obvil.sorbonne-universite.site/corpus/gongora/gongora_obra-poetica)
30
+ ### English
31
+ - [Eighteenth-Century Poetry Archive (ECPA)](https://github.com/alhuber1502/ECPA)
32
+ - [For better for verse](https://github.com/waynegraham/for_better_for_verse)
33
+ ### French
34
+ - [Métrique en Ligne](https://crisco2.unicaen.fr/verlaine/index.php?navigation=accueil) - [source](https://github.com/linhd-postdata/metrique-en-ligne)
35
+ ### Italian
36
+ - [Biblioteca italiana](https://github.com/linhd-postdata/biblioteca_italiana) - [source](http://www.bibliotecaitaliana.it/)
37
+ ### Czech
38
+ - [Corpus of Czech Verse](https://github.com/versotym/corpusCzechVerse)
39
+ ### Portuguese
40
+ - [Stichotheque](https://gitlab.com/stichotheque/stichotheque-pt)
41
+
42
+ Also, we obtained the following corpora from these sources:
43
+ ### Spanish
44
+ - [Poesi.as](https://github.com/linhd-postdata/poesi.as) - [source](http://www.poesi.as/)
45
+ ### English
46
+ - [A Gutenberg Poetry Corpus](https://github.com/aparrish/gutenberg-poetry-corpus)
47
+ ### Arabic
48
+ - [Arabic Poetry dataset](https://www.kaggle.com/ahmedabelal/arabic-poetry)
49
+ ### Chinese
50
+ - [THU Chinese Classical Poetry Corpus](https://github.com/THUNLP-AIPoet/Datasets/tree/master/CCPC)
51
+ ### Finnish
52
+ - [SKVR](https://github.com/sks190/SKVR)
53
+ ### German
54
+ - [TextGrid Poetry Corpus](https://github.com/linhd-postdata/textgrid-poetry) - [source](https://textgrid.de/en/digitale-bibliothek)
55
+ - [German Rhyme Corpus](https://github.com/tnhaider/german-rhyme-corpus)
56
+ ### Hungarian
57
+ - [verskorpusz](https://github.com/ELTE-DH/verskorpusz)
58
+ ### Portuguese
59
+ - [Poems in Portuguese](https://www.kaggle.com/oliveirasp6/poems-in-portuguese)
60
+ ### Russian
61
+ - [19 000 Russian poems](https://www.kaggle.com/grafstor/19-000-russian-poems)
62
+
63
+ ## Team members
64
+
65
+ - Álvaro Pérez ([alvp](https://huggingface.co/alvp))
66
+ - Javier de la Rosa ([versae](https://huggingface.co/versae))
67
+ - Aitor Díaz ([aitordiaz](https://huggingface.co/aitordiaz))
68
+ - Elena González-Blanco
69
+ - Salvador Ros ([salva](https://huggingface.co/salva))
70
+
71
+ ## Useful links
72
+
73
+ - [Community Week timeline](https://discuss.huggingface.co/t/open-to-the-community-community-week-using-jax-flax-for-nlp-cv/7104#summary-timeline-calendar-6)
74
+ - [Community Week README](https://github.com/huggingface/transformers/blob/master/examples/research_projects/jax-projects/README.md)
75
+ - [Community Week thread](https://discuss.huggingface.co/t/bertin-pretrain-roberta-large-from-scratch-in-spanish/7125)
76
+ - [Community Week channel](https://discord.com/channels/858019234139602994/859113060068229190)
77
+ - [Masked Language Modelling example scripts](https://github.com/huggingface/transformers/tree/master/examples/flax/language-modeling)
78
+ - [Model Repository](https://huggingface.co/flax-community/alberti-bert-base-multilingual-cased/)
79
+
80
+ ## Acknowledgments
81
+
82
+ This project would not have been possible without the infrastructure and resources provided by HuggingFace and Google Cloud. Moreover, we want to thank POSTDATA Project (ERC-StG-679528) and the Computational Literary Studies Infrastructure (CLS INFRA No. 101004984) of the European Union's Horizon 2020 research and innovation programme for their support and time allowance.
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "directionality": "bidi",
7
+ "gradient_checkpointing": false,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 768,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 3072,
13
+ "layer_norm_eps": 1e-12,
14
+ "max_position_embeddings": 512,
15
+ "model_type": "bert",
16
+ "num_attention_heads": 12,
17
+ "num_hidden_layers": 12,
18
+ "pad_token_id": 0,
19
+ "pooler_fc_size": 768,
20
+ "pooler_num_attention_heads": 12,
21
+ "pooler_num_fc_layers": 3,
22
+ "pooler_size_per_head": 128,
23
+ "pooler_type": "first_token_transform",
24
+ "position_embedding_type": "absolute",
25
+ "transformers_version": "4.9.0.dev0",
26
+ "type_vocab_size": 2,
27
+ "use_cache": true,
28
+ "vocab_size": 119547
29
+ }
config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from transformers import BertConfig
4
+
5
+ config = BertConfig.from_pretrained("bert-base-multilingual-cased")
6
+
7
+ config.save_pretrained("./")
convert.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #!/usr/bin/env python
3
+ import tempfile
4
+ import jax
5
+ from jax import numpy as jnp
6
+ from transformers import AutoTokenizer, FlaxRobertaForMaskedLM, RobertaForMaskedLM, FlaxBertForMaskedLM, BertForMaskedLM
7
+
8
+
9
+ def main():
10
+ # Saving extra files from config.json and tokenizer.json files
11
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
12
+ tokenizer.save_pretrained("./")
13
+ # Temporary saving bfloat16 Flax model into float32
14
+ tmp = tempfile.mkdtemp()
15
+ #flax_model = FlaxRobertaForMaskedLM.from_pretrained("./")
16
+ flax_model = FlaxBertForMaskedLM.from_pretrained("./")
17
+ flax_model.save_pretrained(tmp)
18
+ # Converting float32 Flax to PyTorch
19
+ #model = RobertaForMaskedLM.from_pretrained(tmp, from_flax=True)
20
+ model = BertForMaskedLM.from_pretrained(tmp, from_flax=True)
21
+ model.save_pretrained("./", save_config=False)
22
+
23
+
24
+ if __name__ == "__main__":
25
+ main()
evals/alberti/eval_results_arabic.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.6408291005392143,
3
+ "eval_loss": 1.505015057336042,
4
+ "eval_perplexity": 4.504221451353881
5
+ }
evals/alberti/eval_results_chinese.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.31155171271450344,
3
+ "eval_loss": 3.9333015512157954,
4
+ "eval_perplexity": 51.07532741795546
5
+ }
evals/alberti/eval_results_czech.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.6062408166567269,
3
+ "eval_loss": 1.8359284606976425,
4
+ "eval_perplexity": 6.270953777486964
5
+ }
evals/alberti/eval_results_english.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5320815459645918,
3
+ "eval_loss": 2.394027611476076,
4
+ "eval_perplexity": 10.957537892911233
5
+ }
evals/alberti/eval_results_finnish.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.6272082468928667,
3
+ "eval_loss": 1.845318445734281,
4
+ "eval_perplexity": 6.330115267679467
5
+ }
evals/alberti/eval_results_french.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5842149738042928,
3
+ "eval_loss": 2.0680841484282575,
4
+ "eval_perplexity": 7.909654867720871
5
+ }
evals/alberti/eval_results_german.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5835830474456813,
3
+ "eval_loss": 1.9559251674484819,
4
+ "eval_perplexity": 7.070457355700252
5
+ }
evals/alberti/eval_results_hindi.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.07489781581300294,
3
+ "eval_loss": 9.280142339379232,
4
+ "eval_perplexity": 10722.958107026718
5
+ }
evals/alberti/eval_results_hungarian.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5566523349747832,
3
+ "eval_loss": 2.1803966072570926,
4
+ "eval_perplexity": 8.849815463823662
5
+ }
evals/alberti/eval_results_italian.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5162272232348571,
3
+ "eval_loss": 2.477469312651519,
4
+ "eval_perplexity": 11.91108301701437
5
+ }
evals/alberti/eval_results_portuguese.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.4926062056586033,
3
+ "eval_loss": 2.7949925894154566,
4
+ "eval_perplexity": 16.362507496962778
5
+ }
evals/alberti/eval_results_russian.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5853658536585366,
3
+ "eval_loss": 2.086235640967887,
4
+ "eval_perplexity": 8.054537852308378
5
+ }
evals/alberti/eval_results_spanish.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5859480165147395,
3
+ "eval_loss": 2.084652532470857,
4
+ "eval_perplexity": 8.04179673294292
5
+ }
evals/eval_results_alberti.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.5680093428409695,
3
+ "eval_loss": 2.2008613169662152,
4
+ "eval_perplexity": 9.032790245322317
5
+ }
evals/eval_results_mbert.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.2531256913599916,
3
+ "eval_loss": 4.986973319130462,
4
+ "eval_perplexity": 146.49236618254264
5
+ }
evals/mbert/eval_results_arabic.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.26391261358166496,
3
+ "eval_loss": 3.8152461392225794,
4
+ "eval_perplexity": 45.38792675716374
5
+ }
evals/mbert/eval_results_chinese.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.09895315709269198,
3
+ "eval_loss": 6.6723325796726956,
4
+ "eval_perplexity": 790.2367464940897
5
+ }
evals/mbert/eval_results_czech.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.2773844709547667,
3
+ "eval_loss": 4.42254573093298,
4
+ "eval_perplexity": 83.30809563399087
5
+ }
evals/mbert/eval_results_english.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.2975008599745663,
3
+ "eval_loss": 4.490137260330782,
4
+ "eval_perplexity": 89.13367955737988
5
+ }
evals/mbert/eval_results_finnish.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.22131404624517728,
3
+ "eval_loss": 5.228847592703858,
4
+ "eval_perplexity": 186.57766611729022
5
+ }
evals/mbert/eval_results_french.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.36305560250126756,
3
+ "eval_loss": 3.776505989099206,
4
+ "eval_perplexity": 43.66321515247085
5
+ }
evals/mbert/eval_results_german.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.27947910102919554,
3
+ "eval_loss": 4.477016383112791,
4
+ "eval_perplexity": 87.97180655711638
5
+ }
evals/mbert/eval_results_hindi.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.3055626516796526,
3
+ "eval_loss": 3.95077246854643,
4
+ "eval_perplexity": 51.97550077126472
5
+ }
evals/mbert/eval_results_hungarian.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.29008286594165167,
3
+ "eval_loss": 4.358099513515926,
4
+ "eval_perplexity": 78.10854903381517
5
+ }
evals/mbert/eval_results_italian.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.2593468204267504,
3
+ "eval_loss": 4.857048540301865,
4
+ "eval_perplexity": 128.6439537945917
5
+ }
evals/mbert/eval_results_portuguese.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.2960448389972281,
3
+ "eval_loss": 4.607839268924084,
4
+ "eval_perplexity": 100.2672648109061
5
+ }
evals/mbert/eval_results_russian.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.28699294248879165,
3
+ "eval_loss": 4.441657214642727,
4
+ "eval_perplexity": 84.91554842410918
5
+ }
evals/mbert/eval_results_spanish.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "eval_accuracy": 0.3220253743973355,
3
+ "eval_loss": 4.129566473031045,
4
+ "eval_perplexity": 62.15097297048524
5
+ }
flax_model.msgpack ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53d0ce75962d5d739f9bc2f5d6cdc40155753ddf8be1524112c95477237751cf
3
+ size 711905363
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a5e2e38ef7342bc73dd33611f57c5123c491f12560fb32cec11dffe442572af
3
+ size 711926000
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74e76b0ba8bee646b78f7efdbdf3cd500ca183bc26439944fc1733f48a77f5ba
3
+ size 711980011
run.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # From https://arxiv.org/pdf/1907.11692.pdf
2
+ ./run_mlm_flax.py \
3
+ --model_name_or_path="bert-base-multilingual-cased" \
4
+ --output_dir="./" \
5
+ --model_type="bert" \
6
+ --config_name="./" \
7
+ --validation_file="./datasets/pulpo_lines_clean_val.json" \
8
+ --train_file="./datasets/pulpo_lines_clean_train.json" \
9
+ --tokenizer_name="bert-base-multilingual-cased" \
10
+ --max_seq_length="32" \
11
+ --pad_to_max_length \
12
+ --per_device_train_batch_size="256" \
13
+ --per_device_eval_batch_size="256" \
14
+ --adam_beta1="0.9" \
15
+ --adam_beta2="0.98" \
16
+ --adam_epsilon="1e-6" \
17
+ --learning_rate="1.25e-4" \
18
+ --weight_decay="0.01" \
19
+ --save_strategy="steps" \
20
+ --save_steps="1000" \
21
+ --save_total_limit="5" \
22
+ --warmup_steps="10000" \
23
+ --num_train_epochs="40" \
24
+ --overwrite_output_dir \
25
+ --eval_steps="1000" \
26
+ --save_total_limit="1000" \
27
+ --logging_steps="500" 2>&1 | tee run.log
run_eval.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # From https://arxiv.org/pdf/1907.11692.pdf
2
+ ./run_mlm_flax_eval.py \
3
+ --model_name_or_path="flax-community/alberti-bert-base-multilingual-cased" \
4
+ --output_dir="./" \
5
+ --model_type="bert" \
6
+ --config_name="./" \
7
+ --validation_file="./pulpo_lines_val.json" \
8
+ --train_file="./pulpo_lines_train.json" \
9
+ --tokenizer_name="bert-base-multilingual-cased" \
10
+ --max_seq_length="32" \
11
+ --pad_to_max_length \
12
+ --per_device_train_batch_size="256" \
13
+ --per_device_eval_batch_size="256" \
14
+ --adam_beta1="0.9" \
15
+ --adam_beta2="0.98" \
16
+ --adam_epsilon="1e-6" \
17
+ --learning_rate="1.25e-4" \
18
+ --weight_decay="0.01" \
19
+ --save_steps="1000" \
20
+ --warmup_steps="10000" \
21
+ --num_train_epochs="40" \
22
+ --overwrite_output_dir \
23
+ --eval_steps="1000" \
24
+ --do_train="false" \
25
+ --do_eval="true" \
26
+ --preprocessing_num_workers="96" \
27
+ --logging_steps="500" 2>&1 | tee run.log
run_evals.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ for lang in "arabic" "chinese" "czech" "english" "finnish" "french" "german" "hindi" "hungarian" "italian" "portuguese" "russian" "spanish" "turkish"
2
+ do
3
+ echo "";
4
+ echo "$lang";
5
+ ./run_mlm_flax_eval.py \
6
+ --model_name_or_path="bert-base-multilingual-cased" \
7
+ --output_dir="./" \
8
+ --model_type="bert" \
9
+ --config_name="./" \
10
+ --validation_file="./pulpo_lines_val.json" \
11
+ --train_file="./pulpo_lines_train.json" \
12
+ --tokenizer_name="bert-base-multilingual-cased" \
13
+ --max_seq_length="32" \
14
+ --pad_to_max_length \
15
+ --per_device_train_batch_size="256" \
16
+ --per_device_eval_batch_size="256" \
17
+ --adam_beta1="0.9" \
18
+ --adam_beta2="0.98" \
19
+ --adam_epsilon="1e-6" \
20
+ --learning_rate="1.25e-4" \
21
+ --weight_decay="0.01" \
22
+ --save_steps="1000" \
23
+ --warmup_steps="10000" \
24
+ --num_train_epochs="40" \
25
+ --overwrite_output_dir \
26
+ --eval_steps="1000" \
27
+ --do_train="false" \
28
+ --do_eval="true" \
29
+ --lang="$lang" \
30
+ --logging_steps="500"
31
+ done
run_mlm_flax.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Team 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 masked language modeling (BERT, ALBERT, RoBERTa...) with whole word masking on a
18
+ text file or a dataset.
19
+
20
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
21
+ https://huggingface.co/models?filter=masked-lm
22
+ """
23
+ import json
24
+ import logging
25
+ import os
26
+ import shutil
27
+ import sys
28
+ import time
29
+ from dataclasses import dataclass, field
30
+
31
+ # You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
32
+ from pathlib import Path
33
+ from typing import Dict, List, Optional, Tuple
34
+
35
+ import joblib
36
+ import numpy as np
37
+ from datasets import load_dataset
38
+ from tqdm import tqdm
39
+
40
+ import flax
41
+ import jax
42
+ import jax.numpy as jnp
43
+ import optax
44
+ from flax import jax_utils, traverse_util
45
+ from flax.serialization import from_bytes, to_bytes
46
+ from flax.training import train_state
47
+ from flax.training.common_utils import get_metrics, onehot, shard
48
+ from transformers import (
49
+ CONFIG_MAPPING,
50
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
51
+ AutoConfig,
52
+ AutoTokenizer,
53
+ FlaxAutoModelForMaskedLM,
54
+ HfArgumentParser,
55
+ PreTrainedTokenizerBase,
56
+ TensorType,
57
+ TrainingArguments,
58
+ is_tensorboard_available,
59
+ set_seed,
60
+ )
61
+
62
+ print("TPU count:", jax.device_count())
63
+
64
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
65
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
66
+
67
+
68
+
69
+ @dataclass
70
+ class ModelArguments:
71
+ """
72
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
73
+ """
74
+
75
+ model_name_or_path: Optional[str] = field(
76
+ default=None,
77
+ metadata={
78
+ "help": "The model checkpoint for weights initialization."
79
+ "Don't set if you want to train a model from scratch."
80
+ },
81
+ )
82
+ model_type: Optional[str] = field(
83
+ default=None,
84
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
85
+ )
86
+ config_name: Optional[str] = field(
87
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
88
+ )
89
+ tokenizer_name: Optional[str] = field(
90
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
91
+ )
92
+ cache_dir: Optional[str] = field(
93
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
94
+ )
95
+ use_fast_tokenizer: bool = field(
96
+ default=True,
97
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
98
+ )
99
+ dtype: Optional[str] = field(
100
+ default="float32",
101
+ metadata={
102
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
103
+ },
104
+ )
105
+
106
+
107
+ @dataclass
108
+ class DataTrainingArguments:
109
+ """
110
+ Arguments pertaining to what data we are going to input our model for training and eval.
111
+ """
112
+
113
+ dataset_name: Optional[str] = field(
114
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
115
+ )
116
+ dataset_config_name: Optional[str] = field(
117
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
118
+ )
119
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
120
+ validation_file: Optional[str] = field(
121
+ default=None,
122
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
123
+ )
124
+ train_ref_file: Optional[str] = field(
125
+ default=None,
126
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
127
+ )
128
+ validation_ref_file: Optional[str] = field(
129
+ default=None,
130
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
131
+ )
132
+ overwrite_cache: bool = field(
133
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
134
+ )
135
+ validation_split_percentage: Optional[int] = field(
136
+ default=5,
137
+ metadata={
138
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
139
+ },
140
+ )
141
+ max_seq_length: Optional[int] = field(
142
+ default=None,
143
+ metadata={
144
+ "help": "The maximum total input sequence length after tokenization. Sequences longer "
145
+ "than this will be truncated. Default to the max input length of the model."
146
+ },
147
+ )
148
+ preprocessing_num_workers: Optional[int] = field(
149
+ default=None,
150
+ metadata={"help": "The number of processes to use for the preprocessing."},
151
+ )
152
+ mlm_probability: float = field(
153
+ default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
154
+ )
155
+ pad_to_max_length: bool = field(
156
+ default=False,
157
+ metadata={
158
+ "help": "Whether to pad all samples to `max_seq_length`. "
159
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
160
+ },
161
+ )
162
+ line_by_line: bool = field(
163
+ default=False,
164
+ metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
165
+ )
166
+
167
+ def __post_init__(self):
168
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
169
+ raise ValueError("Need either a dataset name or a training/validation file.")
170
+ else:
171
+ if self.train_file is not None:
172
+ extension = self.train_file.split(".")[-1]
173
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
174
+ if self.validation_file is not None:
175
+ extension = self.validation_file.split(".")[-1]
176
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
177
+
178
+
179
+ @flax.struct.dataclass
180
+ class FlaxDataCollatorForLanguageModeling:
181
+ """
182
+ Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
183
+ are not all of the same length.
184
+
185
+ Args:
186
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
187
+ The tokenizer used for encoding the data.
188
+ mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
189
+ The probability with which to (randomly) mask tokens in the input.
190
+
191
+ .. note::
192
+
193
+ For best performance, this data collator should be used with a dataset having items that are dictionaries or
194
+ BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
195
+ :class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
196
+ argument :obj:`return_special_tokens_mask=True`.
197
+ """
198
+
199
+ tokenizer: PreTrainedTokenizerBase
200
+ mlm_probability: float = 0.15
201
+
202
+ def __post_init__(self):
203
+ if self.tokenizer.mask_token is None:
204
+ raise ValueError(
205
+ "This tokenizer does not have a mask token which is necessary for masked language modeling. "
206
+ "You should pass `mlm=False` to train on causal language modeling instead."
207
+ )
208
+
209
+ def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
210
+ # Handle dict or lists with proper padding and conversion to tensor.
211
+ batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
212
+
213
+ # If special token mask has been preprocessed, pop it from the dict.
214
+ special_tokens_mask = batch.pop("special_tokens_mask", None)
215
+
216
+ batch["input_ids"], batch["labels"] = self.mask_tokens(
217
+ batch["input_ids"], special_tokens_mask=special_tokens_mask
218
+ )
219
+ return batch
220
+
221
+ def mask_tokens(
222
+ self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
223
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
224
+ """
225
+ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
226
+ """
227
+ labels = inputs.copy()
228
+ # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
229
+ probability_matrix = np.full(labels.shape, self.mlm_probability)
230
+ special_tokens_mask = special_tokens_mask.astype("bool")
231
+
232
+ probability_matrix[special_tokens_mask] = 0.0
233
+ masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
234
+ labels[~masked_indices] = -100 # We only compute loss on masked tokens
235
+
236
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
237
+ indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
238
+ inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
239
+
240
+ # 10% of the time, we replace masked input tokens with random word
241
+ indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
242
+ indices_random &= masked_indices & ~indices_replaced
243
+
244
+ random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
245
+ inputs[indices_random] = random_words[indices_random]
246
+
247
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
248
+ return inputs, labels
249
+
250
+
251
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
252
+ num_samples = len(samples_idx)
253
+ samples_to_remove = num_samples % batch_size
254
+
255
+ if samples_to_remove != 0:
256
+ samples_idx = samples_idx[:-samples_to_remove]
257
+ sections_split = num_samples // batch_size
258
+ batch_idx = np.split(samples_idx, sections_split)
259
+ return batch_idx
260
+
261
+
262
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
263
+ summary_writer.scalar("train_time", train_time, step)
264
+
265
+ train_metrics = get_metrics(train_metrics)
266
+ for key, vals in train_metrics.items():
267
+ tag = f"train_{key}"
268
+ for i, val in enumerate(vals):
269
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
270
+
271
+
272
+ def write_eval_metric(summary_writer, eval_metrics, step):
273
+ for metric_name, value in eval_metrics.items():
274
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
275
+
276
+
277
+ def rotate_checkpoints(path, max_checkpoints=5):
278
+ paths = sorted(Path(path).iterdir(), key=os.path.getmtime)[::-1]
279
+ if len(paths) > max_checkpoints:
280
+ for path_to_delete in paths[max_checkpoints:]:
281
+ try:
282
+ shutil.rmtree(path_to_delete)
283
+ except OSError:
284
+ os.remove(path_to_delete)
285
+
286
+
287
+ def save_checkpoint_files(state, data_collator, training_args, save_dir):
288
+ unreplicated_state = jax_utils.unreplicate(state)
289
+ with open(os.path.join(save_dir, "optimizer_state.msgpack"), "wb") as f:
290
+ f.write(to_bytes(unreplicated_state.opt_state))
291
+ joblib.dump(training_args, os.path.join(save_dir, "training_args.joblib"))
292
+ joblib.dump(data_collator, os.path.join(save_dir, "data_collator.joblib"))
293
+ with open(os.path.join(save_dir, "training_state.json"), "w") as f:
294
+ json.dump({"step": unreplicated_state.step.item()}, f)
295
+
296
+
297
+
298
+ if __name__ == "__main__":
299
+ # See all possible arguments in src/transformers/training_args.py
300
+ # or by passing the --help flag to this script.
301
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
302
+
303
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
304
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
305
+ # If we pass only one argument to the script and it's the path to a json file,
306
+ # let's parse it to get our arguments.
307
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
308
+ else:
309
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
310
+
311
+ if (
312
+ os.path.exists(training_args.output_dir)
313
+ and os.listdir(training_args.output_dir)
314
+ and training_args.do_train
315
+ and not training_args.overwrite_output_dir
316
+ ):
317
+ raise ValueError(
318
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
319
+ "Use --overwrite_output_dir to overcome."
320
+ )
321
+
322
+ # Setup logging
323
+ logging.basicConfig(
324
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
325
+ level="NOTSET",
326
+ datefmt="[%X]",
327
+ )
328
+
329
+ # Log on each process the small summary:
330
+ logger = logging.getLogger(__name__)
331
+ #logger.warning(
332
+ # f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
333
+ # + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
334
+ #)
335
+
336
+ # Set the verbosity to info of the Transformers logger (on main process only):
337
+ logger.info(f"Training/evaluation parameters {training_args}")
338
+
339
+ # Set seed before initializing model.
340
+ set_seed(training_args.seed)
341
+
342
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
343
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
344
+ # (the dataset will be downloaded automatically from the datasets Hub).
345
+ #
346
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
347
+ # 'text' is found. You can easily tweak this behavior (see below).
348
+ #
349
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
350
+ # download the dataset.
351
+
352
+ #datasets = load_dataset('json', name='averell', data_files={"train": "./datasets/lines_train.json", "validation": "./datasets/lines_val.json"})
353
+
354
+ if data_args.dataset_name is not None:
355
+ # Downloading and loading a dataset from the hub.
356
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
357
+
358
+ if "validation" not in datasets.keys():
359
+ datasets["validation"] = load_dataset(
360
+ data_args.dataset_name,
361
+ data_args.dataset_config_name,
362
+ split=f"train[:{data_args.validation_split_percentage}%]",
363
+ cache_dir=model_args.cache_dir,
364
+ )
365
+ datasets["train"] = load_dataset(
366
+ data_args.dataset_name,
367
+ data_args.dataset_config_name,
368
+ split=f"train[{data_args.validation_split_percentage}%:]",
369
+ cache_dir=model_args.cache_dir,
370
+ )
371
+ else:
372
+ #### Custom dataset
373
+ data_files = {}
374
+ if data_args.train_file is not None:
375
+ data_files["train"] = data_args.train_file
376
+ if data_args.validation_file is not None:
377
+ data_files["validation"] = data_args.validation_file
378
+ extension = data_args.train_file.split(".")[-1]
379
+ if extension == "txt":
380
+ extension = "text"
381
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
382
+ #datasets = load_dataset('json', name='averell', data_files={"train": "./datasets/lines_train.json", "validation": "./datasets/lines_val.json"})
383
+
384
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
385
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
386
+
387
+ # Load pretrained model and tokenizer
388
+
389
+ # Distributed training:
390
+ # The .from_pretrained methods guarantee that only one local process can concurrently
391
+ # download model & vocab.
392
+ if model_args.config_name:
393
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
394
+ elif model_args.model_name_or_path:
395
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
396
+ else:
397
+ config = CONFIG_MAPPING[model_args.model_type]()
398
+ logger.warning("You are instantiating a new config instance from scratch.")
399
+
400
+ if model_args.tokenizer_name:
401
+ tokenizer = AutoTokenizer.from_pretrained(
402
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
403
+ )
404
+ elif model_args.model_name_or_path:
405
+ tokenizer = AutoTokenizer.from_pretrained(
406
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
407
+ )
408
+ else:
409
+ raise ValueError(
410
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
411
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
412
+ )
413
+
414
+ # Preprocessing the datasets.
415
+ # First we tokenize all the texts.
416
+ if training_args.do_train:
417
+ column_names = datasets["train"].column_names
418
+ else:
419
+ column_names = datasets["validation"].column_names
420
+ text_column_name = "text" if "text" in column_names else column_names[0]
421
+
422
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
423
+
424
+ if data_args.line_by_line:
425
+ # When using line_by_line, we just tokenize each nonempty line.
426
+ padding = "max_length" if data_args.pad_to_max_length else False
427
+
428
+ def tokenize_function(examples):
429
+ # Remove empty lines
430
+ examples = [line for line in examples if len(line) > 0 and not line.isspace()]
431
+ return tokenizer(
432
+ examples,
433
+ return_special_tokens_mask=True,
434
+ padding=padding,
435
+ truncation=True,
436
+ max_length=max_seq_length,
437
+ )
438
+
439
+ tokenized_datasets = datasets.map(
440
+ tokenize_function,
441
+ input_columns=[text_column_name],
442
+ batched=True,
443
+ num_proc=data_args.preprocessing_num_workers,
444
+ remove_columns=column_names,
445
+ load_from_cache_file=not data_args.overwrite_cache,
446
+ )
447
+
448
+ else:
449
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
450
+ # We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
451
+ # efficient when it receives the `special_tokens_mask`.
452
+ def tokenize_function(examples):
453
+ return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
454
+
455
+ tokenized_datasets = datasets.map(
456
+ tokenize_function,
457
+ batched=True,
458
+ num_proc=data_args.preprocessing_num_workers,
459
+ remove_columns=column_names,
460
+ load_from_cache_file=not data_args.overwrite_cache,
461
+ )
462
+
463
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of
464
+ # max_seq_length.
465
+ def group_texts(examples):
466
+ # Concatenate all texts.
467
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
468
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
469
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
470
+ # customize this part to your needs.
471
+ total_length = (total_length // max_seq_length) * max_seq_length
472
+ # Split by chunks of max_len.
473
+ result = {
474
+ k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
475
+ for k, t in concatenated_examples.items()
476
+ }
477
+ return result
478
+
479
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
480
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
481
+ # might be slower to preprocess.
482
+ #
483
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
484
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
485
+ tokenized_datasets = tokenized_datasets.map(
486
+ group_texts,
487
+ batched=True,
488
+ num_proc=data_args.preprocessing_num_workers,
489
+ load_from_cache_file=not data_args.overwrite_cache,
490
+ )
491
+
492
+ # Enable tensorboard only on the master node
493
+ has_tensorboard = is_tensorboard_available()
494
+ if has_tensorboard and jax.process_index() == 0:
495
+ try:
496
+ import wandb
497
+ wandb.init(
498
+ entity='wandb',
499
+ project='hf-flax-alberti-poetry',
500
+ sync_tensorboard=True,
501
+ )
502
+ wandb.config.update(training_args)
503
+ wandb.config.update(model_args)
504
+ wandb.config.update(data_args)
505
+
506
+ from flax.metrics.tensorboard import SummaryWriter
507
+
508
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir) / "logs")
509
+
510
+
511
+ except ImportError as ie:
512
+ has_tensorboard = False
513
+ logger.warning(
514
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
515
+ )
516
+ else:
517
+ logger.warning(
518
+ "Unable to display metrics through TensorBoard because the package is not installed: "
519
+ "Please run pip install tensorboard to enable."
520
+ )
521
+
522
+ # Data collator
523
+ # This one will take care of randomly masking the tokens.
524
+ data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
525
+
526
+ # Initialize our training
527
+ rng = jax.random.PRNGKey(training_args.seed)
528
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
529
+
530
+ if model_args.model_name_or_path:
531
+ model = FlaxAutoModelForMaskedLM.from_pretrained(
532
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
533
+ )
534
+ else:
535
+ model = FlaxAutoModelForMaskedLM.from_config(
536
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
537
+ )
538
+
539
+ # Store some constant
540
+ num_epochs = int(training_args.num_train_epochs)
541
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
542
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
543
+
544
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
545
+
546
+ # Create learning rate schedule
547
+ warmup_fn = optax.linear_schedule(
548
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
549
+ )
550
+ decay_fn = optax.linear_schedule(
551
+ init_value=training_args.learning_rate,
552
+ end_value=0,
553
+ transition_steps=num_train_steps - training_args.warmup_steps,
554
+ )
555
+ linear_decay_lr_schedule_fn = optax.join_schedules(
556
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
557
+ )
558
+
559
+ # We use Optax's "masking" functionality to not apply weight decay
560
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
561
+ # mask boolean with the same structure as the parameters.
562
+ # The mask is True for parameters that should be decayed.
563
+ # Note that this mask is specifically adapted for FlaxBERT-like models.
564
+ # For other models, one should correct the layer norm parameter naming
565
+ # accordingly.
566
+ def decay_mask_fn(params):
567
+ flat_params = traverse_util.flatten_dict(params)
568
+ flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
569
+ return traverse_util.unflatten_dict(flat_mask)
570
+
571
+ # create adam optimizer
572
+ if training_args.adafactor:
573
+ # We use the default parameters here to initialize adafactor,
574
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
575
+ optimizer = optax.adafactor(
576
+ learning_rate=linear_decay_lr_schedule_fn,
577
+ )
578
+ else:
579
+ optimizer = optax.adamw(
580
+ learning_rate=linear_decay_lr_schedule_fn,
581
+ b1=training_args.adam_beta1,
582
+ b2=training_args.adam_beta2,
583
+ eps=training_args.adam_epsilon,
584
+ weight_decay=training_args.weight_decay,
585
+ mask=decay_mask_fn,
586
+ )
587
+
588
+ # Setup train state
589
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
590
+
591
+ # Define gradient update step fn
592
+ def train_step(state, batch, dropout_rng):
593
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
594
+
595
+ def loss_fn(params):
596
+ labels = batch.pop("labels")
597
+
598
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
599
+
600
+ # compute loss, ignore padded input tokens
601
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
602
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
603
+
604
+ # take average
605
+ loss = loss.sum() / label_mask.sum()
606
+
607
+ return loss
608
+
609
+ grad_fn = jax.value_and_grad(loss_fn)
610
+ loss, grad = grad_fn(state.params)
611
+ grad = jax.lax.pmean(grad, "batch")
612
+ new_state = state.apply_gradients(grads=grad)
613
+
614
+ metrics = jax.lax.pmean(
615
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
616
+ )
617
+
618
+ return new_state, metrics, new_dropout_rng
619
+
620
+ # Create parallel version of the train step
621
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
622
+
623
+ # Define eval fn
624
+ def eval_step(params, batch):
625
+ labels = batch.pop("labels")
626
+
627
+ logits = model(**batch, params=params, train=False)[0]
628
+
629
+ # compute loss, ignore padded input tokens
630
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
631
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
632
+
633
+ # compute accuracy
634
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
635
+
636
+ # summarize metrics
637
+ metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
638
+ metrics = jax.lax.psum(metrics, axis_name="batch")
639
+
640
+ return metrics
641
+
642
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
643
+
644
+ # Replicate the train state on each device
645
+ state = jax_utils.replicate(state)
646
+
647
+ train_time = 0
648
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
649
+ for epoch in epochs:
650
+ # ======================== Training ================================
651
+ train_start = time.time()
652
+ train_metrics = []
653
+
654
+ # Create sampling rng
655
+ rng, input_rng = jax.random.split(rng)
656
+
657
+ # Generate an epoch by shuffling sampling indices from the train dataset
658
+ num_train_samples = len(tokenized_datasets["train"])
659
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
660
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
661
+
662
+ # Gather the indexes for creating the batch and do a training step
663
+ for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
664
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
665
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
666
+
667
+ # Model forward
668
+ model_inputs = shard(model_inputs.data)
669
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
670
+ train_metrics.append(train_metric)
671
+
672
+ cur_step = epoch * (num_train_samples // train_batch_size) + step
673
+
674
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
675
+ # Save metrics
676
+ train_metric = jax_utils.unreplicate(train_metric)
677
+ train_time += time.time() - train_start
678
+ if has_tensorboard and jax.process_index() == 0:
679
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
680
+
681
+ epochs.write(
682
+ f"Step... ({cur_step} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
683
+ )
684
+
685
+ train_metrics = []
686
+
687
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
688
+ # ======================== Evaluating ==============================
689
+ num_eval_samples = len(tokenized_datasets["validation"])
690
+ eval_samples_idx = jnp.arange(num_eval_samples)
691
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
692
+
693
+ eval_metrics = []
694
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
695
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
696
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
697
+
698
+ # Model forward
699
+ model_inputs = shard(model_inputs.data)
700
+ metrics = p_eval_step(state.params, model_inputs)
701
+ eval_metrics.append(metrics)
702
+
703
+ # normalize eval metrics
704
+ eval_metrics = get_metrics(eval_metrics)
705
+ eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
706
+ eval_normalizer = eval_metrics.pop("normalizer")
707
+ eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
708
+
709
+ # Update progress bar
710
+ epochs.desc = f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
711
+
712
+ # Save metrics
713
+ if has_tensorboard and jax.process_index() == 0:
714
+ cur_step = epoch * (len(tokenized_datasets["train"]) // train_batch_size)
715
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
716
+
717
+ # if cur_step % training_args.save_steps == 0 and cur_step > 0:
718
+ # # save checkpoint after each epoch and push checkpoint to the hub
719
+ # if jax.process_index() == 0:
720
+ # params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
721
+ # model.save_pretrained(
722
+ # training_args.output_dir,
723
+ # params=params,
724
+ # push_to_hub=training_args.push_to_hub,
725
+ # commit_message=f"Saving weights and logs of step {cur_step}",
726
+ # )
727
+ # save checkpoint after eval_steps
728
+ if step % training_args.save_steps == 0 and step > 0 and jax.process_index() == 0:
729
+ logger.info(f"Saving checkpoint at {step + 1} steps")
730
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
731
+ model.save_pretrained(
732
+ training_args.output_dir,
733
+ params=params,
734
+ push_to_hub=training_args.push_to_hub,
735
+ commit_message=f"Saving weights and logs of step {step}",
736
+ )
737
+ save_checkpoint_files(state, data_collator, training_args, training_args.output_dir)
738
+ checkpoints_dir = Path(training_args.output_dir) / "checkpoints" / f"checkpoint-{step}"
739
+ checkpoints_dir.mkdir(parents=True, exist_ok=True)
740
+ model.save_pretrained(checkpoints_dir, params=params,)
741
+ save_checkpoint_files(state, data_collator, training_args, checkpoints_dir)
742
+ rotate_checkpoints(
743
+ Path(training_args.output_dir) / "checkpoints",
744
+ max_checkpoints=training_args.save_total_limit
745
+ )
run_mlm_flax_eval.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Team 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 masked language modeling (BERT, ALBERT, RoBERTa...) with whole word masking on a
18
+ text file or a dataset.
19
+
20
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
21
+ https://huggingface.co/models?filter=fill-mask
22
+ """
23
+ import json
24
+ import logging
25
+ import math
26
+ import os
27
+ import sys
28
+ import time
29
+ from dataclasses import asdict, dataclass, field
30
+ from enum import Enum
31
+ from itertools import chain
32
+
33
+ # You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
34
+ from pathlib import Path
35
+ from typing import Dict, List, Optional, Tuple
36
+
37
+ import numpy as np
38
+ from datasets import load_dataset
39
+ from tqdm import tqdm
40
+
41
+ import flax
42
+ import jax
43
+ import jax.numpy as jnp
44
+ import optax
45
+ from flax import jax_utils, traverse_util
46
+ from flax.training import train_state
47
+ from flax.training.common_utils import get_metrics, onehot, shard
48
+ from huggingface_hub import Repository
49
+ from transformers import (
50
+ CONFIG_MAPPING,
51
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
52
+ AutoConfig,
53
+ AutoTokenizer,
54
+ FlaxAutoModelForMaskedLM,
55
+ HfArgumentParser,
56
+ PreTrainedTokenizerBase,
57
+ TensorType,
58
+ is_tensorboard_available,
59
+ set_seed,
60
+ )
61
+ from transformers.file_utils import get_full_repo_name
62
+
63
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
64
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
65
+
66
+
67
+ @dataclass
68
+ class TrainingArguments:
69
+ output_dir: str = field(
70
+ metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
71
+ )
72
+ overwrite_output_dir: bool = field(
73
+ default=False,
74
+ metadata={
75
+ "help": (
76
+ "Overwrite the content of the output directory. "
77
+ "Use this to continue training if output_dir points to a checkpoint directory."
78
+ )
79
+ },
80
+ )
81
+ do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
82
+ do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
83
+ per_device_train_batch_size: int = field(
84
+ default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."}
85
+ )
86
+ per_device_eval_batch_size: int = field(
87
+ default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}
88
+ )
89
+ learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
90
+ weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
91
+ adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
92
+ adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
93
+ adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
94
+ adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
95
+ num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
96
+ warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})
97
+ logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."})
98
+ save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."})
99
+ eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."})
100
+ seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
101
+ push_to_hub: bool = field(
102
+ default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."}
103
+ )
104
+ hub_model_id: str = field(
105
+ default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."}
106
+ )
107
+ hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."})
108
+
109
+ def __post_init__(self):
110
+ if self.output_dir is not None:
111
+ self.output_dir = os.path.expanduser(self.output_dir)
112
+
113
+ def to_dict(self):
114
+ """
115
+ Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
116
+ the token values by removing their value.
117
+ """
118
+ d = asdict(self)
119
+ for k, v in d.items():
120
+ if isinstance(v, Enum):
121
+ d[k] = v.value
122
+ if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):
123
+ d[k] = [x.value for x in v]
124
+ if k.endswith("_token"):
125
+ d[k] = f"<{k.upper()}>"
126
+ return d
127
+
128
+
129
+ @dataclass
130
+ class ModelArguments:
131
+ """
132
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
133
+ """
134
+
135
+ model_name_or_path: Optional[str] = field(
136
+ default=None,
137
+ metadata={
138
+ "help": "The model checkpoint for weights initialization."
139
+ "Don't set if you want to train a model from scratch."
140
+ },
141
+ )
142
+ model_type: Optional[str] = field(
143
+ default=None,
144
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
145
+ )
146
+ config_name: Optional[str] = field(
147
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
148
+ )
149
+ tokenizer_name: Optional[str] = field(
150
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
151
+ )
152
+ cache_dir: Optional[str] = field(
153
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
154
+ )
155
+ use_fast_tokenizer: bool = field(
156
+ default=True,
157
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
158
+ )
159
+ dtype: Optional[str] = field(
160
+ default="float32",
161
+ metadata={
162
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
163
+ },
164
+ )
165
+
166
+
167
+ @dataclass
168
+ class DataTrainingArguments:
169
+ """
170
+ Arguments pertaining to what data we are going to input our model for training and eval.
171
+ """
172
+
173
+ dataset_name: Optional[str] = field(
174
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
175
+ )
176
+ dataset_config_name: Optional[str] = field(
177
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
178
+ )
179
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
180
+ validation_file: Optional[str] = field(
181
+ default=None,
182
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
183
+ )
184
+ train_ref_file: Optional[str] = field(
185
+ default=None,
186
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
187
+ )
188
+ validation_ref_file: Optional[str] = field(
189
+ default=None,
190
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
191
+ )
192
+ overwrite_cache: bool = field(
193
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
194
+ )
195
+ validation_split_percentage: Optional[int] = field(
196
+ default=5,
197
+ metadata={
198
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
199
+ },
200
+ )
201
+ max_seq_length: Optional[int] = field(
202
+ default=None,
203
+ metadata={
204
+ "help": "The maximum total input sequence length after tokenization. Sequences longer "
205
+ "than this will be truncated. Default to the max input length of the model."
206
+ },
207
+ )
208
+ preprocessing_num_workers: Optional[int] = field(
209
+ default=None,
210
+ metadata={"help": "The number of processes to use for the preprocessing."},
211
+ )
212
+ mlm_probability: float = field(
213
+ default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
214
+ )
215
+ pad_to_max_length: bool = field(
216
+ default=False,
217
+ metadata={
218
+ "help": "Whether to pad all samples to `max_seq_length`. "
219
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
220
+ },
221
+ )
222
+ line_by_line: bool = field(
223
+ default=False,
224
+ metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
225
+ )
226
+ lang: Optional[str] = field(
227
+ default=None,
228
+ metadata={"help": "Langauge to filter a dataset entries by."},
229
+ )
230
+
231
+
232
+ def __post_init__(self):
233
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
234
+ raise ValueError("Need either a dataset name or a training/validation file.")
235
+ else:
236
+ if self.train_file is not None:
237
+ extension = self.train_file.split(".")[-1]
238
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
239
+ if self.validation_file is not None:
240
+ extension = self.validation_file.split(".")[-1]
241
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
242
+
243
+
244
+ @flax.struct.dataclass
245
+ class FlaxDataCollatorForLanguageModeling:
246
+ """
247
+ Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
248
+ are not all of the same length.
249
+
250
+ Args:
251
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
252
+ The tokenizer used for encoding the data.
253
+ mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
254
+ The probability with which to (randomly) mask tokens in the input.
255
+
256
+ .. note::
257
+
258
+ For best performance, this data collator should be used with a dataset having items that are dictionaries or
259
+ BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
260
+ :class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
261
+ argument :obj:`return_special_tokens_mask=True`.
262
+ """
263
+
264
+ tokenizer: PreTrainedTokenizerBase
265
+ mlm_probability: float = 0.15
266
+
267
+ def __post_init__(self):
268
+ if self.tokenizer.mask_token is None:
269
+ raise ValueError(
270
+ "This tokenizer does not have a mask token which is necessary for masked language modeling. "
271
+ "You should pass `mlm=False` to train on causal language modeling instead."
272
+ )
273
+
274
+ def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
275
+ # Handle dict or lists with proper padding and conversion to tensor.
276
+ batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
277
+
278
+ # If special token mask has been preprocessed, pop it from the dict.
279
+ special_tokens_mask = batch.pop("special_tokens_mask", None)
280
+
281
+ batch["input_ids"], batch["labels"] = self.mask_tokens(
282
+ batch["input_ids"], special_tokens_mask=special_tokens_mask
283
+ )
284
+ return batch
285
+
286
+ def mask_tokens(
287
+ self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
288
+ ) -> Tuple[np.ndarray, np.ndarray]:
289
+ """
290
+ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
291
+ """
292
+ labels = inputs.copy()
293
+ # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
294
+ probability_matrix = np.full(labels.shape, self.mlm_probability)
295
+ special_tokens_mask = special_tokens_mask.astype("bool")
296
+
297
+ probability_matrix[special_tokens_mask] = 0.0
298
+ masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
299
+ labels[~masked_indices] = -100 # We only compute loss on masked tokens
300
+
301
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
302
+ indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
303
+ inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
304
+
305
+ # 10% of the time, we replace masked input tokens with random word
306
+ indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
307
+ indices_random &= masked_indices & ~indices_replaced
308
+
309
+ random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
310
+ inputs[indices_random] = random_words[indices_random]
311
+
312
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
313
+ return inputs, labels
314
+
315
+
316
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
317
+ num_samples = len(samples_idx)
318
+ samples_to_remove = num_samples % batch_size
319
+
320
+ if samples_to_remove != 0:
321
+ samples_idx = samples_idx[:-samples_to_remove]
322
+ sections_split = num_samples // batch_size
323
+ batch_idx = np.split(samples_idx, sections_split)
324
+ return batch_idx
325
+
326
+
327
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
328
+ summary_writer.scalar("train_time", train_time, step)
329
+
330
+ train_metrics = get_metrics(train_metrics)
331
+ for key, vals in train_metrics.items():
332
+ tag = f"train_{key}"
333
+ for i, val in enumerate(vals):
334
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
335
+
336
+
337
+ def write_eval_metric(summary_writer, eval_metrics, step):
338
+ for metric_name, value in eval_metrics.items():
339
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
340
+
341
+
342
+ def main():
343
+ # See all possible arguments in src/transformers/training_args.py
344
+ # or by passing the --help flag to this script.
345
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
346
+
347
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
348
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
349
+ # If we pass only one argument to the script and it's the path to a json file,
350
+ # let's parse it to get our arguments.
351
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
352
+ else:
353
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
354
+
355
+ if (
356
+ os.path.exists(training_args.output_dir)
357
+ and os.listdir(training_args.output_dir)
358
+ and training_args.do_train
359
+ and not training_args.overwrite_output_dir
360
+ ):
361
+ raise ValueError(
362
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
363
+ "Use --overwrite_output_dir to overcome."
364
+ )
365
+
366
+ # Setup logging
367
+ logging.basicConfig(
368
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
369
+ level=logging.INFO,
370
+ datefmt="[%X]",
371
+ )
372
+
373
+ # Log on each process the small summary:
374
+ logger = logging.getLogger(__name__)
375
+
376
+ # Set the verbosity to info of the Transformers logger (on main process only):
377
+ logger.info(f"Training/evaluation parameters {training_args}")
378
+
379
+ # Set seed before initializing model.
380
+ set_seed(training_args.seed)
381
+
382
+ # Handle the repository creation
383
+ if training_args.push_to_hub:
384
+ if training_args.hub_model_id is None:
385
+ repo_name = get_full_repo_name(
386
+ Path(training_args.output_dir).absolute().name, token=training_args.hub_token
387
+ )
388
+ else:
389
+ repo_name = training_args.hub_model_id
390
+ repo = Repository(training_args.output_dir, clone_from=repo_name)
391
+
392
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
393
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
394
+ # (the dataset will be downloaded automatically from the datasets Hub).
395
+ #
396
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
397
+ # 'text' is found. You can easily tweak this behavior (see below).
398
+ #
399
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
400
+ # download the dataset.
401
+ if data_args.dataset_name is not None:
402
+ # Downloading and loading a dataset from the hub.
403
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
404
+
405
+ if "validation" not in datasets.keys():
406
+ datasets["validation"] = load_dataset(
407
+ data_args.dataset_name,
408
+ data_args.dataset_config_name,
409
+ split=f"train[:{data_args.validation_split_percentage}%]",
410
+ cache_dir=model_args.cache_dir,
411
+ )
412
+ datasets["train"] = load_dataset(
413
+ data_args.dataset_name,
414
+ data_args.dataset_config_name,
415
+ split=f"train[{data_args.validation_split_percentage}%:]",
416
+ cache_dir=model_args.cache_dir,
417
+ )
418
+ else:
419
+ data_files = {}
420
+ if data_args.train_file is not None:
421
+ data_files["train"] = data_args.train_file
422
+ if data_args.validation_file is not None:
423
+ data_files["validation"] = data_args.validation_file
424
+ extension = data_args.train_file.split(".")[-1]
425
+ if extension == "txt":
426
+ extension = "text"
427
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
428
+
429
+ if "validation" not in datasets.keys():
430
+ datasets["validation"] = load_dataset(
431
+ extension,
432
+ data_files=data_files,
433
+ split=f"train[:{data_args.validation_split_percentage}%]",
434
+ cache_dir=model_args.cache_dir,
435
+ )
436
+ datasets["train"] = load_dataset(
437
+ extension,
438
+ data_files=data_files,
439
+ split=f"train[{data_args.validation_split_percentage}%:]",
440
+ cache_dir=model_args.cache_dir,
441
+ )
442
+ if data_args.lang is not None:
443
+ datasets = datasets.filter(lambda x: x["lang"] == data_args.lang)
444
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
445
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
446
+
447
+ # Load pretrained model and tokenizer
448
+
449
+ # Distributed training:
450
+ # The .from_pretrained methods guarantee that only one local process can concurrently
451
+ # download model & vocab.
452
+ if model_args.config_name:
453
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
454
+ elif model_args.model_name_or_path:
455
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
456
+ else:
457
+ config = CONFIG_MAPPING[model_args.model_type]()
458
+ logger.warning("You are instantiating a new config instance from scratch.")
459
+
460
+ if model_args.tokenizer_name:
461
+ tokenizer = AutoTokenizer.from_pretrained(
462
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
463
+ )
464
+ elif model_args.model_name_or_path:
465
+ tokenizer = AutoTokenizer.from_pretrained(
466
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
467
+ )
468
+ else:
469
+ raise ValueError(
470
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
471
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
472
+ )
473
+
474
+ # Preprocessing the datasets.
475
+ # First we tokenize all the texts.
476
+ if training_args.do_train:
477
+ column_names = datasets["train"].column_names
478
+ else:
479
+ column_names = datasets["validation"].column_names
480
+ text_column_name = "text" if "text" in column_names else column_names[0]
481
+
482
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
483
+
484
+ if data_args.line_by_line:
485
+ # When using line_by_line, we just tokenize each nonempty line.
486
+ padding = "max_length" if data_args.pad_to_max_length else False
487
+
488
+ def tokenize_function(examples):
489
+ # Remove empty lines
490
+ examples = [line for line in examples if len(line) > 0 and not line.isspace()]
491
+ return tokenizer(
492
+ examples,
493
+ return_special_tokens_mask=True,
494
+ padding=padding,
495
+ truncation=True,
496
+ max_length=max_seq_length,
497
+ )
498
+
499
+ tokenized_datasets = datasets.map(
500
+ tokenize_function,
501
+ input_columns=[text_column_name],
502
+ batched=True,
503
+ num_proc=data_args.preprocessing_num_workers,
504
+ remove_columns=column_names,
505
+ load_from_cache_file=not data_args.overwrite_cache,
506
+ )
507
+
508
+ else:
509
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
510
+ # We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
511
+ # efficient when it receives the `special_tokens_mask`.
512
+ def tokenize_function(examples):
513
+ return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
514
+
515
+ tokenized_datasets = datasets.map(
516
+ tokenize_function,
517
+ batched=True,
518
+ num_proc=data_args.preprocessing_num_workers,
519
+ remove_columns=column_names,
520
+ load_from_cache_file=not data_args.overwrite_cache,
521
+ )
522
+
523
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of
524
+ # max_seq_length.
525
+ def group_texts(examples):
526
+ # Concatenate all texts.
527
+ concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
528
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
529
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
530
+ # customize this part to your needs.
531
+ if total_length >= max_seq_length:
532
+ total_length = (total_length // max_seq_length) * max_seq_length
533
+ # Split by chunks of max_len.
534
+ result = {
535
+ k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
536
+ for k, t in concatenated_examples.items()
537
+ }
538
+ return result
539
+
540
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
541
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
542
+ # might be slower to preprocess.
543
+ #
544
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
545
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
546
+ tokenized_datasets = tokenized_datasets.map(
547
+ group_texts,
548
+ batched=True,
549
+ num_proc=data_args.preprocessing_num_workers,
550
+ load_from_cache_file=not data_args.overwrite_cache,
551
+ )
552
+
553
+ # Enable tensorboard only on the master node
554
+ has_tensorboard = is_tensorboard_available()
555
+ if has_tensorboard and jax.process_index() == 0:
556
+ try:
557
+ # Enable Weight&Biases
558
+ #import wandb
559
+ #wandb.init(
560
+ # entity='versae',
561
+ # project='roberta-base-ncc',
562
+ # sync_tensorboard=True,
563
+ #)
564
+ #wandb.config.update(training_args)
565
+ #wandb.config.update(model_args)
566
+ #wandb.config.update(data_args)
567
+
568
+ from flax.metrics.tensorboard import SummaryWriter
569
+
570
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
571
+ except ImportError as ie:
572
+ has_tensorboard = False
573
+ logger.warning(
574
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
575
+ )
576
+ else:
577
+ logger.warning(
578
+ "Unable to display metrics through TensorBoard because the package is not installed: "
579
+ "Please run pip install tensorboard to enable."
580
+ )
581
+
582
+ # Data collator
583
+ # This one will take care of randomly masking the tokens.
584
+ data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
585
+
586
+ # Initialize our training
587
+ rng = jax.random.PRNGKey(training_args.seed)
588
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
589
+
590
+ if model_args.model_name_or_path:
591
+ model = FlaxAutoModelForMaskedLM.from_pretrained(
592
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
593
+ )
594
+ else:
595
+ model = FlaxAutoModelForMaskedLM.from_config(
596
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
597
+ )
598
+
599
+ # Store some constant
600
+ num_epochs = int(training_args.num_train_epochs)
601
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
602
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
603
+
604
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
605
+
606
+ # Create learning rate schedule
607
+ warmup_fn = optax.linear_schedule(
608
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
609
+ )
610
+ decay_fn = optax.linear_schedule(
611
+ init_value=training_args.learning_rate,
612
+ end_value=0,
613
+ transition_steps=num_train_steps - training_args.warmup_steps,
614
+ )
615
+ linear_decay_lr_schedule_fn = optax.join_schedules(
616
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
617
+ )
618
+
619
+ # We use Optax's "masking" functionality to not apply weight decay
620
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
621
+ # mask boolean with the same structure as the parameters.
622
+ # The mask is True for parameters that should be decayed.
623
+ # Note that this mask is specifically adapted for FlaxBERT-like models.
624
+ # For other models, one should correct the layer norm parameter naming
625
+ # accordingly.
626
+ def decay_mask_fn(params):
627
+ flat_params = traverse_util.flatten_dict(params)
628
+ flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
629
+ return traverse_util.unflatten_dict(flat_mask)
630
+
631
+ # create adam optimizer
632
+ if training_args.adafactor:
633
+ # We use the default parameters here to initialize adafactor,
634
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
635
+ optimizer = optax.adafactor(
636
+ learning_rate=linear_decay_lr_schedule_fn,
637
+ )
638
+ else:
639
+ optimizer = optax.adamw(
640
+ learning_rate=linear_decay_lr_schedule_fn,
641
+ b1=training_args.adam_beta1,
642
+ b2=training_args.adam_beta2,
643
+ eps=training_args.adam_epsilon,
644
+ weight_decay=training_args.weight_decay,
645
+ mask=decay_mask_fn,
646
+ )
647
+
648
+ # Setup train state
649
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
650
+
651
+ # Define gradient update step fn
652
+ def train_step(state, batch, dropout_rng):
653
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
654
+
655
+ def loss_fn(params):
656
+ labels = batch.pop("labels")
657
+
658
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
659
+
660
+ # compute loss, ignore padded input tokens
661
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
662
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
663
+
664
+ # take average
665
+ loss = loss.sum() / label_mask.sum()
666
+
667
+ return loss
668
+
669
+ grad_fn = jax.value_and_grad(loss_fn)
670
+ loss, grad = grad_fn(state.params)
671
+ grad = jax.lax.pmean(grad, "batch")
672
+ new_state = state.apply_gradients(grads=grad)
673
+
674
+ metrics = jax.lax.pmean(
675
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
676
+ )
677
+
678
+ return new_state, metrics, new_dropout_rng
679
+
680
+ # Create parallel version of the train step
681
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
682
+
683
+ # Define eval fn
684
+ def eval_step(params, batch):
685
+ labels = batch.pop("labels")
686
+
687
+ logits = model(**batch, params=params, train=False)[0]
688
+
689
+ # compute loss, ignore padded input tokens
690
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
691
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
692
+
693
+ # compute accuracy
694
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
695
+
696
+ # summarize metrics
697
+ metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
698
+ metrics = jax.lax.psum(metrics, axis_name="batch")
699
+
700
+ return metrics
701
+
702
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
703
+
704
+ # Replicate the train state on each device
705
+ state = jax_utils.replicate(state)
706
+
707
+ train_time = 0
708
+ if training_args.do_train:
709
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
710
+ else:
711
+ epochs = []
712
+ for epoch in epochs:
713
+ # ======================== Training ================================
714
+ train_start = time.time()
715
+ train_metrics = []
716
+
717
+ # Create sampling rng
718
+ rng, input_rng = jax.random.split(rng)
719
+
720
+ # Generate an epoch by shuffling sampling indices from the train dataset
721
+ num_train_samples = len(tokenized_datasets["train"])
722
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
723
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
724
+
725
+ # Gather the indexes for creating the batch and do a training step
726
+ for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
727
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
728
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
729
+
730
+ # Model forward
731
+ model_inputs = shard(model_inputs.data)
732
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
733
+ train_metrics.append(train_metric)
734
+
735
+ cur_step = epoch * (num_train_samples // train_batch_size) + step
736
+
737
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
738
+ # Save metrics
739
+ train_metric = jax_utils.unreplicate(train_metric)
740
+ train_time += time.time() - train_start
741
+ if has_tensorboard and jax.process_index() == 0:
742
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
743
+
744
+ epochs.write(
745
+ f"Step... ({cur_step} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
746
+ )
747
+
748
+ train_metrics = []
749
+
750
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
751
+ # ======================== Evaluating ==============================
752
+ num_eval_samples = len(tokenized_datasets["validation"])
753
+ eval_samples_idx = jnp.arange(num_eval_samples)
754
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
755
+
756
+ eval_metrics = []
757
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
758
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
759
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
760
+
761
+ # Model forward
762
+ model_inputs = shard(model_inputs.data)
763
+ metrics = p_eval_step(state.params, model_inputs)
764
+ eval_metrics.append(metrics)
765
+
766
+ # normalize eval metrics
767
+ eval_metrics = get_metrics(eval_metrics)
768
+ eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
769
+ eval_normalizer = eval_metrics.pop("normalizer")
770
+ eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
771
+
772
+ # Update progress bar
773
+ epochs.desc = f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
774
+
775
+ # Save metrics
776
+ if has_tensorboard and jax.process_index() == 0:
777
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
778
+
779
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
780
+ # save checkpoint after each epoch and push checkpoint to the hub
781
+ if jax.process_index() == 0:
782
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
783
+ model.save_pretrained(training_args.output_dir, params=params)
784
+ tokenizer.save_pretrained(training_args.output_dir)
785
+ if training_args.push_to_hub:
786
+ repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False)
787
+
788
+ # Eval after training
789
+ if training_args.do_eval:
790
+ num_eval_samples = len(tokenized_datasets["validation"])
791
+ eval_samples_idx = jnp.arange(num_eval_samples)
792
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
793
+
794
+ eval_metrics = []
795
+ for _, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
796
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
797
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
798
+
799
+ # Model forward
800
+ model_inputs = shard(model_inputs.data)
801
+ metrics = p_eval_step(state.params, model_inputs)
802
+ eval_metrics.append(metrics)
803
+
804
+ # normalize eval metrics
805
+ eval_metrics = get_metrics(eval_metrics)
806
+ eval_metrics = jax.tree_map(lambda metric: jnp.sum(metric).item(), eval_metrics)
807
+ eval_normalizer = eval_metrics.pop("normalizer")
808
+ eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
809
+
810
+ try:
811
+ perplexity = math.exp(eval_metrics["loss"])
812
+ except OverflowError:
813
+ perplexity = float("inf")
814
+ eval_metrics["perplexity"] = perplexity
815
+
816
+ if data_args.lang is not None:
817
+ eval_filename = f"eval_results_{data_args.lang}.json"
818
+ else:
819
+ eval_filename = "eval_results.json"
820
+ if jax.process_index() == 0:
821
+ eval_metrics = {f"eval_{metric_name}": value for metric_name, value in eval_metrics.items()}
822
+ path = os.path.join(training_args.output_dir, eval_filename)
823
+ with open(path, "w") as f:
824
+ json.dump(eval_metrics, f, indent=4, sort_keys=True)
825
+
826
+
827
+ if __name__ == "__main__":
828
+ main()
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"do_lower_case": false, "unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]", "tokenize_chinese_chars": true, "strip_accents": null, "model_max_length": 512, "special_tokens_map_file": null, "name_or_path": "bert-base-multilingual-cased", "tokenizer_class": "BertTokenizer"}
training_state.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"step": 111279}
vocab.txt ADDED
The diff for this file is too large to render. See raw diff