AdithyaSK HF Staff commited on
Commit
d2c8cf9
·
verified ·
1 Parent(s): c956b6d

Stage Harbor release files 25001-25500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/token-classification/run_no_trainer.sh +21 -0
  2. tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/README.md +211 -0
  3. tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/requirements.txt +8 -0
  4. tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/run_translation.py +697 -0
  5. tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/run_translation_no_trainer.py +790 -0
  6. tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/xla_spawn.py +82 -0
  7. tasks/tasksmith-441eeab80047/tests/source/examples/quantization/custom_quantization.py +78 -0
  8. tasks/tasksmith-441eeab80047/tests/source/examples/quantization/custom_quantization_int8_example.py +257 -0
  9. tasks/tasksmith-441eeab80047/tests/source/examples/research_projects/README.md +20 -0
  10. tasks/tasksmith-441eeab80047/tests/source/examples/run_on_remote.py +71 -0
  11. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/README.md +44 -0
  12. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/_tests_requirements.txt +25 -0
  13. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/contrastive-image-text/README.md +81 -0
  14. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/contrastive-image-text/requirements.txt +2 -0
  15. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/contrastive-image-text/run_clip.py +611 -0
  16. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/image-classification/README.md +162 -0
  17. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/image-classification/requirements.txt +3 -0
  18. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/image-classification/run_image_classification.py +577 -0
  19. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/README.md +110 -0
  20. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/prepare_tfrecord_shards.py +192 -0
  21. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/requirements.txt +3 -0
  22. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/run_mlm.py +323 -0
  23. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/train_unigram.py +130 -0
  24. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/README.md +80 -0
  25. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/requirements.txt +2 -0
  26. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/run_clm.py +658 -0
  27. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/run_mlm.py +682 -0
  28. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/multiple-choice/README.md +43 -0
  29. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/multiple-choice/requirements.txt +3 -0
  30. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/multiple-choice/run_swag.py +504 -0
  31. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/README.md +57 -0
  32. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/requirements.txt +3 -0
  33. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/run_qa.py +831 -0
  34. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/utils_qa.py +444 -0
  35. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/summarization/README.md +40 -0
  36. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/summarization/requirements.txt +3 -0
  37. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/summarization/run_summarization.py +750 -0
  38. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/test_tensorflow_examples.py +338 -0
  39. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/README.md +115 -0
  40. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/requirements.txt +5 -0
  41. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/run_glue.py +600 -0
  42. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/run_text_classification.py +593 -0
  43. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/token-classification/README.md +47 -0
  44. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/token-classification/requirements.txt +3 -0
  45. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/token-classification/run_ner.py +636 -0
  46. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/translation/README.md +69 -0
  47. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/translation/requirements.txt +3 -0
  48. tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/translation/run_translation.py +716 -0
  49. tasks/tasksmith-441eeab80047/tests/source/examples/training/distributed_training.py +113 -0
  50. tasks/tasksmith-441eeab80047/tests/source/hubconf.py +162 -0
tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/token-classification/run_no_trainer.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ accelerate launch run_ner_no_trainer.py \
16
+ --model_name_or_path bert-base-uncased \
17
+ --dataset_name conll2003 \
18
+ --output_dir /tmp/test-ner \
19
+ --pad_to_max_length \
20
+ --task_name ner \
21
+ --return_entity_level_metrics
tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/README.md ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2020 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ ## Translation
18
+
19
+ This directory contains examples for finetuning and evaluating transformers on translation tasks.
20
+ Please tag @patil-suraj with any issues/unexpected behaviors, or send a PR!
21
+ For deprecated `bertabs` instructions, see https://github.com/huggingface/transformers-research-projects/blob/main/bertabs/README.md.
22
+ For the old `finetune_trainer.py` and related utils, see [`examples/legacy/seq2seq`](https://github.com/huggingface/transformers/blob/main/examples/legacy/seq2seq).
23
+
24
+ ### Supported Architectures
25
+
26
+ - `BartForConditionalGeneration`
27
+ - `FSMTForConditionalGeneration` (translation only)
28
+ - `MBartForConditionalGeneration`
29
+ - `MarianMTModel`
30
+ - `PegasusForConditionalGeneration`
31
+ - `T5ForConditionalGeneration`
32
+ - `MT5ForConditionalGeneration`
33
+
34
+ `run_translation.py` is a lightweight examples of how to download and preprocess a dataset from the [🤗 Datasets](https://github.com/huggingface/datasets) library or use your own files (jsonlines or csv), then fine-tune one of the architectures above on it.
35
+
36
+ For custom datasets in `jsonlines` format please see: https://huggingface.co/docs/datasets/loading_datasets#json-files
37
+ and you also will find examples of these below.
38
+
39
+
40
+ ## With Trainer
41
+
42
+ Here is an example of a translation fine-tuning with a MarianMT model:
43
+
44
+ ```bash
45
+ python examples/pytorch/translation/run_translation.py \
46
+ --model_name_or_path Helsinki-NLP/opus-mt-en-ro \
47
+ --do_train \
48
+ --do_eval \
49
+ --source_lang en \
50
+ --target_lang ro \
51
+ --dataset_name wmt16 \
52
+ --dataset_config_name ro-en \
53
+ --output_dir /tmp/tst-translation \
54
+ --per_device_train_batch_size=4 \
55
+ --per_device_eval_batch_size=4 \
56
+ --overwrite_output_dir \
57
+ --predict_with_generate
58
+ ```
59
+
60
+ MBart and some T5 models require special handling.
61
+
62
+ T5 models `google-t5/t5-small`, `google-t5/t5-base`, `google-t5/t5-large`, `google-t5/t5-3b` and `google-t5/t5-11b` must use an additional argument: `--source_prefix "translate {source_lang} to {target_lang}"`. For example:
63
+
64
+ ```bash
65
+ python examples/pytorch/translation/run_translation.py \
66
+ --model_name_or_path google-t5/t5-small \
67
+ --do_train \
68
+ --do_eval \
69
+ --source_lang en \
70
+ --target_lang ro \
71
+ --source_prefix "translate English to Romanian: " \
72
+ --dataset_name wmt16 \
73
+ --dataset_config_name ro-en \
74
+ --output_dir /tmp/tst-translation \
75
+ --per_device_train_batch_size=4 \
76
+ --per_device_eval_batch_size=4 \
77
+ --overwrite_output_dir \
78
+ --predict_with_generate
79
+ ```
80
+
81
+ If you get a terrible BLEU score, make sure that you didn't forget to use the `--source_prefix` argument.
82
+
83
+ For the aforementioned group of T5 models it's important to remember that if you switch to a different language pair, make sure to adjust the source and target values in all 3 language-specific command line argument: `--source_lang`, `--target_lang` and `--source_prefix`.
84
+
85
+ MBart models require a different format for `--source_lang` and `--target_lang` values, e.g. instead of `en` it expects `en_XX`, for `ro` it expects `ro_RO`. The full MBart specification for language codes can be found [here](https://huggingface.co/facebook/mbart-large-cc25). For example:
86
+
87
+ ```bash
88
+ python examples/pytorch/translation/run_translation.py \
89
+ --model_name_or_path facebook/mbart-large-en-ro \
90
+ --do_train \
91
+ --do_eval \
92
+ --dataset_name wmt16 \
93
+ --dataset_config_name ro-en \
94
+ --source_lang en_XX \
95
+ --target_lang ro_RO \
96
+ --output_dir /tmp/tst-translation \
97
+ --per_device_train_batch_size=4 \
98
+ --per_device_eval_batch_size=4 \
99
+ --overwrite_output_dir \
100
+ --predict_with_generate
101
+ ```
102
+
103
+ And here is how you would use the translation finetuning on your own files, after adjusting the
104
+ values for the arguments `--train_file`, `--validation_file` to match your setup:
105
+
106
+ ```bash
107
+ python examples/pytorch/translation/run_translation.py \
108
+ --model_name_or_path google-t5/t5-small \
109
+ --do_train \
110
+ --do_eval \
111
+ --source_lang en \
112
+ --target_lang ro \
113
+ --source_prefix "translate English to Romanian: " \
114
+ --dataset_name wmt16 \
115
+ --dataset_config_name ro-en \
116
+ --train_file path_to_jsonlines_file \
117
+ --validation_file path_to_jsonlines_file \
118
+ --output_dir /tmp/tst-translation \
119
+ --per_device_train_batch_size=4 \
120
+ --per_device_eval_batch_size=4 \
121
+ --overwrite_output_dir \
122
+ --predict_with_generate
123
+ ```
124
+
125
+ The task of translation supports only custom JSONLINES files, with each line being a dictionary with a key `"translation"` and its value another dictionary whose keys is the language pair. For example:
126
+
127
+ ```json
128
+ { "translation": { "en": "Others have dismissed him as a joke.", "ro": "Alții l-au numit o glumă." } }
129
+ { "translation": { "en": "And some are holding out for an implosion.", "ro": "Iar alții așteaptă implozia." } }
130
+ ```
131
+ Here the languages are Romanian (`ro`) and English (`en`).
132
+
133
+ If you want to use a pre-processed dataset that leads to high BLEU scores, but for the `en-de` language pair, you can use `--dataset_name stas/wmt14-en-de-pre-processed`, as following:
134
+
135
+ ```bash
136
+ python examples/pytorch/translation/run_translation.py \
137
+ --model_name_or_path google-t5/t5-small \
138
+ --do_train \
139
+ --do_eval \
140
+ --source_lang en \
141
+ --target_lang de \
142
+ --source_prefix "translate English to German: " \
143
+ --dataset_name stas/wmt14-en-de-pre-processed \
144
+ --output_dir /tmp/tst-translation \
145
+ --per_device_train_batch_size=4 \
146
+ --per_device_eval_batch_size=4 \
147
+ --overwrite_output_dir \
148
+ --predict_with_generate
149
+ ```
150
+
151
+ ## With Accelerate
152
+
153
+ Based on the script [`run_translation_no_trainer.py`](https://github.com/huggingface/transformers/blob/main/examples/pytorch/translation/run_translation_no_trainer.py).
154
+
155
+ Like `run_translation.py`, this script allows you to fine-tune any of the models supported on a
156
+ translation task, the main difference is that this
157
+ script exposes the bare training loop, to allow you to quickly experiment and add any customization you would like.
158
+
159
+ It offers less options than the script with `Trainer` (for instance you can easily change the options for the optimizer
160
+ or the dataloaders directly in the script) but still run in a distributed setup, on TPU and supports mixed precision by
161
+ the mean of the [🤗 `Accelerate`](https://github.com/huggingface/accelerate) library. You can use the script normally
162
+ after installing it:
163
+
164
+ ```bash
165
+ pip install git+https://github.com/huggingface/accelerate
166
+ ```
167
+
168
+ then
169
+
170
+ ```bash
171
+ python run_translation_no_trainer.py \
172
+ --model_name_or_path Helsinki-NLP/opus-mt-en-ro \
173
+ --source_lang en \
174
+ --target_lang ro \
175
+ --dataset_name wmt16 \
176
+ --dataset_config_name ro-en \
177
+ --output_dir ~/tmp/tst-translation
178
+ ```
179
+
180
+ You can then use your usual launchers to run in it in a distributed environment, but the easiest way is to run
181
+
182
+ ```bash
183
+ accelerate config
184
+ ```
185
+
186
+ and reply to the questions asked. Then
187
+
188
+ ```bash
189
+ accelerate test
190
+ ```
191
+
192
+ that will check everything is ready for training. Finally, you can launch training with
193
+
194
+ ```bash
195
+ accelerate launch run_translation_no_trainer.py \
196
+ --model_name_or_path Helsinki-NLP/opus-mt-en-ro \
197
+ --source_lang en \
198
+ --target_lang ro \
199
+ --dataset_name wmt16 \
200
+ --dataset_config_name ro-en \
201
+ --output_dir ~/tmp/tst-translation
202
+ ```
203
+
204
+ This command is the same and will work for:
205
+
206
+ - a CPU-only setup
207
+ - a setup with one GPU
208
+ - a distributed training with several GPUs (single or multi node)
209
+ - a training on TPUs
210
+
211
+ Note that this library is in alpha release so your feedback is more than welcome if you encounter any problem using it.
tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate >= 0.12.0
2
+ datasets >= 1.8.0
3
+ sentencepiece != 0.1.92
4
+ protobuf
5
+ sacrebleu >= 1.4.12
6
+ py7zr
7
+ torch >= 1.3
8
+ evaluate
tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/run_translation.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright The HuggingFace Team and The HuggingFace Inc. 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 sequence to sequence.
18
+ """
19
+ # You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
20
+
21
+ import logging
22
+ import os
23
+ import sys
24
+ from dataclasses import dataclass, field
25
+ from typing import Optional
26
+
27
+ import datasets
28
+ import evaluate
29
+ import numpy as np
30
+ from datasets import load_dataset
31
+
32
+ import transformers
33
+ from transformers import (
34
+ AutoConfig,
35
+ AutoModelForSeq2SeqLM,
36
+ AutoTokenizer,
37
+ DataCollatorForSeq2Seq,
38
+ HfArgumentParser,
39
+ M2M100Tokenizer,
40
+ MBart50Tokenizer,
41
+ MBart50TokenizerFast,
42
+ MBartTokenizer,
43
+ MBartTokenizerFast,
44
+ Seq2SeqTrainer,
45
+ Seq2SeqTrainingArguments,
46
+ default_data_collator,
47
+ set_seed,
48
+ )
49
+ from transformers.trainer_utils import get_last_checkpoint
50
+ from transformers.utils import check_min_version, send_example_telemetry
51
+ from transformers.utils.versions import require_version
52
+
53
+
54
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
55
+ check_min_version("4.50.0.dev0")
56
+
57
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/translation/requirements.txt")
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+ # A list of all multilingual tokenizer which require src_lang and tgt_lang attributes.
62
+ MULTILINGUAL_TOKENIZERS = [MBartTokenizer, MBartTokenizerFast, MBart50Tokenizer, MBart50TokenizerFast, M2M100Tokenizer]
63
+
64
+
65
+ @dataclass
66
+ class ModelArguments:
67
+ """
68
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
69
+ """
70
+
71
+ model_name_or_path: str = field(
72
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
73
+ )
74
+ config_name: Optional[str] = field(
75
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
76
+ )
77
+ tokenizer_name: Optional[str] = field(
78
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
79
+ )
80
+ cache_dir: Optional[str] = field(
81
+ default=None,
82
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
83
+ )
84
+ use_fast_tokenizer: bool = field(
85
+ default=True,
86
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
87
+ )
88
+ model_revision: str = field(
89
+ default="main",
90
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
91
+ )
92
+ token: str = field(
93
+ default=None,
94
+ metadata={
95
+ "help": (
96
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
97
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
98
+ )
99
+ },
100
+ )
101
+ trust_remote_code: bool = field(
102
+ default=False,
103
+ metadata={
104
+ "help": (
105
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
106
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
107
+ " code, as it will execute code present on the Hub on your local machine."
108
+ )
109
+ },
110
+ )
111
+
112
+
113
+ @dataclass
114
+ class DataTrainingArguments:
115
+ """
116
+ Arguments pertaining to what data we are going to input our model for training and eval.
117
+ """
118
+
119
+ source_lang: str = field(default=None, metadata={"help": "Source language id for translation."})
120
+ target_lang: str = field(default=None, metadata={"help": "Target language id for translation."})
121
+
122
+ dataset_name: Optional[str] = field(
123
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
124
+ )
125
+ dataset_config_name: Optional[str] = field(
126
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
127
+ )
128
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a jsonlines)."})
129
+ validation_file: Optional[str] = field(
130
+ default=None,
131
+ metadata={
132
+ "help": "An optional input evaluation data file to evaluate the metrics (sacrebleu) on a jsonlines file."
133
+ },
134
+ )
135
+ test_file: Optional[str] = field(
136
+ default=None,
137
+ metadata={"help": "An optional input test data file to evaluate the metrics (sacrebleu) on a jsonlines file."},
138
+ )
139
+ overwrite_cache: bool = field(
140
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
141
+ )
142
+ preprocessing_num_workers: Optional[int] = field(
143
+ default=None,
144
+ metadata={"help": "The number of processes to use for the preprocessing."},
145
+ )
146
+ max_source_length: Optional[int] = field(
147
+ default=1024,
148
+ metadata={
149
+ "help": (
150
+ "The maximum total input sequence length after tokenization. Sequences longer "
151
+ "than this will be truncated, sequences shorter will be padded."
152
+ )
153
+ },
154
+ )
155
+ max_target_length: Optional[int] = field(
156
+ default=128,
157
+ metadata={
158
+ "help": (
159
+ "The maximum total sequence length for target text after tokenization. Sequences longer "
160
+ "than this will be truncated, sequences shorter will be padded."
161
+ )
162
+ },
163
+ )
164
+ val_max_target_length: Optional[int] = field(
165
+ default=None,
166
+ metadata={
167
+ "help": (
168
+ "The maximum total sequence length for validation target text after tokenization. Sequences longer "
169
+ "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`. "
170
+ "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
171
+ "during ``evaluate`` and ``predict``."
172
+ )
173
+ },
174
+ )
175
+ pad_to_max_length: bool = field(
176
+ default=False,
177
+ metadata={
178
+ "help": (
179
+ "Whether to pad all samples to model maximum sentence length. "
180
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
181
+ "efficient on GPU but very bad for TPU."
182
+ )
183
+ },
184
+ )
185
+ max_train_samples: Optional[int] = field(
186
+ default=None,
187
+ metadata={
188
+ "help": (
189
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
190
+ "value if set."
191
+ )
192
+ },
193
+ )
194
+ max_eval_samples: Optional[int] = field(
195
+ default=None,
196
+ metadata={
197
+ "help": (
198
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
199
+ "value if set."
200
+ )
201
+ },
202
+ )
203
+ max_predict_samples: Optional[int] = field(
204
+ default=None,
205
+ metadata={
206
+ "help": (
207
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
208
+ "value if set."
209
+ )
210
+ },
211
+ )
212
+ num_beams: Optional[int] = field(
213
+ default=1,
214
+ metadata={
215
+ "help": (
216
+ "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
217
+ "which is used during ``evaluate`` and ``predict``."
218
+ )
219
+ },
220
+ )
221
+ ignore_pad_token_for_loss: bool = field(
222
+ default=True,
223
+ metadata={
224
+ "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
225
+ },
226
+ )
227
+ source_prefix: Optional[str] = field(
228
+ default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
229
+ )
230
+ forced_bos_token: Optional[str] = field(
231
+ default=None,
232
+ metadata={
233
+ "help": (
234
+ "The token to force as the first generated token after the :obj:`decoder_start_token_id`.Useful for"
235
+ " multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token needs to"
236
+ " be the target language token.(Usually it is the target language token)"
237
+ )
238
+ },
239
+ )
240
+
241
+ def __post_init__(self):
242
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
243
+ raise ValueError("Need either a dataset name or a training/validation file.")
244
+ elif self.source_lang is None or self.target_lang is None:
245
+ raise ValueError("Need to specify the source language and the target language.")
246
+
247
+ # accepting both json and jsonl file extensions, as
248
+ # many jsonlines files actually have a .json extension
249
+ valid_extensions = ["json", "jsonl"]
250
+
251
+ if self.train_file is not None:
252
+ extension = self.train_file.split(".")[-1]
253
+ assert extension in valid_extensions, "`train_file` should be a jsonlines file."
254
+ if self.validation_file is not None:
255
+ extension = self.validation_file.split(".")[-1]
256
+ assert extension in valid_extensions, "`validation_file` should be a jsonlines file."
257
+ if self.val_max_target_length is None:
258
+ self.val_max_target_length = self.max_target_length
259
+
260
+
261
+ def main():
262
+ # See all possible arguments in src/transformers/training_args.py
263
+ # or by passing the --help flag to this script.
264
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
265
+
266
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
267
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
268
+ # If we pass only one argument to the script and it's the path to a json file,
269
+ # let's parse it to get our arguments.
270
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
271
+ else:
272
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
273
+
274
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
275
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
276
+ send_example_telemetry("run_translation", model_args, data_args)
277
+
278
+ # Setup logging
279
+ logging.basicConfig(
280
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
281
+ datefmt="%m/%d/%Y %H:%M:%S",
282
+ handlers=[logging.StreamHandler(sys.stdout)],
283
+ )
284
+
285
+ if training_args.should_log:
286
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
287
+ transformers.utils.logging.set_verbosity_info()
288
+
289
+ log_level = training_args.get_process_log_level()
290
+ logger.setLevel(log_level)
291
+ datasets.utils.logging.set_verbosity(log_level)
292
+ transformers.utils.logging.set_verbosity(log_level)
293
+ transformers.utils.logging.enable_default_handler()
294
+ transformers.utils.logging.enable_explicit_format()
295
+
296
+ # Log on each process the small summary:
297
+ logger.warning(
298
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
299
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
300
+ )
301
+ logger.info(f"Training/evaluation parameters {training_args}")
302
+
303
+ if data_args.source_prefix is None and model_args.model_name_or_path in [
304
+ "google-t5/t5-small",
305
+ "google-t5/t5-base",
306
+ "google-t5/t5-large",
307
+ "google-t5/t5-3b",
308
+ "google-t5/t5-11b",
309
+ ]:
310
+ logger.warning(
311
+ "You're running a t5 model but didn't provide a source prefix, which is expected, e.g. with "
312
+ "`--source_prefix 'translate English to German: ' `"
313
+ )
314
+
315
+ # Detecting last checkpoint.
316
+ last_checkpoint = None
317
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
318
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
319
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
320
+ raise ValueError(
321
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
322
+ "Use --overwrite_output_dir to overcome."
323
+ )
324
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
325
+ logger.info(
326
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
327
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
328
+ )
329
+
330
+ # Set seed before initializing model.
331
+ set_seed(training_args.seed)
332
+
333
+ # Get the datasets: you can either provide your own JSON training and evaluation files (see below)
334
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
335
+ # (the dataset will be downloaded automatically from the datasets Hub).
336
+ #
337
+ # For translation, only JSON files are supported, with one field named "translation" containing two keys for the
338
+ # source and target languages (unless you adapt what follows).
339
+ #
340
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
341
+ # download the dataset.
342
+ if data_args.dataset_name is not None:
343
+ # Downloading and loading a dataset from the hub.
344
+ raw_datasets = load_dataset(
345
+ data_args.dataset_name,
346
+ data_args.dataset_config_name,
347
+ cache_dir=model_args.cache_dir,
348
+ token=model_args.token,
349
+ trust_remote_code=model_args.trust_remote_code,
350
+ )
351
+ else:
352
+ data_files = {}
353
+ if data_args.train_file is not None:
354
+ data_files["train"] = data_args.train_file
355
+ extension = data_args.train_file.split(".")[-1]
356
+ if data_args.validation_file is not None:
357
+ data_files["validation"] = data_args.validation_file
358
+ extension = data_args.validation_file.split(".")[-1]
359
+ if data_args.test_file is not None:
360
+ data_files["test"] = data_args.test_file
361
+ extension = data_args.test_file.split(".")[-1]
362
+ if extension == "jsonl":
363
+ builder_name = "json" # the "json" builder reads both .json and .jsonl files
364
+ else:
365
+ builder_name = extension # e.g. "parquet"
366
+ raw_datasets = load_dataset(
367
+ builder_name,
368
+ data_files=data_files,
369
+ cache_dir=model_args.cache_dir,
370
+ token=model_args.token,
371
+ )
372
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
373
+ # https://huggingface.co/docs/datasets/loading.
374
+
375
+ # Load pretrained model and tokenizer
376
+ #
377
+ # Distributed training:
378
+ # The .from_pretrained methods guarantee that only one local process can concurrently
379
+ # download model & vocab.
380
+ config = AutoConfig.from_pretrained(
381
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
382
+ cache_dir=model_args.cache_dir,
383
+ revision=model_args.model_revision,
384
+ token=model_args.token,
385
+ trust_remote_code=model_args.trust_remote_code,
386
+ )
387
+ tokenizer = AutoTokenizer.from_pretrained(
388
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
389
+ cache_dir=model_args.cache_dir,
390
+ use_fast=model_args.use_fast_tokenizer,
391
+ revision=model_args.model_revision,
392
+ token=model_args.token,
393
+ trust_remote_code=model_args.trust_remote_code,
394
+ )
395
+ model = AutoModelForSeq2SeqLM.from_pretrained(
396
+ model_args.model_name_or_path,
397
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
398
+ config=config,
399
+ cache_dir=model_args.cache_dir,
400
+ revision=model_args.model_revision,
401
+ token=model_args.token,
402
+ trust_remote_code=model_args.trust_remote_code,
403
+ )
404
+
405
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
406
+ # on a small vocab and want a smaller embedding size, remove this test.
407
+ embedding_size = model.get_input_embeddings().weight.shape[0]
408
+ if len(tokenizer) > embedding_size:
409
+ model.resize_token_embeddings(len(tokenizer))
410
+
411
+ # Set decoder_start_token_id
412
+ if model.config.decoder_start_token_id is None and isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)):
413
+ if isinstance(tokenizer, MBartTokenizer):
414
+ model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.target_lang]
415
+ else:
416
+ model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(data_args.target_lang)
417
+
418
+ if model.config.decoder_start_token_id is None:
419
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
420
+
421
+ prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
422
+
423
+ # Preprocessing the datasets.
424
+ # We need to tokenize inputs and targets.
425
+ if training_args.do_train:
426
+ column_names = raw_datasets["train"].column_names
427
+ elif training_args.do_eval:
428
+ column_names = raw_datasets["validation"].column_names
429
+ elif training_args.do_predict:
430
+ column_names = raw_datasets["test"].column_names
431
+ else:
432
+ logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
433
+ return
434
+
435
+ # For translation we set the codes of our source and target languages (only useful for mBART, the others will
436
+ # ignore those attributes).
437
+ if isinstance(tokenizer, tuple(MULTILINGUAL_TOKENIZERS)):
438
+ assert data_args.target_lang is not None and data_args.source_lang is not None, (
439
+ f"{tokenizer.__class__.__name__} is a multilingual tokenizer which requires --source_lang and "
440
+ "--target_lang arguments."
441
+ )
442
+
443
+ tokenizer.src_lang = data_args.source_lang
444
+ tokenizer.tgt_lang = data_args.target_lang
445
+
446
+ # For multilingual translation models like mBART-50 and M2M100 we need to force the target language token
447
+ # as the first generated token. We ask the user to explicitly provide this as --forced_bos_token argument.
448
+ forced_bos_token_id = (
449
+ tokenizer.lang_code_to_id[data_args.forced_bos_token] if data_args.forced_bos_token is not None else None
450
+ )
451
+ model.config.forced_bos_token_id = forced_bos_token_id
452
+
453
+ # Get the language codes for input/target.
454
+ source_lang = data_args.source_lang.split("_")[0]
455
+ target_lang = data_args.target_lang.split("_")[0]
456
+
457
+ # Check the whether the source target length fits in the model, if it has absolute positional embeddings
458
+ if (
459
+ hasattr(model.config, "max_position_embeddings")
460
+ and not hasattr(model.config, "relative_attention_max_distance")
461
+ and model.config.max_position_embeddings < data_args.max_source_length
462
+ ):
463
+ raise ValueError(
464
+ f"`--max_source_length` is set to {data_args.max_source_length}, but the model only has"
465
+ f" {model.config.max_position_embeddings} position encodings. Consider either reducing"
466
+ f" `--max_source_length` to {model.config.max_position_embeddings} or using a model with larger position "
467
+ "embeddings"
468
+ )
469
+
470
+ # Temporarily set max_target_length for training.
471
+ max_target_length = data_args.max_target_length
472
+ padding = "max_length" if data_args.pad_to_max_length else False
473
+
474
+ if training_args.label_smoothing_factor > 0 and not hasattr(model, "prepare_decoder_input_ids_from_labels"):
475
+ logger.warning(
476
+ "label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for "
477
+ f"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory"
478
+ )
479
+
480
+ def preprocess_function(examples):
481
+ inputs = [ex[source_lang] for ex in examples["translation"]]
482
+ targets = [ex[target_lang] for ex in examples["translation"]]
483
+ inputs = [prefix + inp for inp in inputs]
484
+ model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True)
485
+
486
+ # Tokenize targets with the `text_target` keyword argument
487
+ labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True)
488
+
489
+ # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
490
+ # padding in the loss.
491
+ if padding == "max_length" and data_args.ignore_pad_token_for_loss:
492
+ labels["input_ids"] = [
493
+ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
494
+ ]
495
+
496
+ model_inputs["labels"] = labels["input_ids"]
497
+ return model_inputs
498
+
499
+ if training_args.do_train:
500
+ if "train" not in raw_datasets:
501
+ raise ValueError("--do_train requires a train dataset")
502
+ train_dataset = raw_datasets["train"]
503
+ if data_args.max_train_samples is not None:
504
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
505
+ train_dataset = train_dataset.select(range(max_train_samples))
506
+ with training_args.main_process_first(desc="train dataset map pre-processing"):
507
+ train_dataset = train_dataset.map(
508
+ preprocess_function,
509
+ batched=True,
510
+ num_proc=data_args.preprocessing_num_workers,
511
+ remove_columns=column_names,
512
+ load_from_cache_file=not data_args.overwrite_cache,
513
+ desc="Running tokenizer on train dataset",
514
+ )
515
+
516
+ if training_args.do_eval:
517
+ max_target_length = data_args.val_max_target_length
518
+ if "validation" not in raw_datasets:
519
+ raise ValueError("--do_eval requires a validation dataset")
520
+ eval_dataset = raw_datasets["validation"]
521
+ if data_args.max_eval_samples is not None:
522
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
523
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
524
+ with training_args.main_process_first(desc="validation dataset map pre-processing"):
525
+ eval_dataset = eval_dataset.map(
526
+ preprocess_function,
527
+ batched=True,
528
+ num_proc=data_args.preprocessing_num_workers,
529
+ remove_columns=column_names,
530
+ load_from_cache_file=not data_args.overwrite_cache,
531
+ desc="Running tokenizer on validation dataset",
532
+ )
533
+
534
+ if training_args.do_predict:
535
+ max_target_length = data_args.val_max_target_length
536
+ if "test" not in raw_datasets:
537
+ raise ValueError("--do_predict requires a test dataset")
538
+ predict_dataset = raw_datasets["test"]
539
+ if data_args.max_predict_samples is not None:
540
+ max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
541
+ predict_dataset = predict_dataset.select(range(max_predict_samples))
542
+ with training_args.main_process_first(desc="prediction dataset map pre-processing"):
543
+ predict_dataset = predict_dataset.map(
544
+ preprocess_function,
545
+ batched=True,
546
+ num_proc=data_args.preprocessing_num_workers,
547
+ remove_columns=column_names,
548
+ load_from_cache_file=not data_args.overwrite_cache,
549
+ desc="Running tokenizer on prediction dataset",
550
+ )
551
+
552
+ # Data collator
553
+ label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id
554
+ if data_args.pad_to_max_length:
555
+ data_collator = default_data_collator
556
+ else:
557
+ data_collator = DataCollatorForSeq2Seq(
558
+ tokenizer,
559
+ model=model,
560
+ label_pad_token_id=label_pad_token_id,
561
+ pad_to_multiple_of=8 if training_args.fp16 else None,
562
+ )
563
+
564
+ # Metric
565
+ metric = evaluate.load("sacrebleu", cache_dir=model_args.cache_dir)
566
+
567
+ def postprocess_text(preds, labels):
568
+ preds = [pred.strip() for pred in preds]
569
+ labels = [[label.strip()] for label in labels]
570
+
571
+ return preds, labels
572
+
573
+ def compute_metrics(eval_preds):
574
+ preds, labels = eval_preds
575
+ if isinstance(preds, tuple):
576
+ preds = preds[0]
577
+ # Replace -100s used for padding as we can't decode them
578
+ preds = np.where(preds != -100, preds, tokenizer.pad_token_id)
579
+ decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
580
+ labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
581
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
582
+
583
+ # Some simple post-processing
584
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
585
+
586
+ result = metric.compute(predictions=decoded_preds, references=decoded_labels)
587
+ result = {"bleu": result["score"]}
588
+
589
+ prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
590
+ result["gen_len"] = np.mean(prediction_lens)
591
+ result = {k: round(v, 4) for k, v in result.items()}
592
+ return result
593
+
594
+ # Initialize our Trainer
595
+ trainer = Seq2SeqTrainer(
596
+ model=model,
597
+ args=training_args,
598
+ train_dataset=train_dataset if training_args.do_train else None,
599
+ eval_dataset=eval_dataset if training_args.do_eval else None,
600
+ processing_class=tokenizer,
601
+ data_collator=data_collator,
602
+ compute_metrics=compute_metrics if training_args.predict_with_generate else None,
603
+ )
604
+
605
+ # Training
606
+ if training_args.do_train:
607
+ checkpoint = None
608
+ if training_args.resume_from_checkpoint is not None:
609
+ checkpoint = training_args.resume_from_checkpoint
610
+ elif last_checkpoint is not None:
611
+ checkpoint = last_checkpoint
612
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
613
+ trainer.save_model() # Saves the tokenizer too for easy upload
614
+
615
+ metrics = train_result.metrics
616
+ max_train_samples = (
617
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
618
+ )
619
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
620
+
621
+ trainer.log_metrics("train", metrics)
622
+ trainer.save_metrics("train", metrics)
623
+ trainer.save_state()
624
+
625
+ # Evaluation
626
+ results = {}
627
+ max_length = (
628
+ training_args.generation_max_length
629
+ if training_args.generation_max_length is not None
630
+ else data_args.val_max_target_length
631
+ )
632
+ num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams
633
+ if training_args.do_eval:
634
+ logger.info("*** Evaluate ***")
635
+
636
+ metrics = trainer.evaluate(max_length=max_length, num_beams=num_beams, metric_key_prefix="eval")
637
+ max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
638
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
639
+
640
+ trainer.log_metrics("eval", metrics)
641
+ trainer.save_metrics("eval", metrics)
642
+
643
+ if training_args.do_predict:
644
+ logger.info("*** Predict ***")
645
+
646
+ predict_results = trainer.predict(
647
+ predict_dataset, metric_key_prefix="predict", max_length=max_length, num_beams=num_beams
648
+ )
649
+ metrics = predict_results.metrics
650
+ max_predict_samples = (
651
+ data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset)
652
+ )
653
+ metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset))
654
+
655
+ trainer.log_metrics("predict", metrics)
656
+ trainer.save_metrics("predict", metrics)
657
+
658
+ if trainer.is_world_process_zero():
659
+ if training_args.predict_with_generate:
660
+ predictions = predict_results.predictions
661
+ predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id)
662
+ predictions = tokenizer.batch_decode(
663
+ predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True
664
+ )
665
+ predictions = [pred.strip() for pred in predictions]
666
+ output_prediction_file = os.path.join(training_args.output_dir, "generated_predictions.txt")
667
+ with open(output_prediction_file, "w", encoding="utf-8") as writer:
668
+ writer.write("\n".join(predictions))
669
+
670
+ kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "translation"}
671
+ if data_args.dataset_name is not None:
672
+ kwargs["dataset_tags"] = data_args.dataset_name
673
+ if data_args.dataset_config_name is not None:
674
+ kwargs["dataset_args"] = data_args.dataset_config_name
675
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
676
+ else:
677
+ kwargs["dataset"] = data_args.dataset_name
678
+
679
+ languages = [l for l in [data_args.source_lang, data_args.target_lang] if l is not None]
680
+ if len(languages) > 0:
681
+ kwargs["language"] = languages
682
+
683
+ if training_args.push_to_hub:
684
+ trainer.push_to_hub(**kwargs)
685
+ else:
686
+ trainer.create_model_card(**kwargs)
687
+
688
+ return results
689
+
690
+
691
+ def _mp_fn(index):
692
+ # For xla_spawn (TPUs)
693
+ main()
694
+
695
+
696
+ if __name__ == "__main__":
697
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/translation/run_translation_no_trainer.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright The HuggingFace Team and The HuggingFace Inc. 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 a 🤗 Transformers model on text translation.
18
+ """
19
+ # You can also adapt this script on your own text translation task. Pointers for this are left as comments.
20
+
21
+ import argparse
22
+ import json
23
+ import logging
24
+ import math
25
+ import os
26
+ import random
27
+ from pathlib import Path
28
+
29
+ import datasets
30
+ import evaluate
31
+ import numpy as np
32
+ import torch
33
+ from accelerate import Accelerator
34
+ from accelerate.logging import get_logger
35
+ from accelerate.utils import set_seed
36
+ from datasets import load_dataset
37
+ from huggingface_hub import HfApi
38
+ from torch.utils.data import DataLoader
39
+ from tqdm.auto import tqdm
40
+
41
+ import transformers
42
+ from transformers import (
43
+ CONFIG_MAPPING,
44
+ MODEL_MAPPING,
45
+ AutoConfig,
46
+ AutoModelForSeq2SeqLM,
47
+ AutoTokenizer,
48
+ DataCollatorForSeq2Seq,
49
+ MBartTokenizer,
50
+ MBartTokenizerFast,
51
+ SchedulerType,
52
+ default_data_collator,
53
+ get_scheduler,
54
+ )
55
+ from transformers.utils import check_min_version, send_example_telemetry
56
+ from transformers.utils.versions import require_version
57
+
58
+
59
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
60
+ check_min_version("4.50.0.dev0")
61
+
62
+ logger = get_logger(__name__)
63
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/translation/requirements.txt")
64
+
65
+ # You should update this to your particular problem to have better documentation of `model_type`
66
+ MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
67
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
68
+
69
+
70
+ # Parsing input arguments
71
+ def parse_args():
72
+ parser = argparse.ArgumentParser(description="Finetune a transformers model on a text classification task")
73
+ parser.add_argument(
74
+ "--dataset_name",
75
+ type=str,
76
+ default=None,
77
+ help="The name of the dataset to use (via the datasets library).",
78
+ )
79
+ parser.add_argument(
80
+ "--predict_with_generate",
81
+ type=bool,
82
+ default=True,
83
+ help="",
84
+ )
85
+ parser.add_argument(
86
+ "--dataset_config_name",
87
+ type=str,
88
+ default=None,
89
+ help="The configuration name of the dataset to use (via the datasets library).",
90
+ )
91
+ parser.add_argument(
92
+ "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
93
+ )
94
+
95
+ parser.add_argument(
96
+ "--num_beams",
97
+ type=int,
98
+ default=None,
99
+ help=(
100
+ "Number of beams to use for evaluation. This argument will be "
101
+ "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``."
102
+ ),
103
+ )
104
+
105
+ parser.add_argument(
106
+ "--max_source_length",
107
+ type=int,
108
+ default=1024,
109
+ help=(
110
+ "The maximum total input sequence length after "
111
+ "tokenization.Sequences longer than this will be truncated, sequences shorter will be padded."
112
+ ),
113
+ )
114
+ parser.add_argument(
115
+ "--max_target_length",
116
+ type=int,
117
+ default=128,
118
+ help=(
119
+ "The maximum total sequence length for target text after "
120
+ "tokenization. Sequences longer than this will be truncated, sequences shorter will be padded "
121
+ "during ``evaluate`` and ``predict``."
122
+ ),
123
+ )
124
+ parser.add_argument(
125
+ "--val_max_target_length",
126
+ type=int,
127
+ default=None,
128
+ help=(
129
+ "The maximum total sequence length for validation "
130
+ "target text after tokenization.Sequences longer than this will be truncated, sequences shorter will be "
131
+ "padded. Will default to `max_target_length`.This argument is also used to override the ``max_length`` "
132
+ "param of ``model.generate``, which is used during ``evaluate`` and ``predict``."
133
+ ),
134
+ )
135
+ parser.add_argument(
136
+ "--pad_to_max_length",
137
+ type=bool,
138
+ default=False,
139
+ help=(
140
+ "Whether to pad all samples to model maximum sentence "
141
+ "length. If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
142
+ "efficient on GPU but very bad for TPU."
143
+ ),
144
+ )
145
+ parser.add_argument(
146
+ "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
147
+ )
148
+ parser.add_argument(
149
+ "--ignore_pad_token_for_loss",
150
+ type=bool,
151
+ default=True,
152
+ help="Whether to ignore the tokens corresponding to padded labels in the loss computation or not.",
153
+ )
154
+ parser.add_argument("--source_lang", type=str, default=None, help="Source language id for translation.")
155
+ parser.add_argument("--target_lang", type=str, default=None, help="Target language id for translation.")
156
+ parser.add_argument(
157
+ "--source_prefix",
158
+ type=str,
159
+ default=None,
160
+ help="A prefix to add before every source text (useful for T5 models).",
161
+ )
162
+ parser.add_argument(
163
+ "--preprocessing_num_workers",
164
+ type=int,
165
+ default=None,
166
+ help="The number of processes to use for the preprocessing.",
167
+ )
168
+ parser.add_argument(
169
+ "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
170
+ )
171
+ parser.add_argument(
172
+ "--max_length",
173
+ type=int,
174
+ default=128,
175
+ help=(
176
+ "The maximum total input sequence length after tokenization. Sequences longer than this will be truncated,"
177
+ " sequences shorter will be padded if `--pad_to_max_length` is passed."
178
+ ),
179
+ )
180
+ parser.add_argument(
181
+ "--model_name_or_path",
182
+ type=str,
183
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
184
+ required=False,
185
+ )
186
+ parser.add_argument(
187
+ "--config_name",
188
+ type=str,
189
+ default=None,
190
+ help="Pretrained config name or path if not the same as model_name",
191
+ )
192
+ parser.add_argument(
193
+ "--tokenizer_name",
194
+ type=str,
195
+ default=None,
196
+ help="Pretrained tokenizer name or path if not the same as model_name",
197
+ )
198
+ parser.add_argument(
199
+ "--use_slow_tokenizer",
200
+ action="store_true",
201
+ help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
202
+ )
203
+ parser.add_argument(
204
+ "--per_device_train_batch_size",
205
+ type=int,
206
+ default=8,
207
+ help="Batch size (per device) for the training dataloader.",
208
+ )
209
+ parser.add_argument(
210
+ "--per_device_eval_batch_size",
211
+ type=int,
212
+ default=8,
213
+ help="Batch size (per device) for the evaluation dataloader.",
214
+ )
215
+ parser.add_argument(
216
+ "--learning_rate",
217
+ type=float,
218
+ default=5e-5,
219
+ help="Initial learning rate (after the potential warmup period) to use.",
220
+ )
221
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
222
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
223
+ parser.add_argument(
224
+ "--max_train_steps",
225
+ type=int,
226
+ default=None,
227
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
228
+ )
229
+ parser.add_argument(
230
+ "--gradient_accumulation_steps",
231
+ type=int,
232
+ default=1,
233
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
234
+ )
235
+ parser.add_argument(
236
+ "--lr_scheduler_type",
237
+ type=SchedulerType,
238
+ default="linear",
239
+ help="The scheduler type to use.",
240
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
241
+ )
242
+ parser.add_argument(
243
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
244
+ )
245
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
246
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
247
+ parser.add_argument(
248
+ "--model_type",
249
+ type=str,
250
+ default=None,
251
+ help="Model type to use if training from scratch.",
252
+ choices=MODEL_TYPES,
253
+ )
254
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
255
+ parser.add_argument(
256
+ "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
257
+ )
258
+ parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
259
+ parser.add_argument(
260
+ "--trust_remote_code",
261
+ action="store_true",
262
+ help=(
263
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
264
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
265
+ " code, as it will execute code present on the Hub on your local machine."
266
+ ),
267
+ )
268
+ parser.add_argument(
269
+ "--checkpointing_steps",
270
+ type=str,
271
+ default=None,
272
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
273
+ )
274
+ parser.add_argument(
275
+ "--resume_from_checkpoint",
276
+ type=str,
277
+ default=None,
278
+ help="If the training should continue from a checkpoint folder.",
279
+ )
280
+ parser.add_argument(
281
+ "--with_tracking",
282
+ action="store_true",
283
+ help="Whether to enable experiment trackers for logging.",
284
+ )
285
+ parser.add_argument(
286
+ "--report_to",
287
+ type=str,
288
+ default="all",
289
+ help=(
290
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
291
+ ' `"wandb"`, `"comet_ml"` and `"clearml"`. Use `"all"` (default) to report to all integrations. '
292
+ "Only applicable when `--with_tracking` is passed."
293
+ ),
294
+ )
295
+ args = parser.parse_args()
296
+
297
+ # Sanity checks
298
+
299
+ if args.dataset_name is None and args.train_file is None and args.validation_file is None:
300
+ raise ValueError("Need either a task name or a training/validation file.")
301
+
302
+ if args.train_file is not None:
303
+ extension = args.train_file.split(".")[-1]
304
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
305
+ if args.validation_file is not None:
306
+ extension = args.validation_file.split(".")[-1]
307
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
308
+
309
+ if args.push_to_hub:
310
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
311
+
312
+ return args
313
+
314
+
315
+ def main():
316
+ # Parse the arguments
317
+ args = parse_args()
318
+
319
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
320
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
321
+ send_example_telemetry("run_translation_no_trainer", args)
322
+
323
+ # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
324
+ # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
325
+ # in the environment
326
+ accelerator = (
327
+ Accelerator(log_with=args.report_to, project_dir=args.output_dir) if args.with_tracking else Accelerator()
328
+ )
329
+
330
+ # Make one log on every process with the configuration for debugging.
331
+ logging.basicConfig(
332
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
333
+ datefmt="%m/%d/%Y %H:%M:%S",
334
+ level=logging.INFO,
335
+ )
336
+ logger.info(accelerator.state, main_process_only=False)
337
+ if accelerator.is_local_main_process:
338
+ datasets.utils.logging.set_verbosity_warning()
339
+ transformers.utils.logging.set_verbosity_info()
340
+ else:
341
+ datasets.utils.logging.set_verbosity_error()
342
+ transformers.utils.logging.set_verbosity_error()
343
+
344
+ # If passed along, set the training seed now.
345
+ if args.seed is not None:
346
+ set_seed(args.seed)
347
+
348
+ # Handle the repository creation
349
+ if accelerator.is_main_process:
350
+ if args.push_to_hub:
351
+ # Retrieve of infer repo_name
352
+ repo_name = args.hub_model_id
353
+ if repo_name is None:
354
+ repo_name = Path(args.output_dir).absolute().name
355
+ # Create repo and retrieve repo_id
356
+ api = HfApi()
357
+ repo_id = api.create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
358
+
359
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
360
+ if "step_*" not in gitignore:
361
+ gitignore.write("step_*\n")
362
+ if "epoch_*" not in gitignore:
363
+ gitignore.write("epoch_*\n")
364
+ elif args.output_dir is not None:
365
+ os.makedirs(args.output_dir, exist_ok=True)
366
+ accelerator.wait_for_everyone()
367
+
368
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
369
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
370
+ # (the dataset will be downloaded automatically from the datasets Hub).
371
+ #
372
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
373
+ # 'text' is found. You can easily tweak this behavior (see below).
374
+ #
375
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
376
+ # download the dataset.
377
+ if args.dataset_name is not None:
378
+ # Downloading and loading a dataset from the hub.
379
+ raw_datasets = load_dataset(
380
+ args.dataset_name, args.dataset_config_name, trust_remote_code=args.trust_remote_code
381
+ )
382
+ else:
383
+ data_files = {}
384
+ if args.train_file is not None:
385
+ data_files["train"] = args.train_file
386
+ extension = args.train_file.split(".")[-1]
387
+ if args.validation_file is not None:
388
+ data_files["validation"] = args.validation_file
389
+ extension = args.validation_file.split(".")[-1]
390
+ raw_datasets = load_dataset(extension, data_files=data_files)
391
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
392
+ # https://huggingface.co/docs/datasets/loading_datasets.
393
+
394
+ # Load pretrained model and tokenizer
395
+ #
396
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
397
+ # download model & vocab.
398
+ if args.config_name:
399
+ config = AutoConfig.from_pretrained(args.config_name, trust_remote_code=args.trust_remote_code)
400
+ elif args.model_name_or_path:
401
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
402
+ else:
403
+ config = CONFIG_MAPPING[args.model_type]()
404
+ logger.warning("You are instantiating a new config instance from scratch.")
405
+
406
+ if args.tokenizer_name:
407
+ tokenizer = AutoTokenizer.from_pretrained(
408
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
409
+ )
410
+ elif args.model_name_or_path:
411
+ tokenizer = AutoTokenizer.from_pretrained(
412
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
413
+ )
414
+ else:
415
+ raise ValueError(
416
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
417
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
418
+ )
419
+
420
+ if args.model_name_or_path:
421
+ model = AutoModelForSeq2SeqLM.from_pretrained(
422
+ args.model_name_or_path,
423
+ from_tf=bool(".ckpt" in args.model_name_or_path),
424
+ config=config,
425
+ trust_remote_code=args.trust_remote_code,
426
+ )
427
+ else:
428
+ logger.info("Training new model from scratch")
429
+ model = AutoModelForSeq2SeqLM.from_config(config, trust_remote_code=args.trust_remote_code)
430
+
431
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
432
+ # on a small vocab and want a smaller embedding size, remove this test.
433
+ embedding_size = model.get_input_embeddings().weight.shape[0]
434
+ if len(tokenizer) > embedding_size:
435
+ model.resize_token_embeddings(len(tokenizer))
436
+
437
+ # Set decoder_start_token_id
438
+ if model.config.decoder_start_token_id is None and isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)):
439
+ assert (
440
+ args.target_lang is not None and args.source_lang is not None
441
+ ), "mBart requires --target_lang and --source_lang"
442
+ if isinstance(tokenizer, MBartTokenizer):
443
+ model.config.decoder_start_token_id = tokenizer.lang_code_to_id[args.target_lang]
444
+ else:
445
+ model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(args.target_lang)
446
+
447
+ if model.config.decoder_start_token_id is None:
448
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
449
+
450
+ prefix = args.source_prefix if args.source_prefix is not None else ""
451
+
452
+ # Preprocessing the datasets.
453
+ # First we tokenize all the texts.
454
+ column_names = raw_datasets["train"].column_names
455
+
456
+ # For translation we set the codes of our source and target languages (only useful for mBART, the others will
457
+ # ignore those attributes).
458
+ if isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)):
459
+ if args.source_lang is not None:
460
+ tokenizer.src_lang = args.source_lang
461
+ if args.target_lang is not None:
462
+ tokenizer.tgt_lang = args.target_lang
463
+
464
+ # Get the language codes for input/target.
465
+ source_lang = args.source_lang.split("_")[0]
466
+ target_lang = args.target_lang.split("_")[0]
467
+
468
+ padding = "max_length" if args.pad_to_max_length else False
469
+
470
+ # Temporarily set max_target_length for training.
471
+ max_target_length = args.max_target_length
472
+ padding = "max_length" if args.pad_to_max_length else False
473
+
474
+ def preprocess_function(examples):
475
+ inputs = [ex[source_lang] for ex in examples["translation"]]
476
+ targets = [ex[target_lang] for ex in examples["translation"]]
477
+ inputs = [prefix + inp for inp in inputs]
478
+ model_inputs = tokenizer(inputs, max_length=args.max_source_length, padding=padding, truncation=True)
479
+
480
+ # Tokenize targets with the `text_target` keyword argument
481
+ labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True)
482
+
483
+ # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
484
+ # padding in the loss.
485
+ if padding == "max_length" and args.ignore_pad_token_for_loss:
486
+ labels["input_ids"] = [
487
+ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
488
+ ]
489
+
490
+ model_inputs["labels"] = labels["input_ids"]
491
+ return model_inputs
492
+
493
+ with accelerator.main_process_first():
494
+ processed_datasets = raw_datasets.map(
495
+ preprocess_function,
496
+ batched=True,
497
+ num_proc=args.preprocessing_num_workers,
498
+ remove_columns=column_names,
499
+ load_from_cache_file=not args.overwrite_cache,
500
+ desc="Running tokenizer on dataset",
501
+ )
502
+
503
+ train_dataset = processed_datasets["train"]
504
+ eval_dataset = processed_datasets["validation"]
505
+
506
+ # Log a few random samples from the training set:
507
+ for index in random.sample(range(len(train_dataset)), 3):
508
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
509
+
510
+ # DataLoaders creation:
511
+ label_pad_token_id = -100 if args.ignore_pad_token_for_loss else tokenizer.pad_token_id
512
+ if args.pad_to_max_length:
513
+ # If padding was already done ot max length, we use the default data collator that will just convert everything
514
+ # to tensors.
515
+ data_collator = default_data_collator
516
+ else:
517
+ # Otherwise, `DataCollatorWithPadding` will apply dynamic padding for us (by padding to the maximum length of
518
+ # the samples passed). When using mixed precision, we add `pad_to_multiple_of=8` to pad all tensors to multiple
519
+ # of 8s, which will enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).
520
+ # For fp8, we pad to multiple of 16.
521
+ if accelerator.mixed_precision == "fp8":
522
+ pad_to_multiple_of = 16
523
+ elif accelerator.mixed_precision != "no":
524
+ pad_to_multiple_of = 8
525
+ else:
526
+ pad_to_multiple_of = None
527
+ data_collator = DataCollatorForSeq2Seq(
528
+ tokenizer,
529
+ model=model,
530
+ label_pad_token_id=label_pad_token_id,
531
+ pad_to_multiple_of=pad_to_multiple_of,
532
+ )
533
+
534
+ train_dataloader = DataLoader(
535
+ train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size
536
+ )
537
+ eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size)
538
+
539
+ # Optimizer
540
+ # Split weights in two groups, one with weight decay and the other not.
541
+ no_decay = ["bias", "LayerNorm.weight", "layer_norm.weight"]
542
+ optimizer_grouped_parameters = [
543
+ {
544
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
545
+ "weight_decay": args.weight_decay,
546
+ },
547
+ {
548
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
549
+ "weight_decay": 0.0,
550
+ },
551
+ ]
552
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
553
+
554
+ # Scheduler and math around the number of training steps.
555
+ overrode_max_train_steps = False
556
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
557
+ if args.max_train_steps is None:
558
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
559
+ overrode_max_train_steps = True
560
+
561
+ lr_scheduler = get_scheduler(
562
+ name=args.lr_scheduler_type,
563
+ optimizer=optimizer,
564
+ num_warmup_steps=args.num_warmup_steps,
565
+ num_training_steps=args.max_train_steps,
566
+ )
567
+
568
+ # Prepare everything with our `accelerator`.
569
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
570
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
571
+ )
572
+
573
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
574
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
575
+ if overrode_max_train_steps:
576
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
577
+ # Afterwards we recalculate our number of training epochs
578
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
579
+ # Figure out how many steps we should save the Accelerator states
580
+ checkpointing_steps = args.checkpointing_steps
581
+ if checkpointing_steps is not None and checkpointing_steps.isdigit():
582
+ checkpointing_steps = int(checkpointing_steps)
583
+
584
+ # We need to initialize the trackers we use, and also store our configuration.
585
+ # We initialize the trackers only on main process because `accelerator.log`
586
+ # only logs on main process and we don't want empty logs/runs on other processes.
587
+ if args.with_tracking:
588
+ if accelerator.is_main_process:
589
+ experiment_config = vars(args)
590
+ # TensorBoard cannot log Enums, need the raw value
591
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
592
+ accelerator.init_trackers("translation_no_trainer", experiment_config)
593
+
594
+ metric = evaluate.load("sacrebleu")
595
+
596
+ def postprocess_text(preds, labels):
597
+ preds = [pred.strip() for pred in preds]
598
+ labels = [[label.strip()] for label in labels]
599
+
600
+ return preds, labels
601
+
602
+ # Train!
603
+ total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
604
+
605
+ logger.info("***** Running training *****")
606
+ logger.info(f" Num examples = {len(train_dataset)}")
607
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
608
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
609
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
610
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
611
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
612
+ # Only show the progress bar once on each machine.
613
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
614
+ completed_steps = 0
615
+ starting_epoch = 0
616
+
617
+ # Potentially load in the weights and states from a previous save
618
+ if args.resume_from_checkpoint:
619
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
620
+ checkpoint_path = args.resume_from_checkpoint
621
+ path = os.path.basename(args.resume_from_checkpoint)
622
+ else:
623
+ # Get the most recent checkpoint
624
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
625
+ dirs.sort(key=os.path.getctime)
626
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
627
+ checkpoint_path = path
628
+ path = os.path.basename(checkpoint_path)
629
+
630
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
631
+ accelerator.load_state(checkpoint_path)
632
+ # Extract `epoch_{i}` or `step_{i}`
633
+ training_difference = os.path.splitext(path)[0]
634
+
635
+ if "epoch" in training_difference:
636
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
637
+ resume_step = None
638
+ completed_steps = starting_epoch * num_update_steps_per_epoch
639
+ else:
640
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
641
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
642
+ starting_epoch = resume_step // len(train_dataloader)
643
+ completed_steps = resume_step // args.gradient_accumulation_steps
644
+ resume_step -= starting_epoch * len(train_dataloader)
645
+
646
+ # update the progress_bar if load from checkpoint
647
+ progress_bar.update(completed_steps)
648
+
649
+ for epoch in range(starting_epoch, args.num_train_epochs):
650
+ model.train()
651
+ if args.with_tracking:
652
+ total_loss = 0
653
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
654
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
655
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
656
+ else:
657
+ active_dataloader = train_dataloader
658
+ for step, batch in enumerate(active_dataloader):
659
+ outputs = model(**batch)
660
+ loss = outputs.loss
661
+ # We keep track of the loss at each epoch
662
+ if args.with_tracking:
663
+ total_loss += loss.detach().float()
664
+ loss = loss / args.gradient_accumulation_steps
665
+ accelerator.backward(loss)
666
+ if step % args.gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
667
+ optimizer.step()
668
+ lr_scheduler.step()
669
+ optimizer.zero_grad()
670
+ progress_bar.update(1)
671
+ completed_steps += 1
672
+
673
+ if isinstance(checkpointing_steps, int):
674
+ if completed_steps % checkpointing_steps == 0 and accelerator.sync_gradients:
675
+ output_dir = f"step_{completed_steps}"
676
+ if args.output_dir is not None:
677
+ output_dir = os.path.join(args.output_dir, output_dir)
678
+ accelerator.save_state(output_dir)
679
+
680
+ if completed_steps >= args.max_train_steps:
681
+ break
682
+
683
+ model.eval()
684
+
685
+ if args.val_max_target_length is None:
686
+ args.val_max_target_length = args.max_target_length
687
+
688
+ gen_kwargs = {
689
+ "max_length": args.val_max_target_length if args is not None else config.max_length,
690
+ "num_beams": args.num_beams,
691
+ }
692
+ samples_seen = 0
693
+ for step, batch in enumerate(eval_dataloader):
694
+ with torch.no_grad():
695
+ generated_tokens = accelerator.unwrap_model(model).generate(
696
+ batch["input_ids"],
697
+ attention_mask=batch["attention_mask"],
698
+ **gen_kwargs,
699
+ )
700
+
701
+ generated_tokens = accelerator.pad_across_processes(
702
+ generated_tokens, dim=1, pad_index=tokenizer.pad_token_id
703
+ )
704
+ labels = batch["labels"]
705
+ if not args.pad_to_max_length:
706
+ # If we did not pad to max length, we need to pad the labels too
707
+ labels = accelerator.pad_across_processes(batch["labels"], dim=1, pad_index=tokenizer.pad_token_id)
708
+
709
+ generated_tokens = accelerator.gather(generated_tokens).cpu().numpy()
710
+ labels = accelerator.gather(labels).cpu().numpy()
711
+
712
+ if args.ignore_pad_token_for_loss:
713
+ # Replace -100 in the labels as we can't decode them.
714
+ labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
715
+
716
+ decoded_preds = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
717
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
718
+
719
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
720
+
721
+ # If we are in a multiprocess environment, the last batch has duplicates
722
+ if accelerator.num_processes > 1:
723
+ if step == len(eval_dataloader) - 1:
724
+ decoded_preds = decoded_preds[: len(eval_dataloader.dataset) - samples_seen]
725
+ decoded_labels = decoded_labels[: len(eval_dataloader.dataset) - samples_seen]
726
+ else:
727
+ samples_seen += len(decoded_labels)
728
+
729
+ metric.add_batch(predictions=decoded_preds, references=decoded_labels)
730
+ eval_metric = metric.compute()
731
+ logger.info({"bleu": eval_metric["score"]})
732
+
733
+ if args.with_tracking:
734
+ accelerator.log(
735
+ {
736
+ "bleu": eval_metric["score"],
737
+ "train_loss": total_loss.item() / len(train_dataloader),
738
+ "epoch": epoch,
739
+ "step": completed_steps,
740
+ },
741
+ step=completed_steps,
742
+ )
743
+
744
+ if args.push_to_hub and epoch < args.num_train_epochs - 1:
745
+ accelerator.wait_for_everyone()
746
+ unwrapped_model = accelerator.unwrap_model(model)
747
+ unwrapped_model.save_pretrained(
748
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
749
+ )
750
+ if accelerator.is_main_process:
751
+ tokenizer.save_pretrained(args.output_dir)
752
+ api.upload_folder(
753
+ commit_message=f"Training in progress epoch {epoch}",
754
+ folder_path=args.output_dir,
755
+ repo_id=repo_id,
756
+ repo_type="model",
757
+ token=args.hub_token,
758
+ )
759
+
760
+ if args.checkpointing_steps == "epoch":
761
+ output_dir = f"epoch_{epoch}"
762
+ if args.output_dir is not None:
763
+ output_dir = os.path.join(args.output_dir, output_dir)
764
+ accelerator.save_state(output_dir)
765
+
766
+ if args.with_tracking:
767
+ accelerator.end_training()
768
+
769
+ if args.output_dir is not None:
770
+ accelerator.wait_for_everyone()
771
+ unwrapped_model = accelerator.unwrap_model(model)
772
+ unwrapped_model.save_pretrained(
773
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
774
+ )
775
+ if accelerator.is_main_process:
776
+ tokenizer.save_pretrained(args.output_dir)
777
+ if args.push_to_hub:
778
+ api.upload_folder(
779
+ commit_message="End of training",
780
+ folder_path=args.output_dir,
781
+ repo_id=repo_id,
782
+ repo_type="model",
783
+ token=args.hub_token,
784
+ )
785
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
786
+ json.dump({"eval_bleu": eval_metric["score"]}, f)
787
+
788
+
789
+ if __name__ == "__main__":
790
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/pytorch/xla_spawn.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ A simple launcher script for TPU training
16
+
17
+ Inspired by https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py
18
+
19
+ ::
20
+ >>> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE
21
+ YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
22
+ arguments of your training script)
23
+
24
+ """
25
+
26
+ import importlib
27
+ import sys
28
+ from argparse import REMAINDER, ArgumentParser
29
+ from pathlib import Path
30
+
31
+ import torch_xla.distributed.xla_multiprocessing as xmp
32
+
33
+
34
+ def parse_args():
35
+ """
36
+ Helper function parsing the command line options
37
+ @retval ArgumentParser
38
+ """
39
+ parser = ArgumentParser(
40
+ description=(
41
+ "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
42
+ )
43
+ )
44
+
45
+ # Optional arguments for the launch helper
46
+ parser.add_argument("--num_cores", type=int, default=1, help="Number of TPU cores to use (1 or 8).")
47
+
48
+ # positional
49
+ parser.add_argument(
50
+ "training_script",
51
+ type=str,
52
+ help=(
53
+ "The full path to the single TPU training "
54
+ "program/script to be launched in parallel, "
55
+ "followed by all the arguments for the "
56
+ "training script"
57
+ ),
58
+ )
59
+
60
+ # rest from the training program
61
+ parser.add_argument("training_script_args", nargs=REMAINDER)
62
+
63
+ return parser.parse_args()
64
+
65
+
66
+ def main():
67
+ args = parse_args()
68
+
69
+ # Import training_script as a module.
70
+ script_fpath = Path(args.training_script)
71
+ sys.path.append(str(script_fpath.parent.resolve()))
72
+ mod_name = script_fpath.stem
73
+ mod = importlib.import_module(mod_name)
74
+
75
+ # Patch sys.argv
76
+ sys.argv = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores)]
77
+
78
+ xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores)
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/quantization/custom_quantization.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Any, Dict
3
+
4
+ import torch
5
+
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ from transformers.quantizers import HfQuantizer, register_quantization_config, register_quantizer
8
+ from transformers.utils.quantization_config import QuantizationConfigMixin
9
+
10
+
11
+ @register_quantization_config("custom")
12
+ class CustomConfig(QuantizationConfigMixin):
13
+ def __init__(self):
14
+ self.quant_method = "custom"
15
+ self.bits = 8
16
+
17
+ def to_dict(self) -> Dict[str, Any]:
18
+ output = {
19
+ "num_bits": self.bits,
20
+ }
21
+ return output
22
+
23
+ def __repr__(self):
24
+ config_dict = self.to_dict()
25
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
26
+
27
+ def to_diff_dict(self) -> Dict[str, Any]:
28
+ config_dict = self.to_dict()
29
+
30
+ default_config_dict = CustomConfig().to_dict()
31
+
32
+ serializable_config_dict = {}
33
+
34
+ for key, value in config_dict.items():
35
+ if value != default_config_dict[key]:
36
+ serializable_config_dict[key] = value
37
+
38
+ return serializable_config_dict
39
+
40
+
41
+ @register_quantizer("custom")
42
+ class CustomQuantizer(HfQuantizer):
43
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
44
+ super().__init__(quantization_config, **kwargs)
45
+ self.quantization_config = quantization_config
46
+ self.scale_map = {}
47
+ self.device = kwargs.get("device", "cuda" if torch.cuda.is_available() else "cpu")
48
+ self.torch_dtype = kwargs.get("torch_dtype", torch.float32)
49
+
50
+ def _process_model_before_weight_loading(self, model, **kwargs):
51
+ return True
52
+
53
+ def _process_model_after_weight_loading(self, model, **kwargs):
54
+ return True
55
+
56
+ def is_serializable(self) -> bool:
57
+ return True
58
+
59
+ def is_trainable(self) -> bool:
60
+ return False
61
+
62
+
63
+ model_8bit = AutoModelForCausalLM.from_pretrained(
64
+ "facebook/opt-350m", quantization_config=CustomConfig(), torch_dtype="auto"
65
+ )
66
+
67
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
68
+ input_text = "once there is"
69
+ inputs = tokenizer(input_text, return_tensors="pt")
70
+ output = model_8bit.generate(
71
+ **inputs,
72
+ max_length=100,
73
+ num_return_sequences=1,
74
+ no_repeat_ngram_size=2,
75
+ )
76
+ generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
77
+
78
+ print(generated_text)
tasks/tasksmith-441eeab80047/tests/source/examples/quantization/custom_quantization_int8_example.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from accelerate import init_empty_weights
8
+ from huggingface_hub import HfApi
9
+
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer
11
+ from transformers.quantizers import HfQuantizer, get_module_from_name, register_quantization_config, register_quantizer
12
+ from transformers.utils.quantization_config import QuantizationConfigMixin
13
+
14
+
15
+ # Implement INT8 Symmetric Linear layer
16
+ class Int8SymmetricLinear(torch.nn.Module):
17
+ def __init__(self, in_features, out_features, bias, dtype=torch.float32):
18
+ super().__init__()
19
+ self.in_features = in_features
20
+ self.out_features = out_features
21
+
22
+ self.register_buffer("weight", torch.zeros((out_features, in_features), dtype=torch.int8))
23
+ self.register_buffer("weight_scale", torch.zeros((out_features, 1), dtype=dtype))
24
+
25
+ if bias:
26
+ self.register_buffer("bias", torch.zeros((self.out_features), dtype=dtype))
27
+ else:
28
+ self.bias = None
29
+
30
+ def forward(self, x):
31
+ dequant_weight = self.weight * self.weight_scale
32
+ output = F.linear(x, dequant_weight)
33
+ if self.bias is not None:
34
+ output = output + self.bias
35
+ return output
36
+
37
+
38
+ # Function to replace standard linear layers with INT8 symmetric quantized layers
39
+ def _replace_with_int8_symmetric_linear(
40
+ model,
41
+ modules_to_not_convert=None,
42
+ current_key_name=None,
43
+ quantization_config=None,
44
+ has_been_replaced=False,
45
+ pre_quantized=False,
46
+ ):
47
+ """
48
+ Recursively replaces nn.Linear modules with Int8SymmetricLinear modules.
49
+ """
50
+ if current_key_name is None:
51
+ current_key_name = []
52
+
53
+ for name, module in model.named_children():
54
+ current_key_name.append(name)
55
+
56
+ if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
57
+ # Check if the current key is not in the `modules_to_not_convert`
58
+ current_key_name_str = ".".join(current_key_name)
59
+ if not any(
60
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
61
+ ):
62
+ with init_empty_weights(include_buffers=True):
63
+ in_features = module.in_features
64
+ out_features = module.out_features
65
+ model._modules[name] = Int8SymmetricLinear(
66
+ in_features, out_features, module.bias is not None, dtype=module.weight.dtype
67
+ )
68
+ has_been_replaced = True
69
+ model._modules[name].requires_grad_(False)
70
+
71
+ if len(list(module.children())) > 0:
72
+ _, has_been_replaced = _replace_with_int8_symmetric_linear(
73
+ module,
74
+ modules_to_not_convert,
75
+ current_key_name,
76
+ quantization_config,
77
+ has_been_replaced=has_been_replaced,
78
+ pre_quantized=pre_quantized,
79
+ )
80
+ # Remove the last key for recursion
81
+ current_key_name.pop(-1)
82
+ return model, has_been_replaced
83
+
84
+
85
+ def replace_with_int8_symmetric_linear(
86
+ model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False
87
+ ):
88
+ """
89
+ Main function to replace model layers with INT8 symmetric quantized versions.
90
+ """
91
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
92
+
93
+ if quantization_config.modules_to_not_convert is not None:
94
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
95
+ modules_to_not_convert = list(set(modules_to_not_convert))
96
+
97
+ model, has_been_replaced = _replace_with_int8_symmetric_linear(
98
+ model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized
99
+ )
100
+
101
+ if not has_been_replaced:
102
+ raise ValueError(
103
+ "You are loading your model using INT8 symmetric quantization but no linear modules were found in your model."
104
+ )
105
+
106
+ return model
107
+
108
+
109
+ @register_quantization_config("int8_symmetric")
110
+ class Int8SymmetricConfig(QuantizationConfigMixin):
111
+ """
112
+ Configuration for INT8 symmetric quantization.
113
+ """
114
+
115
+ def __init__(self, modules_to_not_convert: Optional[List[str]] = None, **kwargs):
116
+ self.quant_method = "int8_symmetric"
117
+ self.modules_to_not_convert = modules_to_not_convert
118
+
119
+ def __repr__(self):
120
+ config_dict = self.to_dict()
121
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
122
+
123
+ def to_diff_dict(self) -> Dict[str, Any]:
124
+ config_dict = self.to_dict()
125
+ default_config_dict = Int8SymmetricConfig().to_dict()
126
+
127
+ serializable_config_dict = {}
128
+ for key, value in config_dict.items():
129
+ if value != default_config_dict[key]:
130
+ serializable_config_dict[key] = value
131
+
132
+ return serializable_config_dict
133
+
134
+
135
+ @register_quantizer("int8_symmetric")
136
+ class Int8SymmetricQuantizer(HfQuantizer):
137
+ """
138
+ Implementation of INT8 symmetric quantization.
139
+
140
+ """
141
+
142
+ requires_calibration = False
143
+ requires_parameters_quantization = True
144
+
145
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
146
+ super().__init__(quantization_config, **kwargs)
147
+ self.quantization_config = quantization_config
148
+
149
+ def _process_model_before_weight_loading(self, model, **kwargs):
150
+ """
151
+ Replace model's linear layers with quantized versions before loading weights.
152
+ """
153
+ self.modules_to_not_convert = self.quantization_config.modules_to_not_convert
154
+
155
+ model = replace_with_int8_symmetric_linear(
156
+ model,
157
+ modules_to_not_convert=self.modules_to_not_convert,
158
+ quantization_config=self.quantization_config,
159
+ pre_quantized=self.pre_quantized,
160
+ )
161
+
162
+ def check_quantized_param(
163
+ self,
164
+ model,
165
+ param_value: "torch.Tensor",
166
+ param_name: str,
167
+ state_dict: Dict[str, Any],
168
+ **kwargs,
169
+ ):
170
+ module, tensor_name = get_module_from_name(model, param_name)
171
+
172
+ if isinstance(module, Int8SymmetricLinear):
173
+ if self.pre_quantized or tensor_name == "bias":
174
+ if tensor_name == "weight" and param_value.dtype != torch.int8:
175
+ raise ValueError("Expect quantized weights but got an unquantized weight")
176
+ return False
177
+ else:
178
+ if tensor_name == "weight_scale":
179
+ raise ValueError("Expect unquantized weights but got a quantized weight_scale")
180
+ return True
181
+ return False
182
+
183
+ def create_quantized_param(
184
+ self,
185
+ model,
186
+ param_value: "torch.Tensor",
187
+ param_name: str,
188
+ target_device: "torch.device",
189
+ state_dict: Dict[str, Any],
190
+ unexpected_keys: Optional[List[str]] = None,
191
+ ):
192
+ """
193
+ Quantizes weights to INT8 symmetric format.
194
+ """
195
+ abs_max_per_row = torch.max(torch.abs(param_value), dim=1, keepdim=True)[0].clamp(min=1e-5)
196
+
197
+ weight_scale = abs_max_per_row / 127.0
198
+
199
+ weight_quantized = torch.round(param_value / weight_scale).clamp(-128, 127).to(torch.int8)
200
+
201
+ module, tensor_name = get_module_from_name(model, param_name)
202
+ module._buffers[tensor_name] = weight_quantized.to(target_device)
203
+ module._buffers["weight_scale"] = weight_scale.to(target_device)
204
+
205
+ def update_missing_keys(self, model, missing_keys: List[str], prefix: str) -> List[str]:
206
+ not_missing_keys = []
207
+ for name, module in model.named_modules():
208
+ if isinstance(module, Int8SymmetricLinear):
209
+ for missing in missing_keys:
210
+ if (
211
+ (name in missing or name in f"{prefix}.{missing}")
212
+ and not missing.endswith(".weight")
213
+ and not missing.endswith(".bias")
214
+ ):
215
+ not_missing_keys.append(missing)
216
+ return [k for k in missing_keys if k not in not_missing_keys]
217
+
218
+ def _process_model_after_weight_loading(self, model, **kwargs):
219
+ """
220
+ Post-processing after weights are loaded.
221
+ """
222
+ return True
223
+
224
+ def is_serializable(self, safe_serialization=None):
225
+ return True
226
+
227
+ @property
228
+ def is_trainable(self) -> bool:
229
+ return False
230
+
231
+
232
+ # Example usage
233
+ if __name__ == "__main__":
234
+ model_int8 = AutoModelForCausalLM.from_pretrained(
235
+ "meta-llama/Llama-3.2-1B", quantization_config=Int8SymmetricConfig(), torch_dtype=torch.float, device_map="cpu"
236
+ )
237
+
238
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
239
+ input_text = "once there is"
240
+ inputs = tokenizer(input_text, return_tensors="pt").to("cpu")
241
+ output = model_int8.generate(
242
+ **inputs,
243
+ max_length=100,
244
+ num_return_sequences=1,
245
+ no_repeat_ngram_size=2,
246
+ )
247
+ generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
248
+ print(generated_text)
249
+
250
+ # Save and upload to HUB
251
+ output_model_dir = "Llama-3.2-1B-INT8-CUSTOM"
252
+ model_int8.save_pretrained(output_model_dir)
253
+ tokenizer.save_pretrained(output_model_dir)
254
+ api = HfApi()
255
+ repo_id = "medmekk/Llama-3.2-1B-INT8-CUSTOM"
256
+ api.create_repo(repo_id, private=False)
257
+ api.upload_folder(folder_path=output_model_dir, repo_id=repo_id, repo_type="model")
tasks/tasksmith-441eeab80047/tests/source/examples/research_projects/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2025 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Research projects
18
+
19
+ This directory previously contained various research projects using 🤗 Transformers. They have been moved
20
+ to a separate repo, so you can now find them at https://github.com/huggingface/transformers-research-projects/
tasks/tasksmith-441eeab80047/tests/source/examples/run_on_remote.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. 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
+ import argparse
18
+ import shlex
19
+
20
+ import runhouse as rh
21
+
22
+
23
+ if __name__ == "__main__":
24
+ # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access
25
+ # setup instructions, if using on-demand hardware
26
+
27
+ # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster
28
+ # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster
29
+ # Throw an error if user passes both BYO and on-demand cluster args
30
+ # Otherwise, use default values
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument("--user", type=str, default="ubuntu")
33
+ parser.add_argument("--host", type=str, default="localhost")
34
+ parser.add_argument("--key_path", type=str, default=None)
35
+ parser.add_argument("--instance", type=str, default="V100:1")
36
+ parser.add_argument("--provider", type=str, default="cheapest")
37
+ parser.add_argument("--use_spot", type=bool, default=False)
38
+ parser.add_argument("--example", type=str, default="pytorch/text-generation/run_generation.py")
39
+ args, unknown = parser.parse_known_args()
40
+ if args.host != "localhost":
41
+ if args.instance != "V100:1" or args.provider != "cheapest":
42
+ raise ValueError("Cannot specify both BYO and on-demand cluster args")
43
+ cluster = rh.cluster(
44
+ name="rh-cluster", ips=[args.host], ssh_creds={"ssh_user": args.user, "ssh_private_key": args.key_path}
45
+ )
46
+ else:
47
+ cluster = rh.cluster(
48
+ name="rh-cluster", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot
49
+ )
50
+ example_dir = args.example.rsplit("/", 1)[0]
51
+
52
+ # Set up remote environment
53
+ cluster.install_packages(["pip:./"]) # Installs transformers from local source
54
+ # Note transformers is copied into the home directory on the remote machine, so we can install from there
55
+ cluster.run([f"pip install -r transformers/examples/{example_dir}/requirements.txt"])
56
+ cluster.run(["pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"])
57
+
58
+ # Run example. You can bypass the CLI wrapper and paste your own code here.
59
+ cluster.run([f'python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}'])
60
+
61
+ # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI):
62
+ # from my_script... import train
63
+ # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard']
64
+ # launch_train_gpu = rh.function(fn=train,
65
+ # system=gpu,
66
+ # reqs=reqs,
67
+ # name='train_bert_glue')
68
+ #
69
+ # We can pass in arguments just like we would to a function:
70
+ # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16
71
+ # stream_logs=True)
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/README.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+ -->
15
+
16
+ # Examples
17
+
18
+ This folder contains actively maintained examples of the use of 🤗 Transformers organized into different ML tasks. All examples in this folder are **TensorFlow** examples and are written using native Keras. If you've previously only used 🤗 Transformers via `TFTrainer`, we highly recommend taking a look at the new style - we think it's a big improvement!
19
+
20
+ In addition, all scripts here now support the [🤗 Datasets](https://github.com/huggingface/datasets) library - you can grab entire datasets just by changing one command-line argument!
21
+
22
+ ## A note on code folding
23
+
24
+ Most of these examples have been formatted with #region blocks. In IDEs such as PyCharm and VSCode, these blocks mark
25
+ named regions of code that can be folded for easier viewing. If you find any of these scripts overwhelming or difficult
26
+ to follow, we highly recommend beginning with all regions folded and then examining regions one at a time!
27
+
28
+ ## The Big Table of Tasks
29
+
30
+ Here is the list of all our examples:
31
+
32
+ | Task | Example datasets |
33
+ |---|---|
34
+ | [**`language-modeling`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling) | WikiText-2
35
+ | [**`multiple-choice`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/multiple-choice) | SWAG
36
+ | [**`question-answering`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) | SQuAD
37
+ | [**`summarization`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization) | XSum
38
+ | [**`text-classification`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification) | GLUE
39
+ | [**`token-classification`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) | CoNLL NER
40
+ | [**`translation`**](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/translation) | WMT
41
+
42
+ ## Coming soon
43
+
44
+ - **Colab notebooks** to easily run through these scripts!
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/_tests_requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tensorflow<2.16
2
+ keras<2.16
3
+ tensorboard
4
+ scikit-learn
5
+ seqeval
6
+ psutil
7
+ sacrebleu >= 1.4.12
8
+ rouge-score
9
+ tensorflow_datasets
10
+ matplotlib
11
+ git-python==1.0.3
12
+ faiss-cpu
13
+ streamlit
14
+ elasticsearch
15
+ nltk
16
+ pandas
17
+ datasets >= 1.13.3
18
+ fire
19
+ pytest<8.0.1
20
+ conllu
21
+ sentencepiece != 0.1.92
22
+ protobuf
23
+ jiwer
24
+ librosa
25
+ evaluate >= 0.2.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/contrastive-image-text/README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2023 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # TFVisionTextDualEncoder and CLIP model training examples
18
+
19
+ The following example showcases how to train a CLIP-like vision-text dual encoder model
20
+ using a pre-trained vision and text encoder.
21
+
22
+ Such a model can be used for natural language image search and potentially zero-shot image classification.
23
+ The model is inspired by [CLIP](https://openai.com/blog/clip/), introduced by Alec Radford et al.
24
+ The idea is to train a vision encoder and a text encoder jointly to project the representation of images and their
25
+ captions into the same embedding space, such that the caption embeddings are located near the embeddings
26
+ of the images they describe.
27
+
28
+ ### Download COCO dataset (2017)
29
+ This example uses COCO dataset (2017) through a custom dataset script, which requires users to manually download the
30
+ COCO dataset before training.
31
+
32
+ ```bash
33
+ mkdir data
34
+ cd data
35
+ wget http://images.cocodataset.org/zips/train2017.zip
36
+ wget http://images.cocodataset.org/zips/val2017.zip
37
+ wget http://images.cocodataset.org/zips/test2017.zip
38
+ wget http://images.cocodataset.org/annotations/annotations_trainval2017.zip
39
+ wget http://images.cocodataset.org/annotations/image_info_test2017.zip
40
+ cd ..
41
+ ```
42
+
43
+ Having downloaded COCO dataset manually you should be able to load with the `ydshieh/coc_dataset_script` dataset loading script:
44
+
45
+ ```py
46
+ import os
47
+ import datasets
48
+
49
+ COCO_DIR = os.path.join(os.getcwd(), "data")
50
+ ds = datasets.load_dataset("ydshieh/coco_dataset_script", "2017", data_dir=COCO_DIR)
51
+ ```
52
+
53
+ ### Create a model from a vision encoder model and a text encoder model
54
+ We can either load a CLIP-like vision-text dual encoder model from an existing dual encoder model, or
55
+ by using a pre-trained vision encoder model and a pre-trained text encoder model.
56
+
57
+ If you wish to load an existing dual encoder model, please use the `--model_name_or_path` argument. If
58
+ you want to use separate pre-trained vision and text models, please use the
59
+ `--vision_model_name_or_path` and `--text_model_name_or_path` arguments instead.
60
+
61
+ ### Train the model
62
+ Finally, we can run the example script to train the model:
63
+
64
+ ```bash
65
+ python examples/tensorflow/contrastive-image-text/run_clip.py \
66
+ --output_dir ./clip-roberta-finetuned \
67
+ --vision_model_name_or_path openai/clip-vit-base-patch32 \
68
+ --text_model_name_or_path FacebookAI/roberta-base \
69
+ --data_dir $PWD/data \
70
+ --dataset_name ydshieh/coco_dataset_script \
71
+ --dataset_config_name=2017 \
72
+ --image_column image_path \
73
+ --caption_column caption \
74
+ --remove_unused_columns=False \
75
+ --do_train --do_eval \
76
+ --per_device_train_batch_size="64" \
77
+ --per_device_eval_batch_size="64" \
78
+ --learning_rate="5e-5" --warmup_steps="0" --weight_decay 0.1 \
79
+ --overwrite_output_dir \
80
+ --push_to_hub
81
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/contrastive-image-text/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ tensorflow>=2.6.0
2
+ datasets>=1.8.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/contrastive-image-text/run_clip.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2023 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
+ Training a CLIP like dual encoder models using text and vision encoders in the library.
18
+
19
+ The script can be used to train CLIP like models for languages other than English by using
20
+ a text encoder pre-trained in the desired language. Currently this script supports the following vision
21
+ and text models:
22
+ Vision models: ViT(https://huggingface.co/models?filter=vit), CLIP (https://huggingface.co/models?filter=clip)
23
+ Text models: BERT, ROBERTa (https://huggingface.co/models?filter=fill-mask)
24
+ """
25
+
26
+ import logging
27
+ import os
28
+ import sys
29
+ from dataclasses import dataclass, field
30
+ from typing import Optional
31
+
32
+ import tensorflow as tf
33
+ from datasets import load_dataset
34
+ from PIL import Image
35
+
36
+ import transformers
37
+ from transformers import (
38
+ AutoImageProcessor,
39
+ AutoTokenizer,
40
+ HfArgumentParser,
41
+ PushToHubCallback,
42
+ TFAutoModel,
43
+ TFTrainingArguments,
44
+ TFVisionTextDualEncoderModel,
45
+ create_optimizer,
46
+ )
47
+ from transformers.utils import check_min_version, send_example_telemetry
48
+ from transformers.utils.versions import require_version
49
+
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
54
+ check_min_version("4.50.0.dev0")
55
+
56
+ require_version(
57
+ "datasets>=1.8.0", "To fix: pip install -r examples/tensorflow/contrastive-image-text/requirements.txt"
58
+ )
59
+
60
+
61
+ @dataclass
62
+ class ModelArguments:
63
+ """
64
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
65
+ """
66
+
67
+ model_name_or_path: str = field(
68
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}, default=None
69
+ )
70
+ vision_model_name_or_path: str = field(
71
+ metadata={"help": "Path to pretrained image model or model identifier from huggingface.co/models"},
72
+ default=None,
73
+ )
74
+ text_model_name_or_path: str = field(
75
+ metadata={"help": "Path to pretrained text model or model identifier from huggingface.co/models"}, default=None
76
+ )
77
+ config_name: Optional[str] = field(
78
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
79
+ )
80
+ tokenizer_name: Optional[str] = field(
81
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
82
+ )
83
+ image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
84
+ cache_dir: Optional[str] = field(
85
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
86
+ )
87
+ model_revision: str = field(
88
+ default="main",
89
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
90
+ )
91
+ use_fast_tokenizer: bool = field(
92
+ default=True,
93
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
94
+ )
95
+ token: str = field(
96
+ default=None,
97
+ metadata={
98
+ "help": (
99
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
100
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
101
+ )
102
+ },
103
+ )
104
+ trust_remote_code: bool = field(
105
+ default=False,
106
+ metadata={
107
+ "help": (
108
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
109
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
110
+ " code, as it will execute code present on the Hub on your local machine."
111
+ )
112
+ },
113
+ )
114
+ freeze_vision_model: bool = field(
115
+ default=False, metadata={"help": "Whether to freeze the vision model parameters or not."}
116
+ )
117
+ freeze_text_model: bool = field(
118
+ default=False, metadata={"help": "Whether to freeze the text model parameters or not."}
119
+ )
120
+
121
+
122
+ @dataclass
123
+ class DataTrainingArguments:
124
+ """
125
+ Arguments pertaining to what data we are going to input our model for training and eval.
126
+ """
127
+
128
+ dataset_name: Optional[str] = field(
129
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
130
+ )
131
+ dataset_config_name: Optional[str] = field(
132
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
133
+ )
134
+ data_dir: Optional[str] = field(default=None, metadata={"help": "The data directory containing input files."})
135
+ image_column: Optional[str] = field(
136
+ default="image_path",
137
+ metadata={"help": "The name of the column in the datasets containing the full image file paths."},
138
+ )
139
+ caption_column: Optional[str] = field(
140
+ default="caption",
141
+ metadata={"help": "The name of the column in the datasets containing the image captions."},
142
+ )
143
+ train_file: Optional[str] = field(
144
+ default=None, metadata={"help": "The input training data file (a jsonlines file)."}
145
+ )
146
+ validation_file: Optional[str] = field(
147
+ default=None,
148
+ metadata={"help": "An optional input evaluation data file (a jsonlines file)."},
149
+ )
150
+ test_file: Optional[str] = field(
151
+ default=None,
152
+ metadata={"help": "An optional input testing data file (a jsonlines file)."},
153
+ )
154
+ max_seq_length: Optional[int] = field(
155
+ default=128,
156
+ metadata={
157
+ "help": (
158
+ "The maximum total input sequence length after tokenization. Sequences longer "
159
+ "than this will be truncated, sequences shorter will be padded."
160
+ )
161
+ },
162
+ )
163
+ max_train_samples: Optional[int] = field(
164
+ default=None,
165
+ metadata={
166
+ "help": (
167
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
168
+ "value if set."
169
+ )
170
+ },
171
+ )
172
+ max_eval_samples: Optional[int] = field(
173
+ default=None,
174
+ metadata={
175
+ "help": (
176
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
177
+ "value if set."
178
+ )
179
+ },
180
+ )
181
+ overwrite_cache: bool = field(
182
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
183
+ )
184
+ preprocessing_num_workers: Optional[int] = field(
185
+ default=None,
186
+ metadata={"help": "The number of processes to use for the preprocessing."},
187
+ )
188
+
189
+ def __post_init__(self):
190
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
191
+ raise ValueError("Need either a dataset name or a training/validation file.")
192
+ else:
193
+ if self.train_file is not None:
194
+ extension = self.train_file.split(".")[-1]
195
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
196
+ if self.validation_file is not None:
197
+ extension = self.validation_file.split(".")[-1]
198
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
199
+ if self.test_file is not None:
200
+ extension = self.test_file.split(".")[-1]
201
+ assert extension in ["csv", "json"], "`test_file` should be a csv or a json file."
202
+
203
+
204
+ dataset_name_mapping = {
205
+ "image_caption_dataset.py": ("image_path", "caption"),
206
+ }
207
+
208
+
209
+ def crop_to_square(image):
210
+ height, width = tf.shape(image)[0], tf.shape(image)[1]
211
+ if height > width:
212
+ image = tf.image.crop_to_bounding_box(image, (height - width) // 2, 0, width, width)
213
+ elif width > height:
214
+ image = tf.image.crop_to_bounding_box(image, 0, (width - height) // 2, height, height)
215
+ return image
216
+
217
+
218
+ def load_as_tf_dataset(dataset, image_column, image_size, mean, std, batch_size, shuffle):
219
+ dataset = dataset.with_format("tensorflow")[:] # Load the dataset as tensor slices, but not the images yet!
220
+ tf_dataset = tf.data.Dataset.from_tensor_slices(dataset)
221
+
222
+ def load_image(sample):
223
+ image_path = sample[image_column]
224
+ image = tf.io.read_file(image_path)
225
+ image = tf.image.decode_image(image, channels=3, expand_animations=False)
226
+ image = crop_to_square(image)
227
+ image = tf.image.resize(image, [image_size, image_size], method="bicubic", antialias=True)
228
+ image = image / 255.0
229
+ image = (image - mean) / std
230
+ image = tf.transpose(image, perm=[2, 0, 1]) # Convert to channels-first
231
+ sample["pixel_values"] = image
232
+ del sample[image_column]
233
+ return sample
234
+
235
+ if shuffle:
236
+ tf_dataset = tf_dataset.shuffle(len(tf_dataset))
237
+ tf_dataset = tf_dataset.map(load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)
238
+ tf_dataset = tf_dataset.batch(batch_size, drop_remainder=shuffle)
239
+ tf_dataset = tf_dataset.prefetch(tf.data.experimental.AUTOTUNE)
240
+
241
+ return tf_dataset
242
+
243
+
244
+ def main():
245
+ # 1. Parse input arguments
246
+ # See all possible arguments in src/transformers/training_args.py
247
+ # or by passing the --help flag to this script.
248
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
249
+
250
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
251
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
252
+ # If we pass only one argument to the script and it's the path to a json file,
253
+ # let's parse it to get our arguments.
254
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
255
+ else:
256
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
257
+
258
+ if model_args.model_name_or_path is not None:
259
+ if model_args.vision_model_name_or_path is not None or model_args.text_model_name_or_path is not None:
260
+ raise ValueError(
261
+ "If using model_name_or_path, you cannot specify separate image/text model paths as well!"
262
+ )
263
+
264
+ if model_args.vision_model_name_or_path is not None or model_args.text_model_name_or_path is not None:
265
+ if model_args.model_name_or_path is not None:
266
+ raise ValueError(
267
+ "If using separate image/text model paths, you cannot specify model_name_or_path as well!"
268
+ )
269
+ if not (model_args.vision_model_name_or_path is not None and model_args.text_model_name_or_path is not None):
270
+ raise ValueError(
271
+ "If using separate image/text model paths, you must specify both vision_model_name_or_path "
272
+ "and text_model_name_or_path!"
273
+ )
274
+
275
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
276
+ # information sent is the one passed as arguments along with your Python/TensorFlow versions.
277
+ send_example_telemetry("run_clip", model_args, data_args, framework="tensorflow")
278
+
279
+ # 2. Setup logging
280
+ logging.basicConfig(
281
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
282
+ datefmt="%m/%d/%Y %H:%M:%S",
283
+ handlers=[logging.StreamHandler(sys.stdout)],
284
+ )
285
+
286
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
287
+ transformers.utils.logging.set_verbosity_info()
288
+
289
+ log_level = training_args.get_process_log_level()
290
+ logger.setLevel(log_level)
291
+ transformers.utils.logging.set_verbosity(log_level)
292
+ transformers.utils.logging.enable_default_handler()
293
+ transformers.utils.logging.enable_explicit_format()
294
+
295
+ # Log on each process the small summary:
296
+ logger.info(f"Training/evaluation parameters {training_args}")
297
+
298
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
299
+ last_checkpoint = None
300
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
301
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
302
+ raise ValueError(
303
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
304
+ "Use --overwrite_output_dir to overcome."
305
+ )
306
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
307
+ logger.info(
308
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
309
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
310
+ )
311
+
312
+ # 4. Load dataset
313
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
314
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
315
+ # (the dataset will be downloaded automatically from the datasets Hub).
316
+ #
317
+ # For CSV/JSON files this script will use the first column for the full image path and the second column for the
318
+ # captions (unless you specify column names for this with the `image_column` and `caption_column` arguments).
319
+ #
320
+ if data_args.dataset_name is not None:
321
+ # Downloading and loading a dataset from the hub.
322
+ dataset = load_dataset(
323
+ data_args.dataset_name,
324
+ data_args.dataset_config_name,
325
+ cache_dir=model_args.cache_dir,
326
+ keep_in_memory=False,
327
+ data_dir=data_args.data_dir,
328
+ token=model_args.token,
329
+ trust_remote_code=model_args.trust_remote_code,
330
+ )
331
+ else:
332
+ data_files = {}
333
+ if data_args.train_file is not None:
334
+ data_files["train"] = data_args.train_file
335
+ extension = data_args.train_file.split(".")[-1]
336
+ if data_args.validation_file is not None:
337
+ data_files["validation"] = data_args.validation_file
338
+ extension = data_args.validation_file.split(".")[-1]
339
+ if data_args.test_file is not None:
340
+ data_files["test"] = data_args.test_file
341
+ extension = data_args.test_file.split(".")[-1]
342
+ dataset = load_dataset(
343
+ extension,
344
+ data_files=data_files,
345
+ cache_dir=model_args.cache_dir,
346
+ token=model_args.token,
347
+ )
348
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
349
+ # https://huggingface.co/docs/datasets/loading_datasets.
350
+
351
+ # 5. Load pretrained model, tokenizer, and image processor
352
+ if model_args.tokenizer_name:
353
+ tokenizer = AutoTokenizer.from_pretrained(
354
+ model_args.tokenizer_name,
355
+ cache_dir=model_args.cache_dir,
356
+ use_fast=model_args.use_fast_tokenizer,
357
+ token=model_args.token,
358
+ trust_remote_code=model_args.trust_remote_code,
359
+ )
360
+ elif model_args.model_name_or_path:
361
+ tokenizer = AutoTokenizer.from_pretrained(
362
+ model_args.model_name_or_path,
363
+ cache_dir=model_args.cache_dir,
364
+ use_fast=model_args.use_fast_tokenizer,
365
+ token=model_args.token,
366
+ trust_remote_code=model_args.trust_remote_code,
367
+ )
368
+ elif model_args.text_model_name_or_path:
369
+ tokenizer = AutoTokenizer.from_pretrained(
370
+ model_args.text_model_name_or_path,
371
+ cache_dir=model_args.cache_dir,
372
+ use_fast=model_args.use_fast_tokenizer,
373
+ token=model_args.token,
374
+ trust_remote_code=model_args.trust_remote_code,
375
+ )
376
+ else:
377
+ raise ValueError(
378
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
379
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
380
+ )
381
+
382
+ if model_args.model_name_or_path:
383
+ # Load image_processor, in this script we only use this to get the mean and std for normalization.
384
+ image_processor = AutoImageProcessor.from_pretrained(
385
+ model_args.image_processor_name or model_args.model_name_or_path,
386
+ cache_dir=model_args.cache_dir,
387
+ revision=model_args.model_revision,
388
+ token=model_args.token,
389
+ trust_remote_code=model_args.trust_remote_code,
390
+ )
391
+ with training_args.strategy.scope():
392
+ model = TFAutoModel.from_pretrained(
393
+ model_args.model_name_or_path,
394
+ cache_dir=model_args.cache_dir,
395
+ revision=model_args.model_revision,
396
+ token=model_args.token,
397
+ trust_remote_code=model_args.trust_remote_code,
398
+ )
399
+ else:
400
+ # Load image_processor, in this script we only use this to get the mean and std for normalization.
401
+ image_processor = AutoImageProcessor.from_pretrained(
402
+ model_args.image_processor_name or model_args.vision_model_name_or_path,
403
+ cache_dir=model_args.cache_dir,
404
+ revision=model_args.model_revision,
405
+ token=model_args.token,
406
+ trust_remote_code=model_args.trust_remote_code,
407
+ )
408
+ with training_args.strategy.scope():
409
+ model = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
410
+ vision_model_name_or_path=model_args.vision_model_name_or_path,
411
+ text_model_name_or_path=model_args.text_model_name_or_path,
412
+ cache_dir=model_args.cache_dir,
413
+ token=model_args.token,
414
+ trust_remote_code=model_args.trust_remote_code,
415
+ )
416
+ config = model.config
417
+
418
+ if model_args.freeze_vision_model:
419
+ model.vision_model.trainable = False
420
+
421
+ if model_args.freeze_text_model:
422
+ model.text_model.trainable = False
423
+
424
+ # Preprocessing the datasets.
425
+ # We need to tokenize inputs and targets.
426
+ if training_args.do_train:
427
+ column_names = dataset["train"].column_names
428
+ elif training_args.do_eval:
429
+ column_names = dataset["validation"].column_names
430
+ elif training_args.do_predict:
431
+ column_names = dataset["test"].column_names
432
+ else:
433
+ logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
434
+ return
435
+
436
+ # 6. Get the column names for input/target.
437
+ dataset_columns = dataset_name_mapping.get(data_args.dataset_name, None)
438
+ if data_args.image_column is None:
439
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
440
+ else:
441
+ image_column = data_args.image_column
442
+ if image_column not in column_names:
443
+ raise ValueError(
444
+ f"--image_column' value '{data_args.image_column}' needs to be one of: {', '.join(column_names)}"
445
+ )
446
+ if data_args.caption_column is None:
447
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
448
+ else:
449
+ caption_column = data_args.caption_column
450
+ if caption_column not in column_names:
451
+ raise ValueError(
452
+ f"--caption_column' value '{data_args.caption_column}' needs to be one of: {', '.join(column_names)}"
453
+ )
454
+
455
+ # # 7. Preprocessing the datasets.
456
+
457
+ # We need to tokenize input captions and transform the images.
458
+ def tokenize_captions(examples):
459
+ captions = list(examples[caption_column])
460
+ text_inputs = tokenizer(captions, max_length=data_args.max_seq_length, padding="max_length", truncation=True)
461
+ examples["input_ids"] = text_inputs.input_ids
462
+ examples["attention_mask"] = text_inputs.attention_mask
463
+ return examples
464
+
465
+ def filter_corrupt_images(examples):
466
+ """remove problematic images"""
467
+ valid_images = []
468
+ for image_file in examples[image_column]:
469
+ try:
470
+ Image.open(image_file)
471
+ valid_images.append(True)
472
+ except Exception:
473
+ valid_images.append(False)
474
+ return valid_images
475
+
476
+ if training_args.do_train:
477
+ if "train" not in dataset:
478
+ raise ValueError("--do_train requires a train dataset")
479
+ train_dataset = dataset["train"]
480
+ if data_args.max_train_samples is not None:
481
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
482
+ train_dataset = train_dataset.select(range(max_train_samples))
483
+
484
+ train_dataset = train_dataset.filter(
485
+ filter_corrupt_images, batched=True, num_proc=data_args.preprocessing_num_workers
486
+ )
487
+ train_dataset = train_dataset.map(
488
+ function=tokenize_captions,
489
+ batched=True,
490
+ remove_columns=[col for col in column_names if col != image_column],
491
+ num_proc=data_args.preprocessing_num_workers,
492
+ load_from_cache_file=not data_args.overwrite_cache,
493
+ desc="Running tokenizer on train dataset",
494
+ )
495
+
496
+ tf_train_dataset = load_as_tf_dataset(
497
+ dataset=train_dataset,
498
+ batch_size=training_args.per_device_train_batch_size,
499
+ image_column=image_column,
500
+ image_size=config.vision_config.image_size,
501
+ mean=image_processor.image_mean,
502
+ std=image_processor.image_std,
503
+ shuffle=True,
504
+ )
505
+
506
+ if training_args.do_eval:
507
+ if "validation" not in dataset:
508
+ raise ValueError("--do_eval requires a train validation")
509
+ eval_dataset = dataset["validation"]
510
+ if data_args.max_eval_samples is not None:
511
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
512
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
513
+
514
+ eval_dataset = eval_dataset.filter(
515
+ filter_corrupt_images, batched=True, num_proc=data_args.preprocessing_num_workers
516
+ )
517
+ eval_dataset = eval_dataset.map(
518
+ function=tokenize_captions,
519
+ batched=True,
520
+ num_proc=data_args.preprocessing_num_workers,
521
+ remove_columns=[col for col in column_names if col != image_column],
522
+ load_from_cache_file=not data_args.overwrite_cache,
523
+ desc="Running tokenizer on validation dataset",
524
+ )
525
+
526
+ tf_eval_dataset = load_as_tf_dataset(
527
+ dataset=eval_dataset,
528
+ batch_size=training_args.per_device_eval_batch_size,
529
+ image_column=image_column,
530
+ image_size=config.vision_config.image_size,
531
+ mean=image_processor.image_mean,
532
+ std=image_processor.image_std,
533
+ shuffle=False,
534
+ )
535
+
536
+ # 8. Preparing push_to_hub and model card
537
+ push_to_hub_model_id = training_args.push_to_hub_model_id
538
+ if model_args.model_name_or_path is not None:
539
+ model_name = model_args.model_name_or_path.split("/")[-1]
540
+ else:
541
+ vision_name = model_args.vision_model_name_or_path.split("/")[-1]
542
+ text_name = model_args.text_model_name_or_path.split("/")[-1]
543
+ model_name = f"{vision_name}-{text_name}"
544
+ if not push_to_hub_model_id:
545
+ if data_args.dataset_name is not None:
546
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}"
547
+ else:
548
+ push_to_hub_model_id = f"{model_name}-finetuned-contrastive-image-text-modeling"
549
+
550
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "contrastive-image-text-modeling"}
551
+ if data_args.dataset_name is not None:
552
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
553
+ if data_args.dataset_config_name is not None:
554
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
555
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
556
+ else:
557
+ model_card_kwargs["dataset"] = data_args.dataset_name
558
+
559
+ if training_args.push_to_hub:
560
+ callbacks = [
561
+ PushToHubCallback(
562
+ output_dir=training_args.output_dir,
563
+ hub_model_id=push_to_hub_model_id,
564
+ hub_token=training_args.push_to_hub_token,
565
+ tokenizer=tokenizer,
566
+ **model_card_kwargs,
567
+ )
568
+ ]
569
+ else:
570
+ callbacks = []
571
+
572
+ # # 9. Training
573
+ if training_args.do_train:
574
+ num_train_steps = int(len(tf_train_dataset) * int(training_args.num_train_epochs))
575
+ if training_args.warmup_steps > 0:
576
+ num_warmup_steps = training_args.warmup_steps
577
+ elif training_args.warmup_ratio > 0:
578
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
579
+ else:
580
+ num_warmup_steps = 0
581
+ optimizer, lr_schedule = create_optimizer(
582
+ init_lr=training_args.learning_rate,
583
+ num_train_steps=num_train_steps,
584
+ num_warmup_steps=num_warmup_steps,
585
+ adam_beta1=training_args.adam_beta1,
586
+ adam_beta2=training_args.adam_beta2,
587
+ adam_epsilon=training_args.adam_epsilon,
588
+ weight_decay_rate=training_args.weight_decay,
589
+ adam_global_clipnorm=training_args.max_grad_norm,
590
+ )
591
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
592
+ # use this for training unless you specify your own loss function in compile().
593
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
594
+
595
+ if not training_args.do_eval:
596
+ tf_eval_dataset = None
597
+ model.fit(
598
+ tf_train_dataset,
599
+ validation_data=tf_eval_dataset,
600
+ epochs=int(training_args.num_train_epochs),
601
+ callbacks=callbacks,
602
+ )
603
+
604
+ # # 10. Evaluation
605
+
606
+ if training_args.do_eval and not training_args.do_train:
607
+ model.evaluate(tf_eval_dataset)
608
+
609
+
610
+ if __name__ == "__main__":
611
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/image-classification/README.md ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2023 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Image classification examples
18
+
19
+ This directory contains 2 scripts that showcase how to fine-tune any model supported by the [`TFAutoModelForImageClassification` API](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.TFAutoModelForImageClassification) (such as [ViT](https://huggingface.co/docs/transformers/main/en/model_doc/vit), [ConvNeXT](https://huggingface.co/docs/transformers/main/en/model_doc/convnext), [ResNet](https://huggingface.co/docs/transformers/main/en/model_doc/resnet), [Swin Transformer](https://huggingface.co/docs/transformers/main/en/model_doc/swin)...) using TensorFlow. They can be used to fine-tune models on both [datasets from the hub](#using-datasets-from-hub) as well as on [your own custom data](#using-your-own-data).
20
+
21
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/image_classification_inference_widget.png" height="400" />
22
+
23
+ Try out the inference widget here: https://huggingface.co/google/vit-base-patch16-224
24
+
25
+ ## TensorFlow
26
+
27
+ Based on the script [`run_image_classification.py`](https://github.com/huggingface/transformers/blob/main/examples/tensorflow/image-classification/run_image_classification.py).
28
+
29
+ ### Using datasets from Hub
30
+
31
+ Here we show how to fine-tune a Vision Transformer (`ViT`) on the [beans](https://huggingface.co/datasets/beans) dataset, to classify the disease type of bean leaves. The following will train a model and push it to the `amyeroberts/vit-base-beans` repo.
32
+
33
+ ```bash
34
+ python run_image_classification.py \
35
+ --dataset_name beans \
36
+ --output_dir ./beans_outputs/ \
37
+ --remove_unused_columns False \
38
+ --do_train \
39
+ --do_eval \
40
+ --push_to_hub \
41
+ --hub_model_id amyeroberts/vit-base-beans \
42
+ --learning_rate 2e-5 \
43
+ --num_train_epochs 5 \
44
+ --per_device_train_batch_size 8 \
45
+ --per_device_eval_batch_size 8 \
46
+ --logging_strategy steps \
47
+ --logging_steps 10 \
48
+ --eval_strategy epoch \
49
+ --save_strategy epoch \
50
+ --load_best_model_at_end True \
51
+ --save_total_limit 3 \
52
+ --seed 1337
53
+ ```
54
+
55
+ 👀 See the results here: [amyeroberts/vit-base-beans](https://huggingface.co/amyeroberts/vit-base-beans).
56
+
57
+ Note that you can replace the model and dataset by simply setting the `model_name_or_path` and `dataset_name` arguments respectively, with any model or dataset from the [hub](https://huggingface.co/). For an overview of all possible arguments, we refer to the [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) of the `TrainingArguments`, which can be passed as flags.
58
+
59
+ > If your model classification head dimensions do not fit the number of labels in the dataset, you can specify `--ignore_mismatched_sizes` to adapt it.
60
+
61
+ ### Using your own data
62
+
63
+ To use your own dataset, there are 2 ways:
64
+ - you can either provide your own folders as `--train_dir` and/or `--validation_dir` arguments
65
+ - you can upload your dataset to the hub (possibly as a private repo, if you prefer so), and simply pass the `--dataset_name` argument.
66
+
67
+ Below, we explain both in more detail.
68
+
69
+ #### Provide them as folders
70
+
71
+ If you provide your own folders with images, the script expects the following directory structure:
72
+
73
+ ```bash
74
+ root/dog/xxx.png
75
+ root/dog/xxy.png
76
+ root/dog/[...]/xxz.png
77
+
78
+ root/cat/123.png
79
+ root/cat/nsdf3.png
80
+ root/cat/[...]/asd932_.png
81
+ ```
82
+
83
+ In other words, you need to organize your images in subfolders, based on their class. You can then run the script like this:
84
+
85
+ ```bash
86
+ python run_image_classification.py \
87
+ --train_dir <path-to-train-root> \
88
+ --output_dir ./outputs/ \
89
+ --remove_unused_columns False \
90
+ --do_train \
91
+ --do_eval
92
+ ```
93
+
94
+ Internally, the script will use the [`ImageFolder`](https://huggingface.co/docs/datasets/v2.0.0/en/image_process#imagefolder) feature which will automatically turn the folders into 🤗 Dataset objects.
95
+
96
+ ##### 💡 The above will split the train dir into training and evaluation sets
97
+ - To control the split amount, use the `--train_val_split` flag.
98
+ - To provide your own validation split in its own directory, you can pass the `--validation_dir <path-to-val-root>` flag.
99
+
100
+ #### Upload your data to the hub, as a (possibly private) repo
101
+
102
+ To upload your image dataset to the hub you can use the [`ImageFolder`](https://huggingface.co/docs/datasets/v2.0.0/en/image_process#imagefolder) feature available in 🤗 Datasets. Simply do the following:
103
+
104
+ ```python
105
+ from datasets import load_dataset
106
+
107
+ # example 1: local folder
108
+ dataset = load_dataset("imagefolder", data_dir="path_to_your_folder")
109
+
110
+ # example 2: local files (supported formats are tar, gzip, zip, xz, rar, zstd)
111
+ dataset = load_dataset("imagefolder", data_files="path_to_zip_file")
112
+
113
+ # example 3: remote files (supported formats are tar, gzip, zip, xz, rar, zstd)
114
+ dataset = load_dataset("imagefolder", data_files="https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip")
115
+
116
+ # example 4: providing several splits
117
+ dataset = load_dataset("imagefolder", data_files={"train": ["path/to/file1", "path/to/file2"], "test": ["path/to/file3", "path/to/file4"]})
118
+ ```
119
+
120
+ `ImageFolder` will create a `label` column, and the label name is based on the directory name.
121
+
122
+ Next, push it to the hub!
123
+
124
+ ```python
125
+ # assuming you have ran the huggingface-cli login command in a terminal
126
+ dataset.push_to_hub("name_of_your_dataset")
127
+
128
+ # if you want to push to a private repo, simply pass private=True:
129
+ dataset.push_to_hub("name_of_your_dataset", private=True)
130
+ ```
131
+
132
+ and that's it! You can now train your model by simply setting the `--dataset_name` argument to the name of your dataset on the hub (as explained in [Using datasets from the 🤗 hub](#using-datasets-from-hub)).
133
+
134
+ More on this can also be found in [this blog post](https://huggingface.co/blog/image-search-datasets).
135
+
136
+ ### Sharing your model on 🤗 Hub
137
+
138
+ 0. If you haven't already, [sign up](https://huggingface.co/join) for a 🤗 account
139
+
140
+ 1. Make sure you have `git-lfs` installed and git set up.
141
+
142
+ ```bash
143
+ $ apt install git-lfs
144
+ $ git config --global user.email "you@example.com"
145
+ $ git config --global user.name "Your Name"
146
+ ```
147
+
148
+ 2. Log in with your HuggingFace account credentials using `huggingface-cli`:
149
+
150
+ ```bash
151
+ $ huggingface-cli login
152
+ # ...follow the prompts
153
+ ```
154
+
155
+ 3. When running the script, pass the following arguments:
156
+
157
+ ```bash
158
+ python run_image_classification.py \
159
+ --push_to_hub \
160
+ --push_to_hub_model_id <name-your-model> \
161
+ ...
162
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/image-classification/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets>=1.17.0
2
+ evaluate
3
+ tensorflow>=2.4
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/image-classification/run_image_classification.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Inc. 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
+ """
16
+ Fine-tuning a 🤗 Transformers model for image classification.
17
+
18
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
19
+ https://huggingface.co/models?filter=image-classification
20
+ """
21
+
22
+ import json
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Optional
28
+
29
+ import evaluate
30
+ import numpy as np
31
+ import tensorflow as tf
32
+ from datasets import load_dataset
33
+ from PIL import Image
34
+
35
+ import transformers
36
+ from transformers import (
37
+ TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
38
+ AutoConfig,
39
+ AutoImageProcessor,
40
+ DefaultDataCollator,
41
+ HfArgumentParser,
42
+ PushToHubCallback,
43
+ TFAutoModelForImageClassification,
44
+ TFTrainingArguments,
45
+ create_optimizer,
46
+ set_seed,
47
+ )
48
+ from transformers.keras_callbacks import KerasMetricCallback
49
+ from transformers.modeling_tf_utils import keras
50
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
51
+ from transformers.utils import check_min_version, send_example_telemetry
52
+ from transformers.utils.versions import require_version
53
+
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
58
+ check_min_version("4.50.0.dev0")
59
+
60
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt")
61
+
62
+ MODEL_CONFIG_CLASSES = list(TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
63
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
64
+
65
+
66
+ def pil_loader(path: str):
67
+ with open(path, "rb") as f:
68
+ im = Image.open(f)
69
+ return im.convert("RGB")
70
+
71
+
72
+ @dataclass
73
+ class DataTrainingArguments:
74
+ """
75
+ Arguments pertaining to what data we are going to input our model for training and eval.
76
+ Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify
77
+ them on the command line.
78
+ """
79
+
80
+ dataset_name: Optional[str] = field(
81
+ default=None,
82
+ metadata={
83
+ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
84
+ },
85
+ )
86
+ dataset_config_name: Optional[str] = field(
87
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
88
+ )
89
+ train_dir: Optional[str] = field(default=None, metadata={"help": "A folder containing the training data."})
90
+ validation_dir: Optional[str] = field(default=None, metadata={"help": "A folder containing the validation data."})
91
+ train_val_split: Optional[float] = field(
92
+ default=0.15, metadata={"help": "Percent to split off of train for validation."}
93
+ )
94
+ overwrite_cache: bool = field(
95
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
96
+ )
97
+ preprocessing_num_workers: Optional[int] = field(
98
+ default=None,
99
+ metadata={"help": "The number of processes to use for the preprocessing."},
100
+ )
101
+ max_train_samples: Optional[int] = field(
102
+ default=None,
103
+ metadata={
104
+ "help": (
105
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
106
+ "value if set."
107
+ )
108
+ },
109
+ )
110
+ max_eval_samples: Optional[int] = field(
111
+ default=None,
112
+ metadata={
113
+ "help": (
114
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
115
+ "value if set."
116
+ )
117
+ },
118
+ )
119
+ max_predict_samples: Optional[int] = field(
120
+ default=None,
121
+ metadata={
122
+ "help": (
123
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
124
+ "value if set."
125
+ )
126
+ },
127
+ )
128
+
129
+ def __post_init__(self):
130
+ if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
131
+ raise ValueError(
132
+ "You must specify either a dataset name from the hub or a train and/or validation directory."
133
+ )
134
+
135
+
136
+ @dataclass
137
+ class ModelArguments:
138
+ """
139
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
140
+ """
141
+
142
+ model_name_or_path: str = field(
143
+ default="google/vit-base-patch16-224-in21k",
144
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"},
145
+ )
146
+ model_type: Optional[str] = field(
147
+ default=None,
148
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
149
+ )
150
+ config_name: Optional[str] = field(
151
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
152
+ )
153
+ cache_dir: Optional[str] = field(
154
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
155
+ )
156
+ model_revision: str = field(
157
+ default="main",
158
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
159
+ )
160
+ image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
161
+ token: str = field(
162
+ default=None,
163
+ metadata={
164
+ "help": (
165
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
166
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
167
+ )
168
+ },
169
+ )
170
+ trust_remote_code: bool = field(
171
+ default=False,
172
+ metadata={
173
+ "help": (
174
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
175
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
176
+ " code, as it will execute code present on the Hub on your local machine."
177
+ )
178
+ },
179
+ )
180
+ ignore_mismatched_sizes: bool = field(
181
+ default=False,
182
+ metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."},
183
+ )
184
+
185
+
186
+ def center_crop(image, size):
187
+ size = (size, size) if isinstance(size, int) else size
188
+ orig_height, orig_width, _ = image.shape
189
+ crop_height, crop_width = size
190
+ top = (orig_height - orig_width) // 2
191
+ left = (orig_width - crop_width) // 2
192
+ image = tf.image.crop_to_bounding_box(image, top, left, crop_height, crop_width)
193
+ return image
194
+
195
+
196
+ # Numpy and TensorFlow compatible version of PyTorch RandomResizedCrop. Code adapted from:
197
+ # https://pytorch.org/vision/main/_modules/torchvision/transforms/transforms.html#RandomResizedCrop
198
+ def random_crop(image, scale=(0.08, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0)):
199
+ height, width, _ = image.shape
200
+ area = height * width
201
+ log_ratio = np.log(ratio)
202
+ for _ in range(10):
203
+ target_area = np.random.uniform(*scale) * area
204
+ aspect_ratio = np.exp(np.random.uniform(*log_ratio))
205
+ w = int(round(np.sqrt(target_area * aspect_ratio)))
206
+ h = int(round(np.sqrt(target_area / aspect_ratio)))
207
+ if 0 < w <= width and 0 < h <= height:
208
+ i = np.random.randint(0, height - h + 1)
209
+ j = np.random.randint(0, width - w + 1)
210
+ return image[i : i + h, j : j + w, :]
211
+
212
+ # Fallback to central crop
213
+ in_ratio = float(width) / float(height)
214
+ w = width if in_ratio < min(ratio) else int(round(height * max(ratio)))
215
+ h = height if in_ratio > max(ratio) else int(round(width / min(ratio)))
216
+ i = (height - h) // 2
217
+ j = (width - w) // 2
218
+ return image[i : i + h, j : j + w, :]
219
+
220
+
221
+ def random_resized_crop(image, size, scale=(0.08, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0)):
222
+ size = (size, size) if isinstance(size, int) else size
223
+ image = random_crop(image, scale, ratio)
224
+ image = tf.image.resize(image, size)
225
+ return image
226
+
227
+
228
+ def main():
229
+ # See all possible arguments in src/transformers/training_args.py
230
+ # or by passing the --help flag to this script.
231
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
232
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
233
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
234
+ # If we pass only one argument to the script and it's the path to a json file,
235
+ # let's parse it to get our arguments.
236
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
237
+ else:
238
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
239
+
240
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
241
+ # information sent is the one passed as arguments along with your Python/TensorFlow versions.
242
+ send_example_telemetry("run_image_classification", model_args, data_args, framework="tensorflow")
243
+
244
+ # Checkpoints. Find the checkpoint the use when loading the model.
245
+ checkpoint = None
246
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
247
+ checkpoint = get_last_checkpoint(training_args.output_dir)
248
+ if checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
249
+ raise ValueError(
250
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
251
+ "Use --overwrite_output_dir to overcome."
252
+ )
253
+ elif checkpoint is not None and training_args.resume_from_checkpoint is None:
254
+ logger.info(
255
+ f"Checkpoint detected, resuming training at {checkpoint}. To avoid this behavior, change "
256
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
257
+ )
258
+
259
+ # Setup logging
260
+ logging.basicConfig(
261
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
262
+ datefmt="%m/%d/%Y %H:%M:%S",
263
+ handlers=[logging.StreamHandler(sys.stdout)],
264
+ )
265
+ log_level = training_args.get_process_log_level()
266
+ logger.setLevel(log_level)
267
+
268
+ # Set the verbosity to info of the Transformers logger (on main process only):
269
+ if is_main_process(training_args.local_rank):
270
+ transformers.utils.logging.set_verbosity_info()
271
+ transformers.utils.logging.enable_default_handler()
272
+ transformers.utils.logging.enable_explicit_format()
273
+ logger.info(f"Training/evaluation parameters {training_args}")
274
+
275
+ # region Dataset and labels
276
+ # Set seed before initializing model.
277
+ set_seed(training_args.seed)
278
+
279
+ # Initialize our dataset and prepare it for the 'image-classification' task.
280
+ if data_args.dataset_name is not None:
281
+ dataset = load_dataset(
282
+ data_args.dataset_name,
283
+ data_args.dataset_config_name,
284
+ cache_dir=model_args.cache_dir,
285
+ token=model_args.token,
286
+ trust_remote_code=model_args.trust_remote_code,
287
+ )
288
+ else:
289
+ data_files = {}
290
+ if data_args.train_dir is not None:
291
+ data_files["train"] = os.path.join(data_args.train_dir, "**")
292
+ if data_args.validation_dir is not None:
293
+ data_files["validation"] = os.path.join(data_args.validation_dir, "**")
294
+ dataset = load_dataset(
295
+ "imagefolder",
296
+ data_files=data_files,
297
+ cache_dir=model_args.cache_dir,
298
+ )
299
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
300
+ # https://huggingface.co/docs/datasets/loading_datasets.
301
+
302
+ # Prepare label mappings.
303
+ # We'll include these in the model's config to get human readable labels in the Inference API.
304
+ labels = dataset["train"].features["labels"].names
305
+ label2id, id2label = {}, {}
306
+ for i, label in enumerate(labels):
307
+ label2id[label] = str(i)
308
+ id2label[str(i)] = label
309
+
310
+ # Load model image processor and configuration
311
+ config = AutoConfig.from_pretrained(
312
+ model_args.config_name or model_args.model_name_or_path,
313
+ num_labels=len(labels),
314
+ label2id=label2id,
315
+ id2label=id2label,
316
+ finetuning_task="image-classification",
317
+ cache_dir=model_args.cache_dir,
318
+ revision=model_args.model_revision,
319
+ token=model_args.token,
320
+ trust_remote_code=model_args.trust_remote_code,
321
+ )
322
+ image_processor = AutoImageProcessor.from_pretrained(
323
+ model_args.image_processor_name or model_args.model_name_or_path,
324
+ cache_dir=model_args.cache_dir,
325
+ revision=model_args.model_revision,
326
+ token=model_args.token,
327
+ trust_remote_code=model_args.trust_remote_code,
328
+ )
329
+
330
+ # If we don't have a validation split, split off a percentage of train as validation.
331
+ data_args.train_val_split = None if "validation" in dataset.keys() else data_args.train_val_split
332
+ if isinstance(data_args.train_val_split, float) and data_args.train_val_split > 0.0:
333
+ split = dataset["train"].train_test_split(data_args.train_val_split)
334
+ dataset["train"] = split["train"]
335
+ dataset["validation"] = split["test"]
336
+
337
+ # Define our data preprocessing function. It takes an image file path as input and returns
338
+ # Write a note describing the resizing behaviour.
339
+ if "shortest_edge" in image_processor.size:
340
+ # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
341
+ image_size = (image_processor.size["shortest_edge"], image_processor.size["shortest_edge"])
342
+ else:
343
+ image_size = (image_processor.size["height"], image_processor.size["width"])
344
+
345
+ def _train_transforms(image):
346
+ img_size = image_size
347
+ image = keras.utils.img_to_array(image)
348
+ image = random_resized_crop(image, size=img_size)
349
+ image = tf.image.random_flip_left_right(image)
350
+ image /= 255.0
351
+ image = (image - image_processor.image_mean) / image_processor.image_std
352
+ image = tf.transpose(image, perm=[2, 0, 1])
353
+ return image
354
+
355
+ def _val_transforms(image):
356
+ image = keras.utils.img_to_array(image)
357
+ image = tf.image.resize(image, size=image_size)
358
+ # image = np.array(image) # FIXME - use tf.image function
359
+ image = center_crop(image, size=image_size)
360
+ image /= 255.0
361
+ image = (image - image_processor.image_mean) / image_processor.image_std
362
+ image = tf.transpose(image, perm=[2, 0, 1])
363
+ return image
364
+
365
+ def train_transforms(example_batch):
366
+ """Apply _train_transforms across a batch."""
367
+ example_batch["pixel_values"] = [
368
+ _train_transforms(pil_img.convert("RGB")) for pil_img in example_batch["image"]
369
+ ]
370
+ return example_batch
371
+
372
+ def val_transforms(example_batch):
373
+ """Apply _val_transforms across a batch."""
374
+ example_batch["pixel_values"] = [_val_transforms(pil_img.convert("RGB")) for pil_img in example_batch["image"]]
375
+ return example_batch
376
+
377
+ train_dataset = None
378
+ if training_args.do_train:
379
+ if "train" not in dataset:
380
+ raise ValueError("--do_train requires a train dataset")
381
+ train_dataset = dataset["train"]
382
+ if data_args.max_train_samples is not None:
383
+ train_dataset = train_dataset.shuffle(seed=training_args.seed).select(range(data_args.max_train_samples))
384
+ train_dataset = train_dataset.map(
385
+ train_transforms,
386
+ batched=True,
387
+ num_proc=data_args.preprocessing_num_workers,
388
+ load_from_cache_file=not data_args.overwrite_cache,
389
+ )
390
+
391
+ eval_dataset = None
392
+ if training_args.do_eval:
393
+ if "validation" not in dataset:
394
+ raise ValueError("--do_eval requires a validation dataset")
395
+ eval_dataset = dataset["validation"]
396
+ if data_args.max_eval_samples is not None:
397
+ eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
398
+ # Set the validation transforms
399
+ eval_dataset = eval_dataset.map(
400
+ val_transforms,
401
+ batched=True,
402
+ num_proc=data_args.preprocessing_num_workers,
403
+ load_from_cache_file=not data_args.overwrite_cache,
404
+ )
405
+
406
+ predict_dataset = None
407
+ if training_args.do_predict:
408
+ if "test" not in dataset:
409
+ raise ValueError("--do_predict requires a test dataset")
410
+ predict_dataset = dataset["test"]
411
+ if data_args.max_predict_samples is not None:
412
+ predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))
413
+ # Set the test transforms
414
+ predict_dataset = predict_dataset.map(
415
+ val_transforms,
416
+ batched=True,
417
+ num_proc=data_args.preprocessing_num_workers,
418
+ load_from_cache_file=not data_args.overwrite_cache,
419
+ )
420
+
421
+ collate_fn = DefaultDataCollator(return_tensors="np")
422
+
423
+ # Load the accuracy metric from the datasets package
424
+ metric = evaluate.load("accuracy", cache_dir=model_args.cache_dir)
425
+
426
+ # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
427
+ # predictions and label_ids field) and has to return a dictionary string to float.
428
+ def compute_metrics(p):
429
+ """Computes accuracy on a batch of predictions"""
430
+ logits, label_ids = p
431
+ predictions = np.argmax(logits, axis=-1)
432
+ metrics = metric.compute(predictions=predictions, references=label_ids)
433
+ return metrics
434
+
435
+ with training_args.strategy.scope():
436
+ if checkpoint is None:
437
+ model_path = model_args.model_name_or_path
438
+ else:
439
+ model_path = checkpoint
440
+
441
+ model = TFAutoModelForImageClassification.from_pretrained(
442
+ model_path,
443
+ config=config,
444
+ from_pt=bool(".bin" in model_path),
445
+ cache_dir=model_args.cache_dir,
446
+ revision=model_args.model_revision,
447
+ token=model_args.token,
448
+ trust_remote_code=model_args.trust_remote_code,
449
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
450
+ )
451
+ num_replicas = training_args.strategy.num_replicas_in_sync
452
+ total_train_batch_size = training_args.per_device_train_batch_size * num_replicas
453
+ total_eval_batch_size = training_args.per_device_eval_batch_size * num_replicas
454
+
455
+ dataset_options = tf.data.Options()
456
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
457
+
458
+ if training_args.do_train:
459
+ num_train_steps = int(len(train_dataset) * training_args.num_train_epochs)
460
+ if training_args.warmup_steps > 0:
461
+ num_warmpup_steps = int(training_args.warmup_steps)
462
+ elif training_args.warmup_ratio > 0:
463
+ num_warmpup_steps = int(training_args.warmup_ratio * num_train_steps)
464
+ else:
465
+ num_warmpup_steps = 0
466
+
467
+ optimizer, _ = create_optimizer(
468
+ init_lr=training_args.learning_rate,
469
+ num_train_steps=num_train_steps,
470
+ num_warmup_steps=num_warmpup_steps,
471
+ adam_beta1=training_args.adam_beta1,
472
+ adam_beta2=training_args.adam_beta2,
473
+ adam_epsilon=training_args.adam_epsilon,
474
+ weight_decay_rate=training_args.weight_decay,
475
+ adam_global_clipnorm=training_args.max_grad_norm,
476
+ )
477
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
478
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
479
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
480
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
481
+ # using model.prepare_tf_dataset()
482
+ # For more info see the docs:
483
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
484
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
485
+ train_dataset = model.prepare_tf_dataset(
486
+ train_dataset,
487
+ shuffle=True,
488
+ batch_size=total_train_batch_size,
489
+ collate_fn=collate_fn,
490
+ ).with_options(dataset_options)
491
+ else:
492
+ optimizer = "sgd" # Just write anything because we won't be using it
493
+
494
+ if training_args.do_eval:
495
+ eval_dataset = model.prepare_tf_dataset(
496
+ eval_dataset,
497
+ shuffle=False,
498
+ batch_size=total_eval_batch_size,
499
+ collate_fn=collate_fn,
500
+ ).with_options(dataset_options)
501
+
502
+ if training_args.do_predict:
503
+ predict_dataset = model.prepare_tf_dataset(
504
+ predict_dataset,
505
+ shuffle=False,
506
+ batch_size=total_eval_batch_size,
507
+ collate_fn=collate_fn,
508
+ ).with_options(dataset_options)
509
+
510
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
511
+ # use this for training unless you specify your own loss function in compile().
512
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla, metrics=["accuracy"])
513
+
514
+ push_to_hub_model_id = training_args.push_to_hub_model_id
515
+ if not push_to_hub_model_id:
516
+ model_name = model_args.model_name_or_path.split("/")[-1]
517
+ push_to_hub_model_id = f"{model_name}-finetuned-image-classification"
518
+
519
+ model_card_kwargs = {
520
+ "finetuned_from": model_args.model_name_or_path,
521
+ "tasks": "image-classification",
522
+ "dataset": data_args.dataset_name,
523
+ "tags": ["image-classification", "tensorflow", "vision"],
524
+ }
525
+
526
+ callbacks = []
527
+ if eval_dataset is not None:
528
+ callbacks.append(KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=eval_dataset))
529
+ if training_args.push_to_hub:
530
+ callbacks.append(
531
+ PushToHubCallback(
532
+ output_dir=training_args.output_dir,
533
+ hub_model_id=push_to_hub_model_id,
534
+ hub_token=training_args.push_to_hub_token,
535
+ tokenizer=image_processor,
536
+ **model_card_kwargs,
537
+ )
538
+ )
539
+
540
+ if training_args.do_train:
541
+ model.fit(
542
+ train_dataset,
543
+ validation_data=eval_dataset,
544
+ epochs=int(training_args.num_train_epochs),
545
+ callbacks=callbacks,
546
+ )
547
+
548
+ if training_args.do_eval:
549
+ n_eval_batches = len(eval_dataset)
550
+ eval_predictions = model.predict(eval_dataset, steps=n_eval_batches)
551
+ eval_labels = dataset["validation"]["labels"][: n_eval_batches * total_eval_batch_size]
552
+ eval_metrics = compute_metrics((eval_predictions.logits, eval_labels))
553
+ logging.info("Eval metrics:")
554
+ for metric_name, value in eval_metrics.items():
555
+ logging.info(f"{metric_name}: {value:.3f}")
556
+
557
+ if training_args.output_dir is not None:
558
+ os.makedirs(training_args.output_dir, exist_ok=True)
559
+ with open(os.path.join(training_args.output_dir, "all_results.json"), "w") as f:
560
+ f.write(json.dumps(eval_metrics))
561
+
562
+ if training_args.do_predict:
563
+ n_predict_batches = len(predict_dataset)
564
+ test_predictions = model.predict(predict_dataset, steps=n_predict_batches)
565
+ test_labels = dataset["validation"]["labels"][: n_predict_batches * total_eval_batch_size]
566
+ test_metrics = compute_metrics((test_predictions.logits, test_labels))
567
+ logging.info("Test metrics:")
568
+ for metric_name, value in test_metrics.items():
569
+ logging.info(f"{metric_name}: {value:.3f}")
570
+
571
+ if training_args.output_dir is not None and not training_args.push_to_hub:
572
+ # If we're not pushing to hub, at least save a local copy when we're done
573
+ model.save_pretrained(training_args.output_dir)
574
+
575
+
576
+ if __name__ == "__main__":
577
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/README.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training a masked language model end-to-end from scratch on TPUs
2
+
3
+ In this example, we're going to demonstrate how to train a TensorFlow model from 🤗 Transformers from scratch. If you're interested in some background theory on training Hugging Face models with TensorFlow on TPU, please check out our
4
+ [tutorial doc](https://huggingface.co/docs/transformers/main/perf_train_tpu_tf) on this topic!
5
+ If you're interested in smaller-scale TPU training from a pre-trained checkpoint, you can also check out the [TPU fine-tuning example](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb).
6
+
7
+ This example will demonstrate pre-training language models at the 100M-1B parameter scale, similar to BERT or GPT-2. More concretely, we will show how to train a [RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta) (base model) from scratch on the [WikiText dataset (v1)](https://huggingface.co/datasets/wikitext).
8
+
9
+ We've tried to ensure that all the practices we show you here are scalable, though - with relatively few changes, the code could be scaled up to much larger models.
10
+
11
+ Google's gargantuan [PaLM model](https://arxiv.org/abs/2204.02311), with
12
+ over 500B parameters, is a good example of how far you can go with pure TPU training, though gathering the dataset and the budget to train at that scale is not an easy task!
13
+
14
+ ### Table of contents
15
+
16
+ - [Setting up a TPU-VM](#setting-up-a-tpu-vm)
17
+ - [Training a tokenizer](#training-a-tokenizer)
18
+ - [Preparing the dataset](#preparing-the-dataset)
19
+ - [Training the model](#training-the-model)
20
+ - [Inference](#inference)
21
+
22
+ ## Setting up a TPU-VM
23
+
24
+ Since this example focuses on using TPUs, the first step is to set up access to TPU hardware. For this example, we chose to use a TPU v3-8 VM. Follow [this guide](https://cloud.google.com/tpu/docs/run-calculation-tensorflow) to quickly create a TPU VM with TensorFlow pre-installed.
25
+
26
+ > 💡 **Note**: You don't need a TPU-enabled hardware for tokenizer training and TFRecord shard preparation.
27
+
28
+ ## Training a tokenizer
29
+
30
+ To train a language model from scratch, the first step is to tokenize text. In most Hugging Face examples, we begin from a pre-trained model and use its tokenizer. However, in this example, we're going to train a tokenizer from scratch as well. The script for this is `train_unigram.py`. An example command is:
31
+
32
+ ```bash
33
+ python train_unigram.py --batch_size 1000 --vocab_size 25000 --export_to_hub
34
+ ```
35
+
36
+ The script will automatically load the `train` split of the WikiText dataset and train a [Unigram tokenizer](https://huggingface.co/course/chapter6/7?fw=pt) on it.
37
+
38
+ > 💡 **Note**: In order for `export_to_hub` to work, you must authenticate yourself with the `huggingface-cli`. Run `huggingface-cli login` and follow the on-screen instructions.
39
+
40
+ ## Preparing the dataset
41
+
42
+ The next step is to prepare the dataset. This consists of loading a text dataset from the Hugging Face Hub, tokenizing it and grouping it into chunks of a fixed length ready for training. The script for this is `prepare_tfrecord_shards.py`.
43
+
44
+ The reason we create TFRecord output files from this step is that these files work well with [`tf.data` pipelines](https://www.tensorflow.org/guide/data_performance). This makes them very suitable for scalable TPU training - the dataset can easily be sharded and read in parallel just by tweaking a few parameters in the pipeline. An example command is:
45
+
46
+ ```bash
47
+ python prepare_tfrecord_shards.py \
48
+ --tokenizer_name_or_path tf-tpu/unigram-tokenizer-wikitext \
49
+ --shard_size 5000 \
50
+ --split test
51
+ --max_length 128 \
52
+ --output_dir gs://tf-tpu-training-resources
53
+ ```
54
+
55
+ **Notes**:
56
+
57
+ * While running the above script, you need to specify the `split` accordingly. The example command above will only filter the `test` split of the dataset.
58
+ * If you append `gs://` in your `output_dir` the TFRecord shards will be directly serialized to a Google Cloud Storage (GCS) bucket. Ensure that you have already [created the GCS bucket](https://cloud.google.com/storage/docs).
59
+ * If you're using a TPU node, you must stream data from a GCS bucket. Otherwise, if you're using a TPU VM,you can store the data locally. You may need to [attach](https://cloud.google.com/tpu/docs/setup-persistent-disk) a persistent storage to the VM.
60
+ * Additional CLI arguments are also supported. We encourage you to run `python prepare_tfrecord_shards.py -h` to know more about them.
61
+
62
+ ## Training the model
63
+
64
+ Once that's done, the model is ready for training. By default, training takes place on TPU, but you can use the `--no_tpu` flag to train on CPU for testing purposes. An example command is:
65
+
66
+ ```bash
67
+ python3 run_mlm.py \
68
+ --train_dataset gs://tf-tpu-training-resources/train/ \
69
+ --eval_dataset gs://tf-tpu-training-resources/validation/ \
70
+ --tokenizer tf-tpu/unigram-tokenizer-wikitext \
71
+ --output_dir trained_model
72
+ ```
73
+
74
+ If you had specified a `hub_model_id` while launching training, then your model will be pushed to a model repository on the Hugging Face Hub. You can find such an example repository here:
75
+ [tf-tpu/roberta-base-epochs-500-no-wd](https://huggingface.co/tf-tpu/roberta-base-epochs-500-no-wd).
76
+
77
+ ## Inference
78
+
79
+ Once the model is trained, you can use 🤗 Pipelines to perform inference:
80
+
81
+ ```python
82
+ from transformers import pipeline
83
+
84
+ model_id = "tf-tpu/roberta-base-epochs-500-no-wd"
85
+ unmasker = pipeline("fill-mask", model=model_id, framework="tf")
86
+ unmasker("Goal of my life is to [MASK].")
87
+
88
+ [{'score': 0.1003185287117958,
89
+ 'token': 52,
90
+ 'token_str': 'be',
91
+ 'sequence': 'Goal of my life is to be.'},
92
+ {'score': 0.032648514956235886,
93
+ 'token': 5,
94
+ 'token_str': '',
95
+ 'sequence': 'Goal of my life is to .'},
96
+ {'score': 0.02152673341333866,
97
+ 'token': 138,
98
+ 'token_str': 'work',
99
+ 'sequence': 'Goal of my life is to work.'},
100
+ {'score': 0.019547373056411743,
101
+ 'token': 984,
102
+ 'token_str': 'act',
103
+ 'sequence': 'Goal of my life is to act.'},
104
+ {'score': 0.01939118467271328,
105
+ 'token': 73,
106
+ 'token_str': 'have',
107
+ 'sequence': 'Goal of my life is to have.'}]
108
+ ```
109
+
110
+ You can also try out inference using the [Inference Widget](https://huggingface.co/tf-tpu/roberta-base-epochs-500-no-wd?text=Goal+of+my+life+is+to+%5BMASK%5D.) from the model page.
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/prepare_tfrecord_shards.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2023 The HuggingFace Inc. 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
+ """Script for preparing TFRecord shards for pre-tokenized examples."""
18
+
19
+ import argparse
20
+ import logging
21
+ import os
22
+
23
+ import datasets
24
+ import tensorflow as tf
25
+
26
+ from transformers import AutoTokenizer
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def parse_args():
33
+ parser = argparse.ArgumentParser(
34
+ description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset."
35
+ )
36
+ parser.add_argument(
37
+ "--dataset_name",
38
+ type=str,
39
+ default="wikitext",
40
+ help="Name of the training. Explore datasets at: hf.co/datasets.",
41
+ )
42
+ parser.add_argument(
43
+ "--dataset_config", type=str, default="wikitext-103-raw-v1", help="Configuration name of the dataset."
44
+ )
45
+ parser.add_argument(
46
+ "--trust_remote_code",
47
+ action="store_true",
48
+ help=(
49
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
50
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
51
+ " code, as it will execute code present on the Hub on your local machine."
52
+ ),
53
+ )
54
+ parser.add_argument(
55
+ "--tokenizer_name_or_path",
56
+ type=str,
57
+ default="sayakpaul/unigram-tokenizer-wikitext",
58
+ help="Tokenizer identifier. Can be a local filepath or a Hub identifier.",
59
+ )
60
+ parser.add_argument(
61
+ "--shard_size",
62
+ type=int,
63
+ default=1000,
64
+ help="Number of entries to go in a single shard.",
65
+ )
66
+ parser.add_argument("--split", type=str, default="train", choices=["train", "test", "validation"])
67
+ parser.add_argument(
68
+ "--limit",
69
+ default=None,
70
+ type=int,
71
+ help="Limit the number of shards (used for debugging).",
72
+ )
73
+ parser.add_argument(
74
+ "--max_length",
75
+ type=int,
76
+ default=512,
77
+ help="Maximum sequence length. For training on TPUs, it helps to have a maximum"
78
+ " sequence length that is a multiple of 8.",
79
+ )
80
+ parser.add_argument(
81
+ "--output_dir",
82
+ default="tf-tpu",
83
+ type=str,
84
+ help="Output directory where the TFRecord shards will be saved. If the"
85
+ " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord"
86
+ " shards will be directly saved to a Google Cloud Storage bucket.",
87
+ )
88
+
89
+ args = parser.parse_args()
90
+ return args
91
+
92
+
93
+ def tokenize_function(tokenizer):
94
+ def fn(examples):
95
+ return tokenizer(examples["text"])
96
+
97
+ return fn
98
+
99
+
100
+ def get_serialized_examples(tokenized_data):
101
+ records = []
102
+ for i in range(len(tokenized_data["input_ids"])):
103
+ features = {
104
+ "input_ids": tf.train.Feature(int64_list=tf.train.Int64List(value=tokenized_data["input_ids"][i])),
105
+ "attention_mask": tf.train.Feature(
106
+ int64_list=tf.train.Int64List(value=tokenized_data["attention_mask"][i])
107
+ ),
108
+ }
109
+ features = tf.train.Features(feature=features)
110
+ example = tf.train.Example(features=features)
111
+ record_bytes = example.SerializeToString()
112
+ records.append(record_bytes)
113
+ return records
114
+
115
+
116
+ def main(args):
117
+ dataset = datasets.load_dataset(
118
+ args.dataset_name, args.dataset_config, split=args.split, trust_remote_code=args.trust_remote_code
119
+ )
120
+
121
+ if args.limit is not None:
122
+ max_samples = min(len(dataset), args.limit)
123
+ dataset = dataset.select(range(max_samples))
124
+ print(f"Limiting the dataset to {args.limit} entries.")
125
+
126
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path)
127
+
128
+ # Handle output directory creation.
129
+ # For serializing into a Google Cloud Storage Bucket, one needs to first
130
+ # create a bucket.
131
+ if "gs" not in args.output_dir:
132
+ if not os.path.exists(args.output_dir):
133
+ os.makedirs(args.output_dir)
134
+ split_dir = os.path.join(args.output_dir, args.split)
135
+ if not os.path.exists(split_dir):
136
+ os.makedirs(split_dir)
137
+ else:
138
+ split_dir = os.path.join(args.output_dir, args.split)
139
+
140
+ # Tokenize the whole dataset at once.
141
+ tokenize_fn = tokenize_function(tokenizer)
142
+ dataset_tokenized = dataset.map(tokenize_fn, batched=True, num_proc=4, remove_columns=["text"])
143
+
144
+ # We need to concatenate all our texts together, and then split the result
145
+ # into chunks of a fixed size, which we will call block_size. To do this, we
146
+ # will use the map method again, with the option batched=True. When we use batched=True,
147
+ # the function we pass to map() will be passed multiple inputs at once, allowing us
148
+ # to group them into more or fewer examples than we had in the input.
149
+ # This allows us to create our new fixed-length samples. The advantage of this
150
+ # method is that we don't lose a whole lot of content from the dataset compared to the
151
+ # case where we simply tokenize with a pre-defined max_length.
152
+
153
+ def group_texts(examples):
154
+ # Concatenate all texts.
155
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
156
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
157
+ # We drop the small remainder, though you could add padding instead if the model supports it
158
+ # In this, as in all things, we advise you to follow your heart 🫀
159
+ total_length = (total_length // args.max_length) * args.max_length
160
+ # Split by chunks of max_len.
161
+ result = {
162
+ k: [t[i : i + args.max_length] for i in range(0, total_length, args.max_length)]
163
+ for k, t in concatenated_examples.items()
164
+ }
165
+ return result
166
+
167
+ grouped_dataset = dataset_tokenized.map(group_texts, batched=True, batch_size=1000, num_proc=4)
168
+
169
+ shard_count = 0
170
+ total_records = 0
171
+ for shard in range(0, len(grouped_dataset), args.shard_size):
172
+ dataset_snapshot = grouped_dataset[shard : shard + args.shard_size]
173
+ records_containing = len(dataset_snapshot["input_ids"])
174
+ filename = os.path.join(split_dir, f"dataset-{shard_count}-{records_containing}.tfrecord")
175
+ serialized_examples = get_serialized_examples(dataset_snapshot)
176
+
177
+ with tf.io.TFRecordWriter(filename) as out_file:
178
+ for i in range(len(serialized_examples)):
179
+ example = serialized_examples[i]
180
+ out_file.write(example)
181
+ print("Wrote file {} containing {} records".format(filename, records_containing))
182
+
183
+ shard_count += 1
184
+ total_records += records_containing
185
+
186
+ with open(f"split-{args.split}-records-count.txt", "w") as f:
187
+ print(f"Total {args.split} records: {total_records}", file=f)
188
+
189
+
190
+ if __name__ == "__main__":
191
+ args = parse_args()
192
+ main(args)
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ transformers==4.48.0
2
+ datasets==2.9.0
3
+ tokenizers==0.13.2
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/run_mlm.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2023 The HuggingFace Inc. 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
+ """Script for training a masked language model on TPU."""
18
+
19
+ import argparse
20
+ import logging
21
+ import os
22
+ import re
23
+
24
+ import tensorflow as tf
25
+ from packaging.version import parse
26
+
27
+ from transformers import (
28
+ AutoConfig,
29
+ AutoTokenizer,
30
+ DataCollatorForLanguageModeling,
31
+ PushToHubCallback,
32
+ TFAutoModelForMaskedLM,
33
+ create_optimizer,
34
+ )
35
+
36
+
37
+ try:
38
+ import tf_keras as keras
39
+ except (ModuleNotFoundError, ImportError):
40
+ import keras
41
+
42
+ if parse(keras.__version__).major > 2:
43
+ raise ValueError(
44
+ "Your currently installed version of Keras is Keras 3, but this is not yet supported in "
45
+ "Transformers. Please install the backwards-compatible tf-keras package with "
46
+ "`pip install tf-keras`."
47
+ )
48
+
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ AUTO = tf.data.AUTOTUNE
53
+
54
+
55
+ def parse_args():
56
+ parser = argparse.ArgumentParser(description="Train a masked language model on TPU.")
57
+ parser.add_argument(
58
+ "--pretrained_model_config",
59
+ type=str,
60
+ default="FacebookAI/roberta-base",
61
+ help="The model config to use. Note that we don't copy the model's weights, only the config!",
62
+ )
63
+ parser.add_argument(
64
+ "--tokenizer",
65
+ type=str,
66
+ default="unigram-tokenizer-wikitext",
67
+ help="The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.",
68
+ )
69
+
70
+ parser.add_argument(
71
+ "--per_replica_batch_size",
72
+ type=int,
73
+ default=8,
74
+ help="Batch size per TPU core.",
75
+ )
76
+
77
+ parser.add_argument(
78
+ "--no_tpu",
79
+ action="store_true",
80
+ help="If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.",
81
+ )
82
+
83
+ parser.add_argument(
84
+ "--tpu_name",
85
+ type=str,
86
+ help="Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.",
87
+ default="local",
88
+ )
89
+
90
+ parser.add_argument(
91
+ "--tpu_zone",
92
+ type=str,
93
+ help="Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.",
94
+ )
95
+
96
+ parser.add_argument(
97
+ "--gcp_project", type=str, help="Google cloud project name. Only used for non-Colab TPU nodes."
98
+ )
99
+
100
+ parser.add_argument(
101
+ "--bfloat16",
102
+ action="store_true",
103
+ help="Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.",
104
+ )
105
+
106
+ parser.add_argument(
107
+ "--train_dataset",
108
+ type=str,
109
+ help="Path to training dataset to load. If the path begins with `gs://`"
110
+ " then the dataset will be loaded from a Google Cloud Storage bucket.",
111
+ )
112
+
113
+ parser.add_argument(
114
+ "--shuffle_buffer_size",
115
+ type=int,
116
+ default=2**18, # Default corresponds to a 1GB buffer for seq_len 512
117
+ help="Size of the shuffle buffer (in samples)",
118
+ )
119
+
120
+ parser.add_argument(
121
+ "--eval_dataset",
122
+ type=str,
123
+ help="Path to evaluation dataset to load. If the path begins with `gs://`"
124
+ " then the dataset will be loaded from a Google Cloud Storage bucket.",
125
+ )
126
+
127
+ parser.add_argument(
128
+ "--num_epochs",
129
+ type=int,
130
+ default=1,
131
+ help="Number of epochs to train for.",
132
+ )
133
+
134
+ parser.add_argument(
135
+ "--learning_rate",
136
+ type=float,
137
+ default=1e-4,
138
+ help="Learning rate to use for training.",
139
+ )
140
+
141
+ parser.add_argument(
142
+ "--weight_decay_rate",
143
+ type=float,
144
+ default=1e-3,
145
+ help="Weight decay rate to use for training.",
146
+ )
147
+
148
+ parser.add_argument(
149
+ "--max_length",
150
+ type=int,
151
+ default=512,
152
+ help="Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py",
153
+ )
154
+
155
+ parser.add_argument(
156
+ "--mlm_probability",
157
+ type=float,
158
+ default=0.15,
159
+ help="Fraction of tokens to mask during training.",
160
+ )
161
+
162
+ parser.add_argument("--output_dir", type=str, required=True, help="Path to save model checkpoints to.")
163
+ parser.add_argument("--hub_model_id", type=str, help="Model ID to upload to on the Hugging Face Hub.")
164
+
165
+ args = parser.parse_args()
166
+ return args
167
+
168
+
169
+ def initialize_tpu(args):
170
+ try:
171
+ if args.tpu_name:
172
+ tpu = tf.distribute.cluster_resolver.TPUClusterResolver(
173
+ args.tpu_name, zone=args.tpu_zone, project=args.gcp_project
174
+ )
175
+ else:
176
+ tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
177
+ except ValueError:
178
+ raise RuntimeError(
179
+ "Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or "
180
+ "--gcp_project. When running on a TPU VM, use --tpu_name local."
181
+ )
182
+
183
+ tf.config.experimental_connect_to_cluster(tpu)
184
+ tf.tpu.experimental.initialize_tpu_system(tpu)
185
+
186
+ return tpu
187
+
188
+
189
+ def count_samples(file_list):
190
+ num_samples = 0
191
+ for file in file_list:
192
+ filename = file.split("/")[-1]
193
+ sample_count = re.search(r"-\d+-(\d+)\.tfrecord", filename).group(1)
194
+ sample_count = int(sample_count)
195
+ num_samples += sample_count
196
+
197
+ return num_samples
198
+
199
+
200
+ def prepare_dataset(records, decode_fn, mask_fn, batch_size, shuffle, shuffle_buffer_size=None):
201
+ num_samples = count_samples(records)
202
+ dataset = tf.data.Dataset.from_tensor_slices(records)
203
+ if shuffle:
204
+ dataset = dataset.shuffle(len(dataset))
205
+ dataset = tf.data.TFRecordDataset(dataset, num_parallel_reads=AUTO)
206
+ # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here
207
+ dataset = dataset.apply(tf.data.experimental.assert_cardinality(num_samples))
208
+ dataset = dataset.map(decode_fn, num_parallel_calls=AUTO)
209
+ if shuffle:
210
+ assert shuffle_buffer_size is not None
211
+ dataset = dataset.shuffle(args.shuffle_buffer_size)
212
+ dataset = dataset.batch(batch_size, drop_remainder=True)
213
+ dataset = dataset.map(mask_fn, num_parallel_calls=AUTO)
214
+ dataset = dataset.prefetch(AUTO)
215
+ return dataset
216
+
217
+
218
+ def main(args):
219
+ if not args.no_tpu:
220
+ tpu = initialize_tpu(args)
221
+ strategy = tf.distribute.TPUStrategy(tpu)
222
+ else:
223
+ strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0")
224
+
225
+ if args.bfloat16:
226
+ keras.mixed_precision.set_global_policy("mixed_bfloat16")
227
+
228
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
229
+ config = AutoConfig.from_pretrained(args.pretrained_model_config)
230
+ config.vocab_size = tokenizer.vocab_size
231
+
232
+ training_records = tf.io.gfile.glob(os.path.join(args.train_dataset, "*.tfrecord"))
233
+ if not training_records:
234
+ raise ValueError(f"No .tfrecord files found in {args.train_dataset}.")
235
+ eval_records = tf.io.gfile.glob(os.path.join(args.eval_dataset, "*.tfrecord"))
236
+ if not eval_records:
237
+ raise ValueError(f"No .tfrecord files found in {args.eval_dataset}.")
238
+
239
+ num_train_samples = count_samples(training_records)
240
+
241
+ steps_per_epoch = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync)
242
+ total_train_steps = steps_per_epoch * args.num_epochs
243
+
244
+ with strategy.scope():
245
+ model = TFAutoModelForMaskedLM.from_config(config)
246
+ model(model.dummy_inputs) # Pass some dummy inputs through the model to ensure all the weights are built
247
+ optimizer, schedule = create_optimizer(
248
+ num_train_steps=total_train_steps,
249
+ num_warmup_steps=total_train_steps // 20,
250
+ init_lr=args.learning_rate,
251
+ weight_decay_rate=args.weight_decay_rate,
252
+ )
253
+
254
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
255
+ # use this for training unless you specify your own loss function in compile().
256
+ model.compile(optimizer=optimizer, metrics=["accuracy"])
257
+
258
+ def decode_fn(example):
259
+ features = {
260
+ "input_ids": tf.io.FixedLenFeature(dtype=tf.int64, shape=(args.max_length,)),
261
+ "attention_mask": tf.io.FixedLenFeature(dtype=tf.int64, shape=(args.max_length,)),
262
+ }
263
+ return tf.io.parse_single_example(example, features)
264
+
265
+ # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can
266
+ # use their methods in our data pipeline.
267
+ data_collator = DataCollatorForLanguageModeling(
268
+ tokenizer=tokenizer, mlm_probability=args.mlm_probability, mlm=True, return_tensors="tf"
269
+ )
270
+
271
+ def mask_with_collator(batch):
272
+ # TF really needs an isin() function
273
+ special_tokens_mask = (
274
+ ~tf.cast(batch["attention_mask"], tf.bool)
275
+ | (batch["input_ids"] == tokenizer.cls_token_id)
276
+ | (batch["input_ids"] == tokenizer.sep_token_id)
277
+ )
278
+ batch["input_ids"], batch["labels"] = data_collator.tf_mask_tokens(
279
+ batch["input_ids"],
280
+ vocab_size=len(tokenizer),
281
+ mask_token_id=tokenizer.mask_token_id,
282
+ special_tokens_mask=special_tokens_mask,
283
+ )
284
+ return batch
285
+
286
+ batch_size = args.per_replica_batch_size * strategy.num_replicas_in_sync
287
+
288
+ train_dataset = prepare_dataset(
289
+ training_records,
290
+ decode_fn=decode_fn,
291
+ mask_fn=mask_with_collator,
292
+ batch_size=batch_size,
293
+ shuffle=True,
294
+ shuffle_buffer_size=args.shuffle_buffer_size,
295
+ )
296
+
297
+ eval_dataset = prepare_dataset(
298
+ eval_records,
299
+ decode_fn=decode_fn,
300
+ mask_fn=mask_with_collator,
301
+ batch_size=batch_size,
302
+ shuffle=False,
303
+ )
304
+
305
+ callbacks = []
306
+ if args.hub_model_id:
307
+ callbacks.append(
308
+ PushToHubCallback(output_dir=args.output_dir, hub_model_id=args.hub_model_id, tokenizer=tokenizer)
309
+ )
310
+
311
+ model.fit(
312
+ train_dataset,
313
+ validation_data=eval_dataset,
314
+ epochs=args.num_epochs,
315
+ callbacks=callbacks,
316
+ )
317
+
318
+ model.save_pretrained(args.output_dir)
319
+
320
+
321
+ if __name__ == "__main__":
322
+ args = parse_args()
323
+ main(args)
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling-tpu/train_unigram.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2023 The HuggingFace Inc. 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
+ """Script for training a Unigram tokenizer."""
18
+
19
+ import argparse
20
+ import logging
21
+
22
+ import datasets
23
+ from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
24
+ from tokenizers.models import Unigram
25
+ from tokenizers.trainers import UnigramTrainer
26
+
27
+ from transformers import AlbertTokenizerFast
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ def parse_args():
34
+ parser = argparse.ArgumentParser(description="Train a unigram tokenizer on the wikitext dataset.")
35
+ parser.add_argument(
36
+ "--dataset_name",
37
+ type=str,
38
+ default="wikitext",
39
+ help="Name of the training. Explore datasets at: hf.co/datasets.",
40
+ )
41
+ parser.add_argument(
42
+ "--dataset_config", type=str, default="wikitext-103-raw-v1", help="Configuration name of the dataset."
43
+ )
44
+ parser.add_argument(
45
+ "--trust_remote_code",
46
+ action="store_true",
47
+ help=(
48
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
49
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
50
+ " code, as it will execute code present on the Hub on your local machine."
51
+ ),
52
+ )
53
+ parser.add_argument(
54
+ "--batch_size",
55
+ type=int,
56
+ default=1000,
57
+ help="Batch size during training.",
58
+ )
59
+ parser.add_argument(
60
+ "--vocab_size",
61
+ type=int,
62
+ default=10048,
63
+ help="Size of the desired vocabulary.",
64
+ )
65
+ parser.add_argument(
66
+ "--limit",
67
+ default=None,
68
+ type=int,
69
+ help="Limit the number of shards (used for debugging).",
70
+ )
71
+ parser.add_argument(
72
+ "--export_to_hub",
73
+ action="store_true",
74
+ )
75
+
76
+ args = parser.parse_args()
77
+ return args
78
+
79
+
80
+ def main(args):
81
+ dataset = datasets.load_dataset(
82
+ args.dataset_name, args.dataset_config, split="train", trust_remote_code=args.trust_remote_code
83
+ )
84
+
85
+ if args.limit is not None:
86
+ max_train_samples = min(len(dataset), args.limit)
87
+ dataset = dataset.select(range(max_train_samples))
88
+ logger.info(f"Limiting the dataset to {args.limit} entries.")
89
+
90
+ def batch_iterator():
91
+ for i in range(0, len(dataset), args.batch_size):
92
+ yield dataset[i : i + args.batch_size]["text"]
93
+
94
+ # Prepare the tokenizer.
95
+ tokenizer = Tokenizer(Unigram())
96
+ tokenizer.normalizer = normalizers.Sequence([normalizers.Replace("``", '"'), normalizers.Replace("''", '"')])
97
+ tokenizer.pre_tokenizer = pre_tokenizers.Metaspace()
98
+
99
+ # Prepare the trainer.
100
+ trainer = UnigramTrainer(
101
+ unk_token="<unk>",
102
+ special_tokens=["[CLS]", "[SEP]", "<unk>", "<pad>", "[MASK]"],
103
+ vocab_size=args.vocab_size,
104
+ )
105
+
106
+ logger.info("Training the tokenizer.")
107
+ tokenizer.train_from_iterator(batch_iterator(), trainer=trainer)
108
+ logger.info("Tokenizer training complete!")
109
+
110
+ cls_token_id = tokenizer.token_to_id("[CLS]")
111
+ sep_token_id = tokenizer.token_to_id("[SEP]")
112
+ tokenizer.post_processor = processors.TemplateProcessing(
113
+ single="[CLS]:0 $A:0 [SEP]:0",
114
+ pair="[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1",
115
+ special_tokens=[
116
+ ("[CLS]", cls_token_id),
117
+ ("[SEP]", sep_token_id),
118
+ ],
119
+ )
120
+ tokenizer.decoder = decoders.Metaspace()
121
+
122
+ if args.export_to_hub:
123
+ logger.info("Exporting the trained tokenizer to Hub.")
124
+ new_tokenizer = AlbertTokenizerFast(tokenizer_object=tokenizer)
125
+ new_tokenizer.push_to_hub("unigram-tokenizer-dataset")
126
+
127
+
128
+ if __name__ == "__main__":
129
+ args = parse_args()
130
+ main(args)
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Language modelling examples
18
+
19
+ This folder contains some scripts showing examples of *language model pre-training* with the 🤗 Transformers library.
20
+ For straightforward use-cases you may be able to use these scripts without modification, although we have also
21
+ included comments in the code to indicate areas that you may need to adapt to your own projects. The two scripts
22
+ have almost identical arguments, but they differ in the type of LM they train - a causal language model (like GPT) or a
23
+ masked language model (like BERT). Masked language models generally train more quickly and perform better when
24
+ fine-tuned on new tasks with a task-specific output head, like text classification. However, their ability to generate
25
+ text is weaker than causal language models.
26
+
27
+ ## Pre-training versus fine-tuning
28
+
29
+ These scripts can be used to both *pre-train* a language model completely from scratch, as well as to *fine-tune*
30
+ a language model on text from your domain of interest. To start with an existing pre-trained language model you
31
+ can use the `--model_name_or_path` argument, or to train from scratch you can use the `--model_type` argument
32
+ to indicate the class of model architecture to initialize.
33
+
34
+ ### Multi-GPU and TPU usage
35
+
36
+ By default, these scripts use a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
37
+ can also be used by passing the name of the TPU resource with the `--tpu` argument.
38
+
39
+ ## run_mlm.py
40
+
41
+ This script trains a masked language model.
42
+
43
+ ### Example command
44
+ ```bash
45
+ python run_mlm.py \
46
+ --model_name_or_path distilbert/distilbert-base-cased \
47
+ --output_dir output \
48
+ --dataset_name wikitext \
49
+ --dataset_config_name wikitext-103-raw-v1
50
+ ```
51
+
52
+ When using a custom dataset, the validation file can be separately passed as an input argument. Otherwise some split (customizable) of training data is used as validation.
53
+ ```bash
54
+ python run_mlm.py \
55
+ --model_name_or_path distilbert/distilbert-base-cased \
56
+ --output_dir output \
57
+ --train_file train_file_path
58
+ ```
59
+
60
+ ## run_clm.py
61
+
62
+ This script trains a causal language model.
63
+
64
+ ### Example command
65
+ ```bash
66
+ python run_clm.py \
67
+ --model_name_or_path distilbert/distilgpt2 \
68
+ --output_dir output \
69
+ --dataset_name wikitext \
70
+ --dataset_config_name wikitext-103-raw-v1
71
+ ```
72
+
73
+ When using a custom dataset, the validation file can be separately passed as an input argument. Otherwise some split (customizable) of training data is used as validation.
74
+
75
+ ```bash
76
+ python run_clm.py \
77
+ --model_name_or_path distilbert/distilgpt2 \
78
+ --output_dir output \
79
+ --train_file train_file_path
80
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ datasets >= 1.8.0
2
+ sentencepiece != 0.1.92
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/run_clm.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. 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 causal language modeling (GPT-2, GPT-Neo...)
18
+ on a text file or a dataset without using HuggingFace Trainer.
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=text-generation
22
+ """
23
+ # You can also adapt this script on your own clm task. Pointers for this are left as comments.
24
+
25
+ import json
26
+
27
+ # region Imports
28
+ import logging
29
+ import math
30
+ import os
31
+ import random
32
+ import sys
33
+ from dataclasses import dataclass, field
34
+ from itertools import chain
35
+ from pathlib import Path
36
+ from typing import Optional
37
+
38
+ import datasets
39
+ import tensorflow as tf
40
+ from datasets import load_dataset
41
+ from sklearn.model_selection import train_test_split
42
+
43
+ import transformers
44
+ from transformers import (
45
+ CONFIG_MAPPING,
46
+ CONFIG_NAME,
47
+ TF2_WEIGHTS_NAME,
48
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
49
+ AutoConfig,
50
+ AutoTokenizer,
51
+ HfArgumentParser,
52
+ PushToHubCallback,
53
+ TFAutoModelForCausalLM,
54
+ TFTrainingArguments,
55
+ create_optimizer,
56
+ set_seed,
57
+ )
58
+ from transformers.utils import send_example_telemetry
59
+ from transformers.utils.versions import require_version
60
+
61
+
62
+ logger = logging.getLogger(__name__)
63
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/tensorflow/language-modeling/requirements.txt")
64
+ MODEL_CONFIG_CLASSES = list(TF_MODEL_FOR_CAUSAL_LM_MAPPING.keys())
65
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
66
+ # endregion
67
+
68
+
69
+ # region Command-line arguments
70
+ @dataclass
71
+ class ModelArguments:
72
+ """
73
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
74
+ """
75
+
76
+ model_name_or_path: Optional[str] = field(
77
+ default=None,
78
+ metadata={
79
+ "help": (
80
+ "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
81
+ )
82
+ },
83
+ )
84
+ model_type: Optional[str] = field(
85
+ default=None,
86
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
87
+ )
88
+ config_overrides: Optional[str] = field(
89
+ default=None,
90
+ metadata={
91
+ "help": (
92
+ "Override some existing default config settings when a model is trained from scratch. Example: "
93
+ "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
94
+ )
95
+ },
96
+ )
97
+ config_name: Optional[str] = field(
98
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
99
+ )
100
+ tokenizer_name: Optional[str] = field(
101
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
102
+ )
103
+ cache_dir: Optional[str] = field(
104
+ default=None,
105
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
106
+ )
107
+ use_fast_tokenizer: bool = field(
108
+ default=True,
109
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
110
+ )
111
+ model_revision: str = field(
112
+ default="main",
113
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
114
+ )
115
+ token: str = field(
116
+ default=None,
117
+ metadata={
118
+ "help": (
119
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
120
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
121
+ )
122
+ },
123
+ )
124
+ trust_remote_code: bool = field(
125
+ default=False,
126
+ metadata={
127
+ "help": (
128
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
129
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
130
+ " code, as it will execute code present on the Hub on your local machine."
131
+ )
132
+ },
133
+ )
134
+
135
+ def __post_init__(self):
136
+ if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
137
+ raise ValueError(
138
+ "--config_overrides can't be used in combination with --config_name or --model_name_or_path"
139
+ )
140
+
141
+
142
+ @dataclass
143
+ class DataTrainingArguments:
144
+ """
145
+ Arguments pertaining to what data we are going to input our model for training and eval.
146
+ """
147
+
148
+ dataset_name: Optional[str] = field(
149
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
150
+ )
151
+ dataset_config_name: Optional[str] = field(
152
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
153
+ )
154
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
155
+ validation_file: Optional[str] = field(
156
+ default=None,
157
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
158
+ )
159
+ overwrite_cache: bool = field(
160
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
161
+ )
162
+ validation_split_percentage: Optional[int] = field(
163
+ default=5,
164
+ metadata={
165
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
166
+ },
167
+ )
168
+ block_size: Optional[int] = field(
169
+ default=None,
170
+ metadata={
171
+ "help": (
172
+ "Optional input sequence length after tokenization. "
173
+ "The training dataset will be truncated in block of this size for training. "
174
+ "Default to the model max input length for single sentence inputs (take into account special tokens)."
175
+ )
176
+ },
177
+ )
178
+ preprocessing_num_workers: Optional[int] = field(
179
+ default=None,
180
+ metadata={"help": "The number of processes to use for the preprocessing."},
181
+ )
182
+ line_by_line: bool = field(
183
+ default=False,
184
+ metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
185
+ )
186
+ max_train_samples: Optional[int] = field(
187
+ default=None,
188
+ metadata={
189
+ "help": (
190
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
191
+ "value if set."
192
+ )
193
+ },
194
+ )
195
+ max_eval_samples: Optional[int] = field(
196
+ default=None,
197
+ metadata={
198
+ "help": (
199
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
200
+ "value if set."
201
+ )
202
+ },
203
+ )
204
+ keep_linebreaks: bool = field(
205
+ default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
206
+ )
207
+
208
+ def __post_init__(self):
209
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
210
+ raise ValueError("Need either a dataset name or a training/validation file.")
211
+ else:
212
+ if self.train_file is not None:
213
+ extension = self.train_file.split(".")[-1]
214
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
215
+ if self.validation_file is not None:
216
+ extension = self.validation_file.split(".")[-1]
217
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
218
+
219
+
220
+ # endregion
221
+
222
+
223
+ def main():
224
+ # region Argument Parsing
225
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
226
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
227
+ # If we pass only one argument to the script and it's the path to a json file,
228
+ # let's parse it to get our arguments.
229
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
230
+ else:
231
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
232
+
233
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
234
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
235
+ send_example_telemetry("run_clm", model_args, data_args, framework="tensorflow")
236
+
237
+ # Sanity checks
238
+ if data_args.dataset_name is None and data_args.train_file is None and data_args.validation_file is None:
239
+ raise ValueError("Need either a dataset name or a training/validation file.")
240
+ else:
241
+ if data_args.train_file is not None:
242
+ extension = data_args.train_file.split(".")[-1]
243
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
244
+ if data_args.validation_file is not None:
245
+ extension = data_args.validation_file.split(".")[-1]
246
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
247
+
248
+ if training_args.output_dir is not None:
249
+ training_args.output_dir = Path(training_args.output_dir)
250
+ os.makedirs(training_args.output_dir, exist_ok=True)
251
+ # endregion
252
+
253
+ # region Checkpoints
254
+ # Detecting last checkpoint.
255
+ checkpoint = None
256
+ if len(os.listdir(training_args.output_dir)) > 0 and not training_args.overwrite_output_dir:
257
+ config_path = training_args.output_dir / CONFIG_NAME
258
+ weights_path = training_args.output_dir / TF2_WEIGHTS_NAME
259
+ if config_path.is_file() and weights_path.is_file():
260
+ checkpoint = training_args.output_dir
261
+ logger.info(
262
+ f"Checkpoint detected, resuming training from checkpoint in {training_args.output_dir}. To avoid this"
263
+ " behavior, change the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
264
+ )
265
+ else:
266
+ raise ValueError(
267
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
268
+ "Use --overwrite_output_dir to continue regardless."
269
+ )
270
+
271
+ # endregion
272
+
273
+ # region Setup logging
274
+ # accelerator.is_local_main_process is only True for one process per machine.
275
+ logger.setLevel(logging.INFO)
276
+ datasets.utils.logging.set_verbosity_warning()
277
+ transformers.utils.logging.set_verbosity_info()
278
+ # endregion
279
+
280
+ # If passed along, set the training seed now.
281
+ if training_args.seed is not None:
282
+ set_seed(training_args.seed)
283
+
284
+ # region Load datasets
285
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
286
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
287
+ # (the dataset will be downloaded automatically from the datasets Hub).
288
+ #
289
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
290
+ # 'text' is found. You can easily tweak this behavior (see below).
291
+ #
292
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
293
+ # download the dataset.
294
+ if data_args.dataset_name is not None:
295
+ # Downloading and loading a dataset from the hub.
296
+ raw_datasets = load_dataset(
297
+ data_args.dataset_name,
298
+ data_args.dataset_config_name,
299
+ cache_dir=model_args.cache_dir,
300
+ token=model_args.token,
301
+ trust_remote_code=model_args.trust_remote_code,
302
+ )
303
+ if "validation" not in raw_datasets.keys():
304
+ raw_datasets["validation"] = load_dataset(
305
+ data_args.dataset_name,
306
+ data_args.dataset_config_name,
307
+ split=f"train[:{data_args.validation_split_percentage}%]",
308
+ cache_dir=model_args.cache_dir,
309
+ token=model_args.token,
310
+ trust_remote_code=model_args.trust_remote_code,
311
+ )
312
+ raw_datasets["train"] = load_dataset(
313
+ data_args.dataset_name,
314
+ data_args.dataset_config_name,
315
+ split=f"train[{data_args.validation_split_percentage}%:]",
316
+ cache_dir=model_args.cache_dir,
317
+ token=model_args.token,
318
+ trust_remote_code=model_args.trust_remote_code,
319
+ )
320
+ else:
321
+ data_files = {}
322
+ dataset_args = {}
323
+ if data_args.train_file is not None:
324
+ data_files["train"] = data_args.train_file
325
+ if data_args.validation_file is not None:
326
+ data_files["validation"] = data_args.validation_file
327
+ extension = (
328
+ data_args.train_file.split(".")[-1]
329
+ if data_args.train_file is not None
330
+ else data_args.validation_file.split(".")[-1]
331
+ )
332
+ if extension == "txt":
333
+ extension = "text"
334
+ dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
335
+ raw_datasets = load_dataset(
336
+ extension,
337
+ data_files=data_files,
338
+ cache_dir=model_args.cache_dir,
339
+ token=model_args.token,
340
+ **dataset_args,
341
+ )
342
+ # If no validation data is there, validation_split_percentage will be used to divide the dataset.
343
+ if "validation" not in raw_datasets.keys():
344
+ raw_datasets["validation"] = load_dataset(
345
+ extension,
346
+ data_files=data_files,
347
+ split=f"train[:{data_args.validation_split_percentage}%]",
348
+ cache_dir=model_args.cache_dir,
349
+ token=model_args.token,
350
+ **dataset_args,
351
+ )
352
+ raw_datasets["train"] = load_dataset(
353
+ extension,
354
+ data_files=data_files,
355
+ split=f"train[{data_args.validation_split_percentage}%:]",
356
+ cache_dir=model_args.cache_dir,
357
+ token=model_args.token,
358
+ **dataset_args,
359
+ )
360
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
361
+ # https://huggingface.co/docs/datasets/loading_datasets.
362
+ # endregion
363
+
364
+ # region Load pretrained model and tokenizer
365
+ #
366
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
367
+ # download model & vocab.
368
+ if model_args.config_name:
369
+ config = AutoConfig.from_pretrained(
370
+ model_args.config_name,
371
+ token=model_args.token,
372
+ trust_remote_code=model_args.trust_remote_code,
373
+ )
374
+ elif model_args.model_name_or_path:
375
+ config = AutoConfig.from_pretrained(
376
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
377
+ )
378
+ else:
379
+ config = CONFIG_MAPPING[model_args.model_type]()
380
+ logger.warning("You are instantiating a new config instance from scratch.")
381
+
382
+ if model_args.tokenizer_name:
383
+ tokenizer = AutoTokenizer.from_pretrained(
384
+ model_args.tokenizer_name, token=model_args.token, trust_remote_code=model_args.trust_remote_code
385
+ )
386
+ elif model_args.model_name_or_path:
387
+ tokenizer = AutoTokenizer.from_pretrained(
388
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
389
+ )
390
+ else:
391
+ raise ValueError(
392
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
393
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
394
+ )
395
+ # endregion
396
+
397
+ # region Dataset preprocessing
398
+ # First we tokenize all the texts.
399
+ column_names = raw_datasets["train"].column_names
400
+ text_column_name = "text" if "text" in column_names else column_names[0]
401
+
402
+ def tokenize_function(examples):
403
+ return tokenizer(examples[text_column_name])
404
+
405
+ tokenized_datasets = raw_datasets.map(
406
+ tokenize_function,
407
+ batched=True,
408
+ num_proc=data_args.preprocessing_num_workers,
409
+ remove_columns=column_names,
410
+ load_from_cache_file=not data_args.overwrite_cache,
411
+ desc="Running tokenizer on dataset",
412
+ )
413
+
414
+ if data_args.block_size is None:
415
+ block_size = tokenizer.model_max_length
416
+ if block_size > config.max_position_embeddings:
417
+ logger.warning(
418
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
419
+ f"Using block_size={min(1024, config.max_position_embeddings)} instead. You can change that default value by passing --block_size xxx."
420
+ )
421
+ block_size = min(1024, config.max_position_embeddings)
422
+ else:
423
+ if data_args.block_size > tokenizer.model_max_length:
424
+ logger.warning(
425
+ f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model "
426
+ f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
427
+ )
428
+ block_size = min(data_args.block_size, tokenizer.model_max_length)
429
+
430
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
431
+ def group_texts(examples):
432
+ # Concatenate all texts.
433
+ concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
434
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
435
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
436
+ # customize this part to your needs.
437
+ if total_length >= block_size:
438
+ total_length = (total_length // block_size) * block_size
439
+ # Split by chunks of max_len.
440
+ result = {
441
+ k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
442
+ for k, t in concatenated_examples.items()
443
+ }
444
+ result["labels"] = result["input_ids"].copy()
445
+ return result
446
+
447
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
448
+ # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
449
+ # to preprocess.
450
+ #
451
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
452
+ # https://huggingface.co/docs/datasets/process#map
453
+
454
+ lm_datasets = tokenized_datasets.map(
455
+ group_texts,
456
+ batched=True,
457
+ num_proc=data_args.preprocessing_num_workers,
458
+ load_from_cache_file=not data_args.overwrite_cache,
459
+ desc=f"Grouping texts in chunks of {block_size}",
460
+ )
461
+
462
+ train_dataset = lm_datasets["train"]
463
+ if data_args.validation_file is not None:
464
+ eval_dataset = lm_datasets["validation"]
465
+ else:
466
+ logger.info(
467
+ f"Validation file not found: using {data_args.validation_split_percentage}% of the dataset as validation"
468
+ " as provided in data_args"
469
+ )
470
+ train_indices, val_indices = train_test_split(
471
+ list(range(len(train_dataset))), test_size=data_args.validation_split_percentage / 100
472
+ )
473
+
474
+ eval_dataset = train_dataset.select(val_indices)
475
+ train_dataset = train_dataset.select(train_indices)
476
+
477
+ if data_args.max_train_samples is not None:
478
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
479
+ train_dataset = train_dataset.select(range(max_train_samples))
480
+ if data_args.max_eval_samples is not None:
481
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
482
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
483
+
484
+ # Log a few random samples from the training set:
485
+ for index in random.sample(range(len(train_dataset)), min(3, len(train_dataset))):
486
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
487
+ # endregion
488
+
489
+ with training_args.strategy.scope():
490
+ # region Prepare model
491
+ if checkpoint is not None:
492
+ model = TFAutoModelForCausalLM.from_pretrained(
493
+ checkpoint, config=config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
494
+ )
495
+ elif model_args.model_name_or_path:
496
+ model = TFAutoModelForCausalLM.from_pretrained(
497
+ model_args.model_name_or_path,
498
+ config=config,
499
+ token=model_args.token,
500
+ trust_remote_code=model_args.trust_remote_code,
501
+ )
502
+ else:
503
+ logger.info("Training new model from scratch")
504
+ model = TFAutoModelForCausalLM.from_config(
505
+ config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
506
+ )
507
+
508
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
509
+ # on a small vocab and want a smaller embedding size, remove this test.
510
+ embeddings = model.get_input_embeddings()
511
+
512
+ # Matt: This is a temporary workaround as we transition our models to exclusively using Keras embeddings.
513
+ # As soon as the transition is complete, all embeddings should be keras.Embeddings layers, and
514
+ # the weights will always be in embeddings.embeddings.
515
+ if hasattr(embeddings, "embeddings"):
516
+ embedding_size = embeddings.embeddings.shape[0]
517
+ else:
518
+ embedding_size = embeddings.weight.shape[0]
519
+ if len(tokenizer) > embedding_size:
520
+ model.resize_token_embeddings(len(tokenizer))
521
+ # endregion
522
+
523
+ # region TF Dataset preparation
524
+ num_replicas = training_args.strategy.num_replicas_in_sync
525
+ options = tf.data.Options()
526
+ options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
527
+
528
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
529
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
530
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
531
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
532
+ # using model.prepare_tf_dataset()
533
+ # For more info see the docs:
534
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
535
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
536
+
537
+ tf_train_dataset = model.prepare_tf_dataset(
538
+ train_dataset,
539
+ shuffle=True,
540
+ batch_size=num_replicas * training_args.per_device_train_batch_size,
541
+ ).with_options(options)
542
+
543
+ tf_eval_dataset = model.prepare_tf_dataset(
544
+ eval_dataset,
545
+ shuffle=False,
546
+ batch_size=num_replicas * training_args.per_device_eval_batch_size,
547
+ drop_remainder=True,
548
+ ).with_options(options)
549
+ # endregion
550
+
551
+ # region Optimizer and loss
552
+ num_train_steps = len(tf_train_dataset) * int(training_args.num_train_epochs)
553
+ if training_args.warmup_steps > 0:
554
+ num_warmup_steps = training_args.warmup_steps
555
+ elif training_args.warmup_ratio > 0:
556
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
557
+ else:
558
+ num_warmup_steps = 0
559
+
560
+ # Bias and layernorm weights are automatically excluded from the decay
561
+ optimizer, lr_schedule = create_optimizer(
562
+ init_lr=training_args.learning_rate,
563
+ num_train_steps=num_train_steps,
564
+ num_warmup_steps=num_warmup_steps,
565
+ adam_beta1=training_args.adam_beta1,
566
+ adam_beta2=training_args.adam_beta2,
567
+ adam_epsilon=training_args.adam_epsilon,
568
+ weight_decay_rate=training_args.weight_decay,
569
+ adam_global_clipnorm=training_args.max_grad_norm,
570
+ )
571
+
572
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
573
+ # use this for training unless you specify your own loss function in compile().
574
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
575
+ # endregion
576
+
577
+ # region Preparing push_to_hub and model card
578
+ push_to_hub_model_id = training_args.push_to_hub_model_id
579
+ model_name = model_args.model_name_or_path.split("/")[-1]
580
+ if not push_to_hub_model_id:
581
+ if data_args.dataset_name is not None:
582
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}"
583
+ else:
584
+ push_to_hub_model_id = f"{model_name}-finetuned-clm"
585
+
586
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
587
+ if data_args.dataset_name is not None:
588
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
589
+ if data_args.dataset_config_name is not None:
590
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
591
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
592
+ else:
593
+ model_card_kwargs["dataset"] = data_args.dataset_name
594
+
595
+ if training_args.push_to_hub:
596
+ callbacks = [
597
+ PushToHubCallback(
598
+ output_dir=training_args.output_dir,
599
+ hub_model_id=push_to_hub_model_id,
600
+ hub_token=training_args.push_to_hub_token,
601
+ tokenizer=tokenizer,
602
+ **model_card_kwargs,
603
+ )
604
+ ]
605
+ else:
606
+ callbacks = []
607
+ # endregion
608
+
609
+ # region Training and validation
610
+ logger.info("***** Running training *****")
611
+ logger.info(f" Num examples = {len(train_dataset)}")
612
+ logger.info(f" Num Epochs = {training_args.num_train_epochs}")
613
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
614
+ logger.info(f" Total train batch size = {training_args.per_device_train_batch_size * num_replicas}")
615
+
616
+ # For long training runs, you may wish to use the PushToHub() callback here to save intermediate checkpoints
617
+ # to the Hugging Face Hub rather than just pushing the finished model.
618
+ # See https://huggingface.co/docs/transformers/main_classes/keras_callbacks#transformers.PushToHubCallback
619
+
620
+ history = model.fit(
621
+ tf_train_dataset,
622
+ validation_data=tf_eval_dataset,
623
+ epochs=int(training_args.num_train_epochs),
624
+ callbacks=callbacks,
625
+ )
626
+ train_loss = history.history["loss"][-1]
627
+ try:
628
+ train_perplexity = math.exp(train_loss)
629
+ except OverflowError:
630
+ train_perplexity = math.inf
631
+ logger.info(f" Final train loss: {train_loss:.3f}")
632
+ logger.info(f" Final train perplexity: {train_perplexity:.3f}")
633
+ validation_loss = history.history["val_loss"][-1]
634
+ try:
635
+ validation_perplexity = math.exp(validation_loss)
636
+ except OverflowError:
637
+ validation_perplexity = math.inf
638
+ logger.info(f" Final validation loss: {validation_loss:.3f}")
639
+ logger.info(f" Final validation perplexity: {validation_perplexity:.3f}")
640
+
641
+ if training_args.output_dir is not None:
642
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
643
+ results_dict = {}
644
+ results_dict["train_loss"] = train_loss
645
+ results_dict["train_perplexity"] = train_perplexity
646
+ results_dict["eval_loss"] = validation_loss
647
+ results_dict["eval_perplexity"] = validation_perplexity
648
+ with open(output_eval_file, "w") as writer:
649
+ writer.write(json.dumps(results_dict))
650
+ # endregion
651
+
652
+ if training_args.output_dir is not None and not training_args.push_to_hub:
653
+ # If we're not pushing to hub, at least save a local copy when we're done
654
+ model.save_pretrained(training_args.output_dir)
655
+
656
+
657
+ if __name__ == "__main__":
658
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/language-modeling/run_mlm.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. 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...)
18
+ on a text file or a dataset without using HuggingFace Trainer.
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
+ # You can also adapt this script on your own mlm task. Pointers for this are left as comments.
24
+
25
+ import json
26
+ import logging
27
+ import math
28
+ import os
29
+ import random
30
+ import sys
31
+ from dataclasses import dataclass, field
32
+ from itertools import chain
33
+ from pathlib import Path
34
+ from typing import Optional
35
+
36
+ import datasets
37
+ import tensorflow as tf
38
+ from datasets import load_dataset
39
+ from sklearn.model_selection import train_test_split
40
+
41
+ import transformers
42
+ from transformers import (
43
+ CONFIG_MAPPING,
44
+ CONFIG_NAME,
45
+ TF2_WEIGHTS_NAME,
46
+ TF_MODEL_FOR_MASKED_LM_MAPPING,
47
+ AutoConfig,
48
+ AutoTokenizer,
49
+ DataCollatorForLanguageModeling,
50
+ HfArgumentParser,
51
+ PushToHubCallback,
52
+ TFAutoModelForMaskedLM,
53
+ TFTrainingArguments,
54
+ create_optimizer,
55
+ set_seed,
56
+ )
57
+ from transformers.utils import send_example_telemetry
58
+ from transformers.utils.versions import require_version
59
+
60
+
61
+ logger = logging.getLogger(__name__)
62
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/tensorflow/language-modeling/requirements.txt")
63
+ MODEL_CONFIG_CLASSES = list(TF_MODEL_FOR_MASKED_LM_MAPPING.keys())
64
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
65
+
66
+
67
+ # region Command-line arguments
68
+ @dataclass
69
+ class ModelArguments:
70
+ """
71
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
72
+ """
73
+
74
+ model_name_or_path: Optional[str] = field(
75
+ default=None,
76
+ metadata={
77
+ "help": (
78
+ "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
79
+ )
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_overrides: Optional[str] = field(
87
+ default=None,
88
+ metadata={
89
+ "help": (
90
+ "Override some existing default config settings when a model is trained from scratch. Example: "
91
+ "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
92
+ )
93
+ },
94
+ )
95
+ config_name: Optional[str] = field(
96
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
97
+ )
98
+ tokenizer_name: Optional[str] = field(
99
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
100
+ )
101
+ cache_dir: Optional[str] = field(
102
+ default=None,
103
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
104
+ )
105
+ use_fast_tokenizer: bool = field(
106
+ default=True,
107
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
108
+ )
109
+ model_revision: str = field(
110
+ default="main",
111
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
112
+ )
113
+ token: str = field(
114
+ default=None,
115
+ metadata={
116
+ "help": (
117
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
118
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
119
+ )
120
+ },
121
+ )
122
+ trust_remote_code: bool = field(
123
+ default=False,
124
+ metadata={
125
+ "help": (
126
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
127
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
128
+ " code, as it will execute code present on the Hub on your local machine."
129
+ )
130
+ },
131
+ )
132
+
133
+ def __post_init__(self):
134
+ if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
135
+ raise ValueError(
136
+ "--config_overrides can't be used in combination with --config_name or --model_name_or_path"
137
+ )
138
+
139
+
140
+ @dataclass
141
+ class DataTrainingArguments:
142
+ """
143
+ Arguments pertaining to what data we are going to input our model for training and eval.
144
+ """
145
+
146
+ dataset_name: Optional[str] = field(
147
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
148
+ )
149
+ dataset_config_name: Optional[str] = field(
150
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
151
+ )
152
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
153
+ validation_file: Optional[str] = field(
154
+ default=None,
155
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
156
+ )
157
+ overwrite_cache: bool = field(
158
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
159
+ )
160
+ validation_split_percentage: Optional[int] = field(
161
+ default=5,
162
+ metadata={
163
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
164
+ },
165
+ )
166
+ max_seq_length: Optional[int] = field(
167
+ default=None,
168
+ metadata={
169
+ "help": (
170
+ "The maximum total input sequence length after tokenization. Sequences longer "
171
+ "than this will be truncated."
172
+ )
173
+ },
174
+ )
175
+ preprocessing_num_workers: Optional[int] = field(
176
+ default=None,
177
+ metadata={"help": "The number of processes to use for the preprocessing."},
178
+ )
179
+ mlm_probability: float = field(
180
+ default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
181
+ )
182
+ line_by_line: bool = field(
183
+ default=False,
184
+ metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
185
+ )
186
+ pad_to_max_length: bool = field(
187
+ default=False,
188
+ metadata={
189
+ "help": (
190
+ "Whether to pad all samples to `max_seq_length`. "
191
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
192
+ )
193
+ },
194
+ )
195
+ max_train_samples: Optional[int] = field(
196
+ default=None,
197
+ metadata={
198
+ "help": (
199
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
200
+ "value if set."
201
+ )
202
+ },
203
+ )
204
+ max_eval_samples: Optional[int] = field(
205
+ default=None,
206
+ metadata={
207
+ "help": (
208
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
209
+ "value if set."
210
+ )
211
+ },
212
+ )
213
+
214
+ def __post_init__(self):
215
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
216
+ raise ValueError("Need either a dataset name or a training/validation file.")
217
+ else:
218
+ if self.train_file is not None:
219
+ extension = self.train_file.split(".")[-1]
220
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
221
+ if self.validation_file is not None:
222
+ extension = self.validation_file.split(".")[-1]
223
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
224
+
225
+
226
+ # endregion
227
+
228
+
229
+ def main():
230
+ # region Argument Parsing
231
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
232
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
233
+ # If we pass only one argument to the script and it's the path to a json file,
234
+ # let's parse it to get our arguments.
235
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
236
+ else:
237
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
238
+
239
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
240
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
241
+ send_example_telemetry("run_mlm", model_args, data_args, framework="tensorflow")
242
+
243
+ # Sanity checks
244
+ if data_args.dataset_name is None and data_args.train_file is None and data_args.validation_file is None:
245
+ raise ValueError("Need either a dataset name or a training/validation file.")
246
+ else:
247
+ if data_args.train_file is not None:
248
+ extension = data_args.train_file.split(".")[-1]
249
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
250
+ if data_args.validation_file is not None:
251
+ extension = data_args.validation_file.split(".")[-1]
252
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
253
+
254
+ if training_args.output_dir is not None:
255
+ training_args.output_dir = Path(training_args.output_dir)
256
+ os.makedirs(training_args.output_dir, exist_ok=True)
257
+
258
+ if isinstance(training_args.strategy, tf.distribute.TPUStrategy) and not data_args.pad_to_max_length:
259
+ logger.warning("We are training on TPU - forcing pad_to_max_length")
260
+ data_args.pad_to_max_length = True
261
+ # endregion
262
+
263
+ # region Checkpoints
264
+ # Detecting last checkpoint.
265
+ checkpoint = None
266
+ if len(os.listdir(training_args.output_dir)) > 0 and not training_args.overwrite_output_dir:
267
+ config_path = training_args.output_dir / CONFIG_NAME
268
+ weights_path = training_args.output_dir / TF2_WEIGHTS_NAME
269
+ if config_path.is_file() and weights_path.is_file():
270
+ checkpoint = training_args.output_dir
271
+ logger.warning(
272
+ f"Checkpoint detected, resuming training from checkpoint in {training_args.output_dir}. To avoid this"
273
+ " behavior, change the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
274
+ )
275
+ else:
276
+ raise ValueError(
277
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
278
+ "Use --overwrite_output_dir to continue regardless."
279
+ )
280
+
281
+ # endregion
282
+
283
+ # region Setup logging
284
+ # accelerator.is_local_main_process is only True for one process per machine.
285
+ logger.setLevel(logging.INFO)
286
+ datasets.utils.logging.set_verbosity_warning()
287
+ transformers.utils.logging.set_verbosity_info()
288
+ # endregion
289
+
290
+ # If passed along, set the training seed now.
291
+ if training_args.seed is not None:
292
+ set_seed(training_args.seed)
293
+
294
+ # region Load datasets
295
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
296
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
297
+ # (the dataset will be downloaded automatically from the datasets Hub).
298
+ #
299
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
300
+ # 'text' is found. You can easily tweak this behavior (see below).
301
+ #
302
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
303
+ # download the dataset.
304
+ if data_args.dataset_name is not None:
305
+ # Downloading and loading a dataset from the hub.
306
+ raw_datasets = load_dataset(
307
+ data_args.dataset_name,
308
+ data_args.dataset_config_name,
309
+ token=model_args.token,
310
+ trust_remote_code=model_args.trust_remote_code,
311
+ )
312
+ if "validation" not in raw_datasets.keys():
313
+ raw_datasets["validation"] = load_dataset(
314
+ data_args.dataset_name,
315
+ data_args.dataset_config_name,
316
+ split=f"train[:{data_args.validation_split_percentage}%]",
317
+ token=model_args.token,
318
+ trust_remote_code=model_args.trust_remote_code,
319
+ )
320
+ raw_datasets["train"] = load_dataset(
321
+ data_args.dataset_name,
322
+ data_args.dataset_config_name,
323
+ split=f"train[{data_args.validation_split_percentage}%:]",
324
+ token=model_args.token,
325
+ trust_remote_code=model_args.trust_remote_code,
326
+ )
327
+ else:
328
+ data_files = {}
329
+ if data_args.train_file is not None:
330
+ data_files["train"] = data_args.train_file
331
+ extension = data_args.train_file.split(".")[-1]
332
+ if data_args.validation_file is not None:
333
+ data_files["validation"] = data_args.validation_file
334
+ extension = data_args.validation_file.split(".")[-1]
335
+ if extension == "txt":
336
+ extension = "text"
337
+ raw_datasets = load_dataset(
338
+ extension,
339
+ data_files=data_files,
340
+ token=model_args.token,
341
+ )
342
+
343
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
344
+ # https://huggingface.co/docs/datasets/loading_datasets.
345
+ # endregion
346
+
347
+ # region Load pretrained model and tokenizer
348
+ #
349
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
350
+ # download model & vocab.
351
+ if checkpoint is not None:
352
+ config = AutoConfig.from_pretrained(
353
+ checkpoint, token=model_args.token, trust_remote_code=model_args.trust_remote_code
354
+ )
355
+ elif model_args.config_name:
356
+ config = AutoConfig.from_pretrained(
357
+ model_args.config_name, token=model_args.token, trust_remote_code=model_args.trust_remote_code
358
+ )
359
+ elif model_args.model_name_or_path:
360
+ config = AutoConfig.from_pretrained(
361
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
362
+ )
363
+ else:
364
+ config = CONFIG_MAPPING[model_args.model_type]()
365
+ logger.warning("You are instantiating a new config instance from scratch.")
366
+
367
+ if model_args.tokenizer_name:
368
+ tokenizer = AutoTokenizer.from_pretrained(
369
+ model_args.tokenizer_name, token=model_args.token, trust_remote_code=model_args.trust_remote_code
370
+ )
371
+ elif model_args.model_name_or_path:
372
+ tokenizer = AutoTokenizer.from_pretrained(
373
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
374
+ )
375
+ else:
376
+ raise ValueError(
377
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
378
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
379
+ )
380
+ # endregion
381
+
382
+ # region Dataset preprocessing
383
+ # First we tokenize all the texts.
384
+ column_names = raw_datasets["train"].column_names
385
+ text_column_name = "text" if "text" in column_names else column_names[0]
386
+
387
+ if data_args.max_seq_length is None:
388
+ max_seq_length = tokenizer.model_max_length
389
+ if max_seq_length > 1024:
390
+ logger.warning(
391
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
392
+ "Picking 1024 instead. You can reduce that default value by passing --max_seq_length xxx."
393
+ )
394
+ max_seq_length = 1024
395
+ else:
396
+ if data_args.max_seq_length > tokenizer.model_max_length:
397
+ logger.warning(
398
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the "
399
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
400
+ )
401
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
402
+
403
+ if data_args.line_by_line:
404
+ # When using line_by_line, we just tokenize each nonempty line.
405
+ padding = "max_length" if data_args.pad_to_max_length else False
406
+
407
+ def tokenize_function(examples):
408
+ # Remove empty lines
409
+ examples[text_column_name] = [
410
+ line for line in examples[text_column_name] if len(line) > 0 and not line.isspace()
411
+ ]
412
+ return tokenizer(
413
+ examples[text_column_name],
414
+ padding=padding,
415
+ truncation=True,
416
+ max_length=max_seq_length,
417
+ # We use this option because DataCollatorForLanguageModeling (see below) is more efficient when it
418
+ # receives the `special_tokens_mask`.
419
+ return_special_tokens_mask=True,
420
+ )
421
+
422
+ tokenized_datasets = raw_datasets.map(
423
+ tokenize_function,
424
+ batched=True,
425
+ num_proc=data_args.preprocessing_num_workers,
426
+ remove_columns=[text_column_name],
427
+ load_from_cache_file=not data_args.overwrite_cache,
428
+ desc="Running tokenizer on dataset line_by_line",
429
+ )
430
+ else:
431
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
432
+ # We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
433
+ # efficient when it receives the `special_tokens_mask`.
434
+ def tokenize_function(examples):
435
+ return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
436
+
437
+ tokenized_datasets = raw_datasets.map(
438
+ tokenize_function,
439
+ batched=True,
440
+ num_proc=data_args.preprocessing_num_workers,
441
+ remove_columns=column_names,
442
+ load_from_cache_file=not data_args.overwrite_cache,
443
+ desc="Running tokenizer on every text in dataset",
444
+ )
445
+
446
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of
447
+ # max_seq_length.
448
+ def group_texts(examples):
449
+ # Concatenate all texts.
450
+ concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
451
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
452
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
453
+ # customize this part to your needs.
454
+ if total_length >= max_seq_length:
455
+ total_length = (total_length // max_seq_length) * max_seq_length
456
+ # Split by chunks of max_len.
457
+ result = {
458
+ k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
459
+ for k, t in concatenated_examples.items()
460
+ }
461
+ return result
462
+
463
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
464
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
465
+ # might be slower to preprocess.
466
+ #
467
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
468
+ # https://huggingface.co/docs/datasets/process#map
469
+
470
+ tokenized_datasets = tokenized_datasets.map(
471
+ group_texts,
472
+ batched=True,
473
+ num_proc=data_args.preprocessing_num_workers,
474
+ load_from_cache_file=not data_args.overwrite_cache,
475
+ desc=f"Grouping texts in chunks of {max_seq_length}",
476
+ )
477
+
478
+ train_dataset = tokenized_datasets["train"]
479
+
480
+ if data_args.validation_file is not None:
481
+ eval_dataset = tokenized_datasets["validation"]
482
+ else:
483
+ logger.info(
484
+ f"Validation file not found: using {data_args.validation_split_percentage}% of the dataset as validation"
485
+ " as provided in data_args"
486
+ )
487
+ train_indices, val_indices = train_test_split(
488
+ list(range(len(train_dataset))), test_size=data_args.validation_split_percentage / 100
489
+ )
490
+
491
+ eval_dataset = train_dataset.select(val_indices)
492
+ train_dataset = train_dataset.select(train_indices)
493
+
494
+ if data_args.max_train_samples is not None:
495
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
496
+ train_dataset = train_dataset.select(range(max_train_samples))
497
+ if data_args.max_eval_samples is not None:
498
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
499
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
500
+
501
+ # Log a few random samples from the training set:
502
+ for index in random.sample(range(len(train_dataset)), min(3, len(train_dataset))):
503
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
504
+ # endregion
505
+
506
+ with training_args.strategy.scope():
507
+ # region Prepare model
508
+ if checkpoint is not None:
509
+ model = TFAutoModelForMaskedLM.from_pretrained(
510
+ checkpoint, config=config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
511
+ )
512
+ elif model_args.model_name_or_path:
513
+ model = TFAutoModelForMaskedLM.from_pretrained(
514
+ model_args.model_name_or_path,
515
+ config=config,
516
+ token=model_args.token,
517
+ trust_remote_code=model_args.trust_remote_code,
518
+ )
519
+ else:
520
+ logger.info("Training new model from scratch")
521
+ model = TFAutoModelForMaskedLM.from_config(
522
+ config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
523
+ )
524
+
525
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
526
+ # on a small vocab and want a smaller embedding size, remove this test.
527
+ embeddings = model.get_input_embeddings()
528
+
529
+ # Matt: This is a temporary workaround as we transition our models to exclusively using Keras embeddings.
530
+ # As soon as the transition is complete, all embeddings should be keras.Embeddings layers, and
531
+ # the weights will always be in embeddings.embeddings.
532
+ if hasattr(embeddings, "embeddings"):
533
+ embedding_size = embeddings.embeddings.shape[0]
534
+ else:
535
+ embedding_size = embeddings.weight.shape[0]
536
+ if len(tokenizer) > embedding_size:
537
+ model.resize_token_embeddings(len(tokenizer))
538
+ # endregion
539
+
540
+ # region TF Dataset preparation
541
+ num_replicas = training_args.strategy.num_replicas_in_sync
542
+ data_collator = DataCollatorForLanguageModeling(
543
+ tokenizer=tokenizer, mlm_probability=data_args.mlm_probability, return_tensors="np"
544
+ )
545
+ options = tf.data.Options()
546
+ options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
547
+
548
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
549
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
550
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
551
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
552
+ # using model.prepare_tf_dataset()
553
+ # For more info see the docs:
554
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
555
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
556
+
557
+ tf_train_dataset = model.prepare_tf_dataset(
558
+ train_dataset,
559
+ shuffle=True,
560
+ batch_size=num_replicas * training_args.per_device_train_batch_size,
561
+ collate_fn=data_collator,
562
+ ).with_options(options)
563
+
564
+ tf_eval_dataset = model.prepare_tf_dataset(
565
+ eval_dataset,
566
+ # labels are passed as input, as we will use the model's internal loss
567
+ shuffle=False,
568
+ batch_size=num_replicas * training_args.per_device_eval_batch_size,
569
+ collate_fn=data_collator,
570
+ drop_remainder=True,
571
+ ).with_options(options)
572
+ # endregion
573
+
574
+ # region Optimizer and loss
575
+ num_train_steps = len(tf_train_dataset) * int(training_args.num_train_epochs)
576
+ if training_args.warmup_steps > 0:
577
+ num_warmup_steps = training_args.warmup_steps
578
+ elif training_args.warmup_ratio > 0:
579
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
580
+ else:
581
+ num_warmup_steps = 0
582
+
583
+ # Bias and layernorm weights are automatically excluded from the decay
584
+ optimizer, lr_schedule = create_optimizer(
585
+ init_lr=training_args.learning_rate,
586
+ num_train_steps=num_train_steps,
587
+ num_warmup_steps=num_warmup_steps,
588
+ adam_beta1=training_args.adam_beta1,
589
+ adam_beta2=training_args.adam_beta2,
590
+ adam_epsilon=training_args.adam_epsilon,
591
+ weight_decay_rate=training_args.weight_decay,
592
+ adam_global_clipnorm=training_args.max_grad_norm,
593
+ )
594
+
595
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
596
+ # use this for training unless you specify your own loss function in compile().
597
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
598
+ # endregion
599
+
600
+ # region Preparing push_to_hub and model card
601
+ push_to_hub_model_id = training_args.push_to_hub_model_id
602
+ model_name = model_args.model_name_or_path.split("/")[-1]
603
+ if not push_to_hub_model_id:
604
+ if data_args.dataset_name is not None:
605
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}"
606
+ else:
607
+ push_to_hub_model_id = f"{model_name}-finetuned-mlm"
608
+
609
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "fill-mask"}
610
+ if data_args.dataset_name is not None:
611
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
612
+ if data_args.dataset_config_name is not None:
613
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
614
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
615
+ else:
616
+ model_card_kwargs["dataset"] = data_args.dataset_name
617
+
618
+ if training_args.push_to_hub:
619
+ callbacks = [
620
+ PushToHubCallback(
621
+ output_dir=training_args.output_dir,
622
+ hub_model_id=push_to_hub_model_id,
623
+ hub_token=training_args.push_to_hub_token,
624
+ tokenizer=tokenizer,
625
+ **model_card_kwargs,
626
+ )
627
+ ]
628
+ else:
629
+ callbacks = []
630
+ # endregion
631
+
632
+ # region Training and validation
633
+ logger.info("***** Running training *****")
634
+ logger.info(f" Num examples = {len(train_dataset)}")
635
+ logger.info(f" Num Epochs = {training_args.num_train_epochs}")
636
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
637
+ logger.info(f" Total train batch size = {training_args.per_device_train_batch_size * num_replicas}")
638
+
639
+ # For long training runs, you may wish to use the PushToHub() callback here to save intermediate checkpoints
640
+ # to the Hugging Face Hub rather than just pushing the finished model.
641
+ # See https://huggingface.co/docs/transformers/main_classes/keras_callbacks#transformers.PushToHubCallback
642
+
643
+ history = model.fit(
644
+ tf_train_dataset,
645
+ validation_data=tf_eval_dataset,
646
+ epochs=int(training_args.num_train_epochs),
647
+ callbacks=callbacks,
648
+ )
649
+ train_loss = history.history["loss"][-1]
650
+ try:
651
+ train_perplexity = math.exp(train_loss)
652
+ except OverflowError:
653
+ train_perplexity = math.inf
654
+ logger.info(f" Final train loss: {train_loss:.3f}")
655
+ logger.info(f" Final train perplexity: {train_perplexity:.3f}")
656
+
657
+ validation_loss = history.history["val_loss"][-1]
658
+ try:
659
+ validation_perplexity = math.exp(validation_loss)
660
+ except OverflowError:
661
+ validation_perplexity = math.inf
662
+ logger.info(f" Final validation loss: {validation_loss:.3f}")
663
+ logger.info(f" Final validation perplexity: {validation_perplexity:.3f}")
664
+
665
+ if training_args.output_dir is not None:
666
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
667
+ results_dict = {}
668
+ results_dict["train_loss"] = train_loss
669
+ results_dict["train_perplexity"] = train_perplexity
670
+ results_dict["eval_loss"] = validation_loss
671
+ results_dict["eval_perplexity"] = validation_perplexity
672
+ with open(output_eval_file, "w") as writer:
673
+ writer.write(json.dumps(results_dict))
674
+ # endregion
675
+
676
+ if training_args.output_dir is not None and not training_args.push_to_hub:
677
+ # If we're not pushing to hub, at least save a local copy when we're done
678
+ model.save_pretrained(training_args.output_dir)
679
+
680
+
681
+ if __name__ == "__main__":
682
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/multiple-choice/README.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+ # Multiple-choice training (e.g. SWAG)
17
+
18
+ This folder contains the `run_swag.py` script, showing an examples of *multiple-choice answering* with the
19
+ 🤗 Transformers library. For straightforward use-cases you may be able to use these scripts without modification,
20
+ although we have also included comments in the code to indicate areas that you may need to adapt to your own projects.
21
+
22
+ ### Multi-GPU and TPU usage
23
+
24
+ By default, the script uses a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
25
+ can also be used by passing the name of the TPU resource with the `--tpu` argument.
26
+
27
+ ### Memory usage and data loading
28
+
29
+ One thing to note is that all data is loaded into memory in this script. Most multiple-choice datasets are small
30
+ enough that this is not an issue, but if you have a very large dataset you will need to modify the script to handle
31
+ data streaming. This is particularly challenging for TPUs, given the stricter requirements and the sheer volume of data
32
+ required to keep them fed. A full explanation of all the possible pitfalls is a bit beyond this example script and
33
+ README, but for more information you can see the 'Input Datasets' section of
34
+ [this document](https://www.tensorflow.org/guide/tpu).
35
+
36
+ ### Example command
37
+ ```bash
38
+ python run_swag.py \
39
+ --model_name_or_path distilbert/distilbert-base-cased \
40
+ --output_dir output \
41
+ --do_eval \
42
+ --do_train
43
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/multiple-choice/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ sentencepiece != 0.1.92
2
+ protobuf
3
+ tensorflow >= 2.3
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/multiple-choice/run_swag.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright The HuggingFace Team and The HuggingFace Inc. 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 multiple choice.
18
+ """
19
+ # You can also adapt this script on your own multiple choice task. Pointers for this are left as comments.
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from itertools import chain
27
+ from pathlib import Path
28
+ from typing import Optional
29
+
30
+ import datasets
31
+ import tensorflow as tf
32
+ from datasets import load_dataset
33
+
34
+ import transformers
35
+ from transformers import (
36
+ CONFIG_NAME,
37
+ TF2_WEIGHTS_NAME,
38
+ AutoConfig,
39
+ AutoTokenizer,
40
+ DataCollatorForMultipleChoice,
41
+ DefaultDataCollator,
42
+ HfArgumentParser,
43
+ PushToHubCallback,
44
+ TFAutoModelForMultipleChoice,
45
+ TFTrainingArguments,
46
+ create_optimizer,
47
+ set_seed,
48
+ )
49
+ from transformers.utils import check_min_version, send_example_telemetry
50
+
51
+
52
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
53
+ check_min_version("4.50.0.dev0")
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+
58
+ # region Arguments
59
+ @dataclass
60
+ class ModelArguments:
61
+ """
62
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
63
+ """
64
+
65
+ model_name_or_path: str = field(
66
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
67
+ )
68
+ config_name: Optional[str] = field(
69
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
70
+ )
71
+ tokenizer_name: Optional[str] = field(
72
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
73
+ )
74
+ cache_dir: Optional[str] = field(
75
+ default=None,
76
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
77
+ )
78
+ use_fast_tokenizer: bool = field(
79
+ default=True,
80
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
81
+ )
82
+ model_revision: str = field(
83
+ default="main",
84
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
85
+ )
86
+ token: str = field(
87
+ default=None,
88
+ metadata={
89
+ "help": (
90
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
91
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
92
+ )
93
+ },
94
+ )
95
+ trust_remote_code: bool = field(
96
+ default=False,
97
+ metadata={
98
+ "help": (
99
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option "
100
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will "
101
+ "execute code present on the Hub on your local machine."
102
+ )
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
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
114
+ validation_file: Optional[str] = field(
115
+ default=None,
116
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
117
+ )
118
+ overwrite_cache: bool = field(
119
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
120
+ )
121
+ preprocessing_num_workers: Optional[int] = field(
122
+ default=None,
123
+ metadata={"help": "The number of processes to use for the preprocessing."},
124
+ )
125
+ max_seq_length: Optional[int] = field(
126
+ default=None,
127
+ metadata={
128
+ "help": (
129
+ "The maximum total input sequence length after tokenization. If passed, sequences longer "
130
+ "than this will be truncated, sequences shorter will be padded."
131
+ )
132
+ },
133
+ )
134
+ pad_to_max_length: bool = field(
135
+ default=False,
136
+ metadata={
137
+ "help": (
138
+ "Whether to pad all samples to the maximum sentence length. "
139
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
140
+ "efficient on GPU but very bad for TPU."
141
+ )
142
+ },
143
+ )
144
+ max_train_samples: Optional[int] = field(
145
+ default=None,
146
+ metadata={
147
+ "help": (
148
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
149
+ "value if set."
150
+ )
151
+ },
152
+ )
153
+ max_eval_samples: Optional[int] = field(
154
+ default=None,
155
+ metadata={
156
+ "help": (
157
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
158
+ "value if set."
159
+ )
160
+ },
161
+ )
162
+
163
+ def __post_init__(self):
164
+ if self.train_file is not None:
165
+ extension = self.train_file.split(".")[-1]
166
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
167
+ if self.validation_file is not None:
168
+ extension = self.validation_file.split(".")[-1]
169
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
170
+
171
+
172
+ # endregion
173
+
174
+
175
+ def main():
176
+ # region Argument parsing
177
+ # See all possible arguments in src/transformers/training_args.py
178
+ # or by passing the --help flag to this script.
179
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
180
+
181
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
182
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
183
+ # If we pass only one argument to the script and it's the path to a json file,
184
+ # let's parse it to get our arguments.
185
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
186
+ else:
187
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
188
+
189
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
190
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
191
+ send_example_telemetry("run_swag", model_args, data_args, framework="tensorflow")
192
+
193
+ output_dir = Path(training_args.output_dir)
194
+ output_dir.mkdir(parents=True, exist_ok=True)
195
+ # endregion
196
+
197
+ # region Logging
198
+ logging.basicConfig(
199
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
200
+ datefmt="%m/%d/%Y %H:%M:%S",
201
+ handlers=[logging.StreamHandler(sys.stdout)],
202
+ )
203
+ log_level = training_args.get_process_log_level()
204
+ logger.setLevel(log_level)
205
+ datasets.utils.logging.set_verbosity(log_level)
206
+ transformers.utils.logging.set_verbosity(log_level)
207
+ transformers.utils.logging.enable_default_handler()
208
+ transformers.utils.logging.enable_explicit_format()
209
+ # endregion
210
+
211
+ # region Checkpoints
212
+ checkpoint = None
213
+ if len(os.listdir(training_args.output_dir)) > 0 and not training_args.overwrite_output_dir:
214
+ if (output_dir / CONFIG_NAME).is_file() and (output_dir / TF2_WEIGHTS_NAME).is_file():
215
+ checkpoint = output_dir
216
+ logger.info(
217
+ f"Checkpoint detected, resuming training from checkpoint in {training_args.output_dir}. To avoid this"
218
+ " behavior, change the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
219
+ )
220
+ else:
221
+ raise ValueError(
222
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
223
+ "Use --overwrite_output_dir to continue regardless."
224
+ )
225
+ # endregion
226
+
227
+ # Set seed before initializing model.
228
+ set_seed(training_args.seed)
229
+
230
+ # region Load datasets
231
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
232
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
233
+ # (the dataset will be downloaded automatically from the datasets Hub).
234
+
235
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
236
+ # 'text' is found. You can easily tweak this behavior (see below).
237
+
238
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
239
+ # download the dataset.
240
+ if data_args.train_file is not None or data_args.validation_file is not None:
241
+ data_files = {}
242
+ if data_args.train_file is not None:
243
+ data_files["train"] = data_args.train_file
244
+ extension = data_args.train_file.split(".")[-1]
245
+ if data_args.validation_file is not None:
246
+ data_files["validation"] = data_args.validation_file
247
+ extension = data_args.validation_file.split(".")[-1]
248
+ raw_datasets = load_dataset(
249
+ extension,
250
+ data_files=data_files,
251
+ cache_dir=model_args.cache_dir,
252
+ token=model_args.token,
253
+ )
254
+ else:
255
+ # Downloading and loading the swag dataset from the hub.
256
+ raw_datasets = load_dataset(
257
+ "swag",
258
+ "regular",
259
+ cache_dir=model_args.cache_dir,
260
+ token=model_args.token,
261
+ )
262
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
263
+ # https://huggingface.co/docs/datasets/loading_datasets.
264
+
265
+ # When using your own dataset or a different dataset from swag, you will probably need to change this.
266
+ ending_names = [f"ending{i}" for i in range(4)]
267
+ context_name = "sent1"
268
+ question_header_name = "sent2"
269
+ # endregion
270
+
271
+ # region Load model config and tokenizer
272
+ if checkpoint is not None:
273
+ config_path = training_args.output_dir
274
+ elif model_args.config_name:
275
+ config_path = model_args.config_name
276
+ else:
277
+ config_path = model_args.model_name_or_path
278
+
279
+ # Distributed training:
280
+ # The .from_pretrained methods guarantee that only one local process can concurrently
281
+ # download model & vocab.
282
+ config = AutoConfig.from_pretrained(
283
+ config_path,
284
+ cache_dir=model_args.cache_dir,
285
+ revision=model_args.model_revision,
286
+ token=model_args.token,
287
+ trust_remote_code=model_args.trust_remote_code,
288
+ )
289
+ tokenizer = AutoTokenizer.from_pretrained(
290
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
291
+ cache_dir=model_args.cache_dir,
292
+ use_fast=model_args.use_fast_tokenizer,
293
+ revision=model_args.model_revision,
294
+ token=model_args.token,
295
+ trust_remote_code=model_args.trust_remote_code,
296
+ )
297
+ # endregion
298
+
299
+ # region Dataset preprocessing
300
+ if data_args.max_seq_length is None:
301
+ max_seq_length = tokenizer.model_max_length
302
+ if max_seq_length > 1024:
303
+ logger.warning(
304
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
305
+ "Picking 1024 instead. You can change that default value by passing --max_seq_length xxx."
306
+ )
307
+ max_seq_length = 1024
308
+ else:
309
+ if data_args.max_seq_length > tokenizer.model_max_length:
310
+ logger.warning(
311
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the "
312
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
313
+ )
314
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
315
+
316
+ def preprocess_function(examples):
317
+ first_sentences = [[context] * 4 for context in examples[context_name]]
318
+ question_headers = examples[question_header_name]
319
+ second_sentences = [
320
+ [f"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(question_headers)
321
+ ]
322
+
323
+ # Flatten out
324
+ first_sentences = list(chain(*first_sentences))
325
+ second_sentences = list(chain(*second_sentences))
326
+
327
+ # Tokenize
328
+ tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True, max_length=max_seq_length)
329
+ # Un-flatten
330
+ data = {k: [v[i : i + 4] for i in range(0, len(v), 4)] for k, v in tokenized_examples.items()}
331
+ return data
332
+
333
+ if training_args.do_train:
334
+ if "train" not in raw_datasets:
335
+ raise ValueError("--do_train requires a train dataset")
336
+ train_dataset = raw_datasets["train"]
337
+ if data_args.max_train_samples is not None:
338
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
339
+ train_dataset = train_dataset.select(range(max_train_samples))
340
+ train_dataset = train_dataset.map(
341
+ preprocess_function,
342
+ batched=True,
343
+ num_proc=data_args.preprocessing_num_workers,
344
+ load_from_cache_file=not data_args.overwrite_cache,
345
+ )
346
+
347
+ if training_args.do_eval:
348
+ if "validation" not in raw_datasets:
349
+ raise ValueError("--do_eval requires a validation dataset")
350
+ eval_dataset = raw_datasets["validation"]
351
+ if data_args.max_eval_samples is not None:
352
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
353
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
354
+ eval_dataset = eval_dataset.map(
355
+ preprocess_function,
356
+ batched=True,
357
+ num_proc=data_args.preprocessing_num_workers,
358
+ load_from_cache_file=not data_args.overwrite_cache,
359
+ )
360
+
361
+ if data_args.pad_to_max_length:
362
+ data_collator = DefaultDataCollator(return_tensors="np")
363
+ else:
364
+ data_collator = DataCollatorForMultipleChoice(tokenizer, return_tensors="tf")
365
+ # endregion
366
+
367
+ with training_args.strategy.scope():
368
+ # region Build model
369
+ if checkpoint is None:
370
+ model_path = model_args.model_name_or_path
371
+ else:
372
+ model_path = checkpoint
373
+ model = TFAutoModelForMultipleChoice.from_pretrained(
374
+ model_path,
375
+ config=config,
376
+ cache_dir=model_args.cache_dir,
377
+ revision=model_args.model_revision,
378
+ token=model_args.token,
379
+ trust_remote_code=model_args.trust_remote_code,
380
+ )
381
+
382
+ num_replicas = training_args.strategy.num_replicas_in_sync
383
+ total_train_batch_size = training_args.per_device_train_batch_size * num_replicas
384
+ total_eval_batch_size = training_args.per_device_eval_batch_size * num_replicas
385
+
386
+ if training_args.do_train:
387
+ num_train_steps = (len(train_dataset) // total_train_batch_size) * int(training_args.num_train_epochs)
388
+ if training_args.warmup_steps > 0:
389
+ num_warmup_steps = training_args.warmup_steps
390
+ elif training_args.warmup_ratio > 0:
391
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
392
+ else:
393
+ num_warmup_steps = 0
394
+ optimizer, lr_schedule = create_optimizer(
395
+ init_lr=training_args.learning_rate,
396
+ num_train_steps=num_train_steps,
397
+ num_warmup_steps=num_warmup_steps,
398
+ adam_beta1=training_args.adam_beta1,
399
+ adam_beta2=training_args.adam_beta2,
400
+ adam_epsilon=training_args.adam_epsilon,
401
+ weight_decay_rate=training_args.weight_decay,
402
+ adam_global_clipnorm=training_args.max_grad_norm,
403
+ )
404
+ else:
405
+ optimizer = "sgd" # Just write anything because we won't be using it
406
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
407
+ # use this for training unless you specify your own loss function in compile().
408
+ model.compile(optimizer=optimizer, metrics=["accuracy"], jit_compile=training_args.xla)
409
+ # endregion
410
+
411
+ # region Preparing push_to_hub and model card
412
+ push_to_hub_model_id = training_args.push_to_hub_model_id
413
+ model_name = model_args.model_name_or_path.split("/")[-1]
414
+ if not push_to_hub_model_id:
415
+ push_to_hub_model_id = f"{model_name}-finetuned-multiplechoice"
416
+
417
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice"}
418
+
419
+ if training_args.push_to_hub:
420
+ callbacks = [
421
+ PushToHubCallback(
422
+ output_dir=training_args.output_dir,
423
+ hub_model_id=push_to_hub_model_id,
424
+ hub_token=training_args.push_to_hub_token,
425
+ tokenizer=tokenizer,
426
+ **model_card_kwargs,
427
+ )
428
+ ]
429
+ else:
430
+ callbacks = []
431
+ # endregion
432
+
433
+ # region Training
434
+ eval_metrics = None
435
+ if training_args.do_train:
436
+ dataset_options = tf.data.Options()
437
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
438
+
439
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
440
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
441
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
442
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
443
+ # using model.prepare_tf_dataset()
444
+ # For more info see the docs:
445
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
446
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
447
+
448
+ tf_train_dataset = model.prepare_tf_dataset(
449
+ train_dataset,
450
+ shuffle=True,
451
+ batch_size=total_train_batch_size,
452
+ collate_fn=data_collator,
453
+ ).with_options(dataset_options)
454
+
455
+ if training_args.do_eval:
456
+ validation_data = model.prepare_tf_dataset(
457
+ eval_dataset,
458
+ shuffle=False,
459
+ batch_size=total_eval_batch_size,
460
+ collate_fn=data_collator,
461
+ drop_remainder=True,
462
+ ).with_options(dataset_options)
463
+ else:
464
+ validation_data = None
465
+ history = model.fit(
466
+ tf_train_dataset,
467
+ validation_data=validation_data,
468
+ epochs=int(training_args.num_train_epochs),
469
+ callbacks=callbacks,
470
+ )
471
+ eval_metrics = {key: val[-1] for key, val in history.history.items()}
472
+ # endregion
473
+
474
+ # region Evaluation
475
+ if training_args.do_eval and not training_args.do_train:
476
+ dataset_options = tf.data.Options()
477
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
478
+ # Do a standalone evaluation pass
479
+ tf_eval_dataset = model.prepare_tf_dataset(
480
+ eval_dataset,
481
+ shuffle=False,
482
+ batch_size=total_eval_batch_size,
483
+ collate_fn=data_collator,
484
+ drop_remainder=True,
485
+ ).with_options(dataset_options)
486
+ eval_results = model.evaluate(tf_eval_dataset)
487
+ eval_metrics = {"val_loss": eval_results[0], "val_accuracy": eval_results[1]}
488
+ # endregion
489
+
490
+ if eval_metrics is not None and training_args.output_dir is not None:
491
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
492
+ with open(output_eval_file, "w") as writer:
493
+ writer.write(json.dumps(eval_metrics))
494
+
495
+ # region Push to hub
496
+
497
+ if training_args.output_dir is not None and not training_args.push_to_hub:
498
+ # If we're not pushing to hub, at least save a local copy when we're done
499
+ model.save_pretrained(training_args.output_dir)
500
+ # endregion
501
+
502
+
503
+ if __name__ == "__main__":
504
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Question answering example
18
+
19
+ This folder contains the `run_qa.py` script, demonstrating *question answering* with the 🤗 Transformers library.
20
+ For straightforward use-cases you may be able to use this script without modification, although we have also
21
+ included comments in the code to indicate areas that you may need to adapt to your own projects.
22
+
23
+ ### Usage notes
24
+
25
+ Note that when contexts are long they may be split into multiple training cases, not all of which may contain
26
+ the answer span.
27
+
28
+ As-is, the example script will train on SQuAD or any other question-answering dataset formatted the same way, and can handle user
29
+ inputs as well.
30
+
31
+ ### Multi-GPU and TPU usage
32
+
33
+ By default, the script uses a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
34
+ can also be used by passing the name of the TPU resource with the `--tpu` argument. There are some issues surrounding
35
+ these strategies and our models right now, which are most likely to appear in the evaluation/prediction steps. We're
36
+ actively working on better support for multi-GPU and TPU training in TF, but if you encounter problems a quick
37
+ workaround is to train in the multi-GPU or TPU context and then perform predictions outside of it.
38
+
39
+ ### Memory usage and data loading
40
+
41
+ One thing to note is that all data is loaded into memory in this script. Most question answering datasets are small
42
+ enough that this is not an issue, but if you have a very large dataset you will need to modify the script to handle
43
+ data streaming. This is particularly challenging for TPUs, given the stricter requirements and the sheer volume of data
44
+ required to keep them fed. A full explanation of all the possible pitfalls is a bit beyond this example script and
45
+ README, but for more information you can see the 'Input Datasets' section of
46
+ [this document](https://www.tensorflow.org/guide/tpu).
47
+
48
+ ### Example command
49
+
50
+ ```bash
51
+ python run_qa.py \
52
+ --model_name_or_path distilbert/distilbert-base-cased \
53
+ --output_dir output \
54
+ --dataset_name squad \
55
+ --do_train \
56
+ --do_eval
57
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets >= 1.4.0
2
+ tensorflow >= 2.3.0
3
+ evaluate >= 0.2.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/run_qa.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2020 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 question answering.
18
+ """
19
+ # You can also adapt this script on your own question answering task. Pointers for this are left as comments.
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+ from typing import Optional
28
+
29
+ import evaluate
30
+ import tensorflow as tf
31
+ from datasets import load_dataset
32
+ from packaging.version import parse
33
+ from utils_qa import postprocess_qa_predictions
34
+
35
+ import transformers
36
+ from transformers import (
37
+ AutoConfig,
38
+ AutoTokenizer,
39
+ EvalPrediction,
40
+ HfArgumentParser,
41
+ PreTrainedTokenizerFast,
42
+ PushToHubCallback,
43
+ TFAutoModelForQuestionAnswering,
44
+ TFTrainingArguments,
45
+ create_optimizer,
46
+ set_seed,
47
+ )
48
+ from transformers.utils import CONFIG_NAME, TF2_WEIGHTS_NAME, check_min_version, send_example_telemetry
49
+
50
+
51
+ try:
52
+ import tf_keras as keras
53
+ except (ModuleNotFoundError, ImportError):
54
+ import keras
55
+
56
+ if parse(keras.__version__).major > 2:
57
+ raise ValueError(
58
+ "Your currently installed version of Keras is Keras 3, but this is not yet supported in "
59
+ "Transformers. Please install the backwards-compatible tf-keras package with "
60
+ "`pip install tf-keras`."
61
+ )
62
+
63
+
64
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
65
+ check_min_version("4.50.0.dev0")
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+
70
+ # region Arguments
71
+ @dataclass
72
+ class ModelArguments:
73
+ """
74
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
75
+ """
76
+
77
+ model_name_or_path: str = field(
78
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
79
+ )
80
+ config_name: Optional[str] = field(
81
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
82
+ )
83
+ tokenizer_name: Optional[str] = field(
84
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
85
+ )
86
+ cache_dir: Optional[str] = field(
87
+ default=None,
88
+ metadata={"help": "Path to directory to store the pretrained models downloaded from huggingface.co"},
89
+ )
90
+ model_revision: str = field(
91
+ default="main",
92
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
93
+ )
94
+ token: str = field(
95
+ default=None,
96
+ metadata={
97
+ "help": (
98
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
99
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
100
+ )
101
+ },
102
+ )
103
+ trust_remote_code: bool = field(
104
+ default=False,
105
+ metadata={
106
+ "help": (
107
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
108
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
109
+ " code, as it will execute code present on the Hub on your local machine."
110
+ )
111
+ },
112
+ )
113
+
114
+
115
+ @dataclass
116
+ class DataTrainingArguments:
117
+ """
118
+ Arguments pertaining to what data we are going to input our model for training and eval.
119
+ """
120
+
121
+ dataset_name: Optional[str] = field(
122
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
123
+ )
124
+ dataset_config_name: Optional[str] = field(
125
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
126
+ )
127
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
128
+ validation_file: Optional[str] = field(
129
+ default=None,
130
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
131
+ )
132
+ test_file: Optional[str] = field(
133
+ default=None,
134
+ metadata={"help": "An optional input test data file to evaluate the perplexity on (a text file)."},
135
+ )
136
+ overwrite_cache: bool = field(
137
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
138
+ )
139
+ preprocessing_num_workers: Optional[int] = field(
140
+ default=None,
141
+ metadata={"help": "The number of processes to use for the preprocessing."},
142
+ )
143
+ max_seq_length: int = field(
144
+ default=384,
145
+ metadata={
146
+ "help": (
147
+ "The maximum total input sequence length after tokenization. Sequences longer "
148
+ "than this will be truncated, sequences shorter will be padded."
149
+ )
150
+ },
151
+ )
152
+ pad_to_max_length: bool = field(
153
+ default=False,
154
+ metadata={
155
+ "help": (
156
+ "Whether to pad all samples to `max_seq_length`. If False, will pad the samples dynamically when"
157
+ " batching to the maximum length in the batch (which can be faster on GPU but will be slower on TPU)."
158
+ )
159
+ },
160
+ )
161
+ max_train_samples: Optional[int] = field(
162
+ default=None,
163
+ metadata={
164
+ "help": (
165
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
166
+ "value if set."
167
+ )
168
+ },
169
+ )
170
+ max_eval_samples: Optional[int] = field(
171
+ default=None,
172
+ metadata={
173
+ "help": (
174
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
175
+ "value if set."
176
+ )
177
+ },
178
+ )
179
+ max_predict_samples: Optional[int] = field(
180
+ default=None,
181
+ metadata={
182
+ "help": (
183
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
184
+ "value if set."
185
+ )
186
+ },
187
+ )
188
+ version_2_with_negative: bool = field(
189
+ default=False, metadata={"help": "If true, some of the examples do not have an answer."}
190
+ )
191
+ null_score_diff_threshold: float = field(
192
+ default=0.0,
193
+ metadata={
194
+ "help": (
195
+ "The threshold used to select the null answer: if the best answer has a score that is less than "
196
+ "the score of the null answer minus this threshold, the null answer is selected for this example. "
197
+ "Only useful when `version_2_with_negative=True`."
198
+ )
199
+ },
200
+ )
201
+ doc_stride: int = field(
202
+ default=128,
203
+ metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."},
204
+ )
205
+ n_best_size: int = field(
206
+ default=20,
207
+ metadata={"help": "The total number of n-best predictions to generate when looking for an answer."},
208
+ )
209
+ max_answer_length: int = field(
210
+ default=30,
211
+ metadata={
212
+ "help": (
213
+ "The maximum length of an answer that can be generated. This is needed because the start "
214
+ "and end predictions are not conditioned on one another."
215
+ )
216
+ },
217
+ )
218
+
219
+ def __post_init__(self):
220
+ if (
221
+ self.dataset_name is None
222
+ and self.train_file is None
223
+ and self.validation_file is None
224
+ and self.test_file is None
225
+ ):
226
+ raise ValueError("Need either a dataset name or a training/validation file/test_file.")
227
+ else:
228
+ if self.train_file is not None:
229
+ extension = self.train_file.split(".")[-1]
230
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
231
+ if self.validation_file is not None:
232
+ extension = self.validation_file.split(".")[-1]
233
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
234
+ if self.test_file is not None:
235
+ extension = self.test_file.split(".")[-1]
236
+ assert extension in ["csv", "json"], "`test_file` should be a csv or a json file."
237
+
238
+
239
+ # endregion
240
+
241
+
242
+ # region Helper classes
243
+ class SavePretrainedCallback(keras.callbacks.Callback):
244
+ # Hugging Face models have a save_pretrained() method that saves both the weights and the necessary
245
+ # metadata to allow them to be loaded as a pretrained model in future. This is a simple Keras callback
246
+ # that saves the model with this method after each epoch.
247
+ def __init__(self, output_dir, **kwargs):
248
+ super().__init__()
249
+ self.output_dir = output_dir
250
+
251
+ def on_epoch_end(self, epoch, logs=None):
252
+ self.model.save_pretrained(self.output_dir)
253
+
254
+
255
+ # endregion
256
+
257
+
258
+ def main():
259
+ # region Argument parsing
260
+ # See all possible arguments in src/transformers/training_args.py
261
+ # or by passing the --help flag to this script.
262
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
263
+
264
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
265
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
266
+ # If we pass only one argument to the script and it's the path to a json file,
267
+ # let's parse it to get our arguments.
268
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
269
+ else:
270
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
271
+
272
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
273
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
274
+ send_example_telemetry("run_qa", model_args, data_args, framework="tensorflow")
275
+
276
+ output_dir = Path(training_args.output_dir)
277
+ output_dir.mkdir(parents=True, exist_ok=True)
278
+ # endregion
279
+
280
+ # region Checkpoints
281
+ checkpoint = None
282
+ if len(os.listdir(training_args.output_dir)) > 0 and not training_args.overwrite_output_dir:
283
+ if (output_dir / CONFIG_NAME).is_file() and (output_dir / TF2_WEIGHTS_NAME).is_file():
284
+ checkpoint = output_dir
285
+ logger.info(
286
+ f"Checkpoint detected, resuming training from checkpoint in {training_args.output_dir}. To avoid this"
287
+ " behavior, change the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
288
+ )
289
+ else:
290
+ raise ValueError(
291
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
292
+ "Use --overwrite_output_dir to continue regardless."
293
+ )
294
+ # endregion
295
+
296
+ # region Logging
297
+ logging.basicConfig(
298
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
299
+ datefmt="%m/%d/%Y %H:%M:%S",
300
+ handlers=[logging.StreamHandler(sys.stdout)],
301
+ )
302
+ logger.setLevel(logging.INFO if training_args.should_log else logging.WARN)
303
+
304
+ # Set the verbosity to info of the Transformers logger (on main process only):
305
+ if training_args.should_log:
306
+ transformers.utils.logging.set_verbosity_info()
307
+ transformers.utils.logging.enable_default_handler()
308
+ transformers.utils.logging.enable_explicit_format()
309
+ logger.info(f"Training/evaluation parameters {training_args}")
310
+ # endregion
311
+
312
+ # Set seed before initializing model.
313
+ set_seed(training_args.seed)
314
+
315
+ # region Load Data
316
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
317
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
318
+ # (the dataset will be downloaded automatically from the datasets Hub).
319
+ #
320
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
321
+ # 'text' is found. You can easily tweak this behavior (see below).
322
+ #
323
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
324
+ # download the dataset.
325
+ if data_args.dataset_name is not None:
326
+ # Downloading and loading a dataset from the hub.
327
+ datasets = load_dataset(
328
+ data_args.dataset_name,
329
+ data_args.dataset_config_name,
330
+ cache_dir=model_args.cache_dir,
331
+ token=model_args.token,
332
+ trust_remote_code=model_args.trust_remote_code,
333
+ )
334
+ else:
335
+ data_files = {}
336
+ if data_args.train_file is not None:
337
+ data_files["train"] = data_args.train_file
338
+ extension = data_args.train_file.split(".")[-1]
339
+
340
+ if data_args.validation_file is not None:
341
+ data_files["validation"] = data_args.validation_file
342
+ extension = data_args.validation_file.split(".")[-1]
343
+ if data_args.test_file is not None:
344
+ data_files["test"] = data_args.test_file
345
+ extension = data_args.test_file.split(".")[-1]
346
+ datasets = load_dataset(
347
+ extension,
348
+ data_files=data_files,
349
+ field="data",
350
+ cache_dir=model_args.cache_dir,
351
+ token=model_args.token,
352
+ )
353
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
354
+ # https://huggingface.co/docs/datasets/loading_datasets.
355
+ # endregion
356
+
357
+ # region Load pretrained model and tokenizer
358
+ #
359
+ # Distributed training:
360
+ # The .from_pretrained methods guarantee that only one local process can concurrently
361
+ # download model & vocab.
362
+ config = AutoConfig.from_pretrained(
363
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
364
+ cache_dir=model_args.cache_dir,
365
+ revision=model_args.model_revision,
366
+ token=model_args.token,
367
+ trust_remote_code=model_args.trust_remote_code,
368
+ )
369
+ tokenizer = AutoTokenizer.from_pretrained(
370
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
371
+ cache_dir=model_args.cache_dir,
372
+ use_fast=True,
373
+ revision=model_args.model_revision,
374
+ token=model_args.token,
375
+ trust_remote_code=model_args.trust_remote_code,
376
+ )
377
+ # endregion
378
+
379
+ # region Tokenizer check: this script requires a fast tokenizer.
380
+ if not isinstance(tokenizer, PreTrainedTokenizerFast):
381
+ raise ValueError(
382
+ "This example script only works for models that have a fast tokenizer. Checkout the big table of models at"
383
+ " https://huggingface.co/transformers/index.html#supported-frameworks to find the model types that meet"
384
+ " this requirement"
385
+ )
386
+ # endregion
387
+
388
+ # region Preprocessing the datasets
389
+ # Preprocessing is slightly different for training and evaluation.
390
+ if training_args.do_train:
391
+ column_names = datasets["train"].column_names
392
+ elif training_args.do_eval:
393
+ column_names = datasets["validation"].column_names
394
+ else:
395
+ column_names = datasets["test"].column_names
396
+ question_column_name = "question" if "question" in column_names else column_names[0]
397
+ context_column_name = "context" if "context" in column_names else column_names[1]
398
+ answer_column_name = "answers" if "answers" in column_names else column_names[2]
399
+
400
+ # Padding side determines if we do (question|context) or (context|question).
401
+ pad_on_right = tokenizer.padding_side == "right"
402
+
403
+ if data_args.max_seq_length > tokenizer.model_max_length:
404
+ logger.warning(
405
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the "
406
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
407
+ )
408
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
409
+
410
+ if data_args.pad_to_max_length or isinstance(training_args.strategy, tf.distribute.TPUStrategy):
411
+ logger.info("Padding all batches to max length because argument was set or we're on TPU.")
412
+ padding = "max_length"
413
+ else:
414
+ padding = False
415
+
416
+ # Training preprocessing
417
+ def prepare_train_features(examples):
418
+ # Some of the questions have lots of whitespace on the left, which is not useful and will make the
419
+ # truncation of the context fail (the tokenized question will take a lots of space). So we remove that
420
+ # left whitespace
421
+ examples[question_column_name] = [q.lstrip() for q in examples[question_column_name]]
422
+
423
+ # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
424
+ # in one example possible giving several features when a context is long, each of those features having a
425
+ # context that overlaps a bit the context of the previous feature.
426
+ tokenized_examples = tokenizer(
427
+ examples[question_column_name if pad_on_right else context_column_name],
428
+ examples[context_column_name if pad_on_right else question_column_name],
429
+ truncation="only_second" if pad_on_right else "only_first",
430
+ max_length=max_seq_length,
431
+ stride=data_args.doc_stride,
432
+ return_overflowing_tokens=True,
433
+ return_offsets_mapping=True,
434
+ padding=padding,
435
+ )
436
+
437
+ # Since one example might give us several features if it has a long context, we need a map from a feature to
438
+ # its corresponding example. This key gives us just that.
439
+ sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
440
+ # The offset mappings will give us a map from token to character position in the original context. This will
441
+ # help us compute the start_positions and end_positions.
442
+ offset_mapping = tokenized_examples.pop("offset_mapping")
443
+
444
+ # Let's label those examples!
445
+ tokenized_examples["start_positions"] = []
446
+ tokenized_examples["end_positions"] = []
447
+
448
+ for i, offsets in enumerate(offset_mapping):
449
+ # We will label impossible answers with the index of the CLS token.
450
+ input_ids = tokenized_examples["input_ids"][i]
451
+ cls_index = input_ids.index(tokenizer.cls_token_id)
452
+
453
+ # Grab the sequence corresponding to that example (to know what is the context and what is the question).
454
+ sequence_ids = tokenized_examples.sequence_ids(i)
455
+
456
+ # One example can give several spans, this is the index of the example containing this span of text.
457
+ sample_index = sample_mapping[i]
458
+ answers = examples[answer_column_name][sample_index]
459
+ # If no answers are given, set the cls_index as answer.
460
+ if len(answers["answer_start"]) == 0:
461
+ tokenized_examples["start_positions"].append(cls_index)
462
+ tokenized_examples["end_positions"].append(cls_index)
463
+ else:
464
+ # Start/end character index of the answer in the text.
465
+ start_char = answers["answer_start"][0]
466
+ end_char = start_char + len(answers["text"][0])
467
+
468
+ # Start token index of the current span in the text.
469
+ token_start_index = 0
470
+ while sequence_ids[token_start_index] != (1 if pad_on_right else 0):
471
+ token_start_index += 1
472
+
473
+ # End token index of the current span in the text.
474
+ token_end_index = len(input_ids) - 1
475
+ while sequence_ids[token_end_index] != (1 if pad_on_right else 0):
476
+ token_end_index -= 1
477
+
478
+ # Detect if the answer is out of the span (in which case this feature is labeled with the CLS index).
479
+ if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char):
480
+ tokenized_examples["start_positions"].append(cls_index)
481
+ tokenized_examples["end_positions"].append(cls_index)
482
+ else:
483
+ # Otherwise move the token_start_index and token_end_index to the two ends of the answer.
484
+ # Note: we could go after the last offset if the answer is the last word (edge case).
485
+ while token_start_index < len(offsets) and offsets[token_start_index][0] <= start_char:
486
+ token_start_index += 1
487
+ tokenized_examples["start_positions"].append(token_start_index - 1)
488
+ while offsets[token_end_index][1] >= end_char:
489
+ token_end_index -= 1
490
+ tokenized_examples["end_positions"].append(token_end_index + 1)
491
+
492
+ return tokenized_examples
493
+
494
+ processed_datasets = {}
495
+ if training_args.do_train:
496
+ if "train" not in datasets:
497
+ raise ValueError("--do_train requires a train dataset")
498
+ train_dataset = datasets["train"]
499
+ if data_args.max_train_samples is not None:
500
+ # We will select sample from whole data if argument is specified
501
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
502
+ train_dataset = train_dataset.select(range(max_train_samples))
503
+ # Create train feature from dataset
504
+ train_dataset = train_dataset.map(
505
+ prepare_train_features,
506
+ batched=True,
507
+ num_proc=data_args.preprocessing_num_workers,
508
+ remove_columns=column_names,
509
+ load_from_cache_file=not data_args.overwrite_cache,
510
+ )
511
+ if data_args.max_train_samples is not None:
512
+ # Number of samples might increase during Feature Creation, We select only specified max samples
513
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
514
+ train_dataset = train_dataset.select(range(max_train_samples))
515
+ processed_datasets["train"] = train_dataset
516
+
517
+ # Validation preprocessing
518
+ def prepare_validation_features(examples):
519
+ # Some of the questions have lots of whitespace on the left, which is not useful and will make the
520
+ # truncation of the context fail (the tokenized question will take a lots of space). So we remove that
521
+ # left whitespace
522
+ examples[question_column_name] = [q.lstrip() for q in examples[question_column_name]]
523
+
524
+ # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
525
+ # in one example possible giving several features when a context is long, each of those features having a
526
+ # context that overlaps a bit the context of the previous feature.
527
+ tokenized_examples = tokenizer(
528
+ examples[question_column_name if pad_on_right else context_column_name],
529
+ examples[context_column_name if pad_on_right else question_column_name],
530
+ truncation="only_second" if pad_on_right else "only_first",
531
+ max_length=max_seq_length,
532
+ stride=data_args.doc_stride,
533
+ return_overflowing_tokens=True,
534
+ return_offsets_mapping=True,
535
+ padding=padding,
536
+ )
537
+
538
+ # Since one example might give us several features if it has a long context, we need a map from a feature to
539
+ # its corresponding example. This key gives us just that.
540
+ sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
541
+
542
+ # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
543
+ # corresponding example_id and we will store the offset mappings.
544
+ tokenized_examples["example_id"] = []
545
+
546
+ for i in range(len(tokenized_examples["input_ids"])):
547
+ # Grab the sequence corresponding to that example (to know what is the context and what is the question).
548
+ sequence_ids = tokenized_examples.sequence_ids(i)
549
+ context_index = 1 if pad_on_right else 0
550
+
551
+ # One example can give several spans, this is the index of the example containing this span of text.
552
+ sample_index = sample_mapping[i]
553
+ tokenized_examples["example_id"].append(examples["id"][sample_index])
554
+
555
+ # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
556
+ # position is part of the context or not.
557
+ tokenized_examples["offset_mapping"][i] = [
558
+ (o if sequence_ids[k] == context_index else None)
559
+ for k, o in enumerate(tokenized_examples["offset_mapping"][i])
560
+ ]
561
+
562
+ return tokenized_examples
563
+
564
+ if training_args.do_eval:
565
+ if "validation" not in datasets:
566
+ raise ValueError("--do_eval requires a validation dataset")
567
+ eval_examples = datasets["validation"]
568
+ if data_args.max_eval_samples is not None:
569
+ # We will select sample from whole data
570
+ max_eval_samples = min(len(eval_examples), data_args.max_eval_samples)
571
+ eval_examples = eval_examples.select(range(max_eval_samples))
572
+ # Validation Feature Creation
573
+ eval_dataset = eval_examples.map(
574
+ prepare_validation_features,
575
+ batched=True,
576
+ num_proc=data_args.preprocessing_num_workers,
577
+ remove_columns=column_names,
578
+ load_from_cache_file=not data_args.overwrite_cache,
579
+ )
580
+ if data_args.max_eval_samples is not None:
581
+ # During Feature creation dataset samples might increase, we will select required samples again
582
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
583
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
584
+ processed_datasets["validation"] = eval_dataset
585
+
586
+ if training_args.do_predict:
587
+ if "test" not in datasets:
588
+ raise ValueError("--do_predict requires a test dataset")
589
+ predict_examples = datasets["test"]
590
+ if data_args.max_predict_samples is not None:
591
+ # We will select sample from whole data
592
+ predict_examples = predict_examples.select(range(data_args.max_predict_samples))
593
+ # Predict Feature Creation
594
+ predict_dataset = predict_examples.map(
595
+ prepare_validation_features,
596
+ batched=True,
597
+ num_proc=data_args.preprocessing_num_workers,
598
+ remove_columns=column_names,
599
+ load_from_cache_file=not data_args.overwrite_cache,
600
+ )
601
+ if data_args.max_predict_samples is not None:
602
+ # During Feature creation dataset samples might increase, we will select required samples again
603
+ max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
604
+ predict_dataset = predict_dataset.select(range(max_predict_samples))
605
+ processed_datasets["test"] = predict_dataset
606
+ # endregion
607
+
608
+ # region Metrics and Post-processing:
609
+ def post_processing_function(examples, features, predictions, stage="eval"):
610
+ # Post-processing: we match the start logits and end logits to answers in the original context.
611
+ predictions = postprocess_qa_predictions(
612
+ examples=examples,
613
+ features=features,
614
+ predictions=predictions,
615
+ version_2_with_negative=data_args.version_2_with_negative,
616
+ n_best_size=data_args.n_best_size,
617
+ max_answer_length=data_args.max_answer_length,
618
+ null_score_diff_threshold=data_args.null_score_diff_threshold,
619
+ output_dir=training_args.output_dir,
620
+ prefix=stage,
621
+ )
622
+ # Format the result to the format the metric expects.
623
+ if data_args.version_2_with_negative:
624
+ formatted_predictions = [
625
+ {"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items()
626
+ ]
627
+ else:
628
+ formatted_predictions = [{"id": k, "prediction_text": v} for k, v in predictions.items()]
629
+
630
+ references = [{"id": ex["id"], "answers": ex[answer_column_name]} for ex in examples]
631
+ return EvalPrediction(predictions=formatted_predictions, label_ids=references)
632
+
633
+ metric = evaluate.load(
634
+ "squad_v2" if data_args.version_2_with_negative else "squad", cache_dir=model_args.cache_dir
635
+ )
636
+
637
+ def compute_metrics(p: EvalPrediction):
638
+ return metric.compute(predictions=p.predictions, references=p.label_ids)
639
+
640
+ # endregion
641
+
642
+ with training_args.strategy.scope():
643
+ dataset_options = tf.data.Options()
644
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
645
+ num_replicas = training_args.strategy.num_replicas_in_sync
646
+
647
+ # region Load model and prepare datasets
648
+ if checkpoint is None:
649
+ model_path = model_args.model_name_or_path
650
+ else:
651
+ model_path = checkpoint
652
+ model = TFAutoModelForQuestionAnswering.from_pretrained(
653
+ model_path,
654
+ config=config,
655
+ cache_dir=model_args.cache_dir,
656
+ revision=model_args.model_revision,
657
+ token=model_args.token,
658
+ trust_remote_code=model_args.trust_remote_code,
659
+ )
660
+ if training_args.do_train:
661
+ training_dataset = model.prepare_tf_dataset(
662
+ processed_datasets["train"],
663
+ shuffle=True,
664
+ batch_size=training_args.per_device_train_batch_size * num_replicas,
665
+ tokenizer=tokenizer,
666
+ )
667
+
668
+ training_dataset = training_dataset.with_options(dataset_options)
669
+
670
+ num_train_steps = len(training_dataset) * training_args.num_train_epochs
671
+ if training_args.warmup_steps > 0:
672
+ num_warmup_steps = training_args.warmup_steps
673
+ elif training_args.warmup_ratio > 0:
674
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
675
+ else:
676
+ num_warmup_steps = 0
677
+
678
+ optimizer, schedule = create_optimizer(
679
+ init_lr=training_args.learning_rate,
680
+ num_train_steps=len(training_dataset) * training_args.num_train_epochs,
681
+ num_warmup_steps=num_warmup_steps,
682
+ adam_beta1=training_args.adam_beta1,
683
+ adam_beta2=training_args.adam_beta2,
684
+ adam_epsilon=training_args.adam_epsilon,
685
+ weight_decay_rate=training_args.weight_decay,
686
+ adam_global_clipnorm=training_args.max_grad_norm,
687
+ )
688
+
689
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
690
+ # use this for training unless you specify your own loss function in compile().
691
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla, metrics=["accuracy"])
692
+
693
+ else:
694
+ # Optimizer doesn't matter as it won't be used anyway
695
+ model.compile(optimizer="sgd", jit_compile=training_args.xla, metrics=["accuracy"])
696
+ training_dataset = None
697
+
698
+ if training_args.do_eval:
699
+ eval_dataset = model.prepare_tf_dataset(
700
+ processed_datasets["validation"],
701
+ shuffle=False,
702
+ batch_size=training_args.per_device_train_batch_size * num_replicas,
703
+ tokenizer=tokenizer,
704
+ )
705
+ eval_dataset = eval_dataset.with_options(dataset_options)
706
+ else:
707
+ eval_dataset = None
708
+
709
+ if training_args.do_predict:
710
+ predict_dataset = model.prepare_tf_dataset(
711
+ processed_datasets["test"],
712
+ shuffle=False,
713
+ batch_size=training_args.per_device_eval_batch_size * num_replicas,
714
+ tokenizer=tokenizer,
715
+ )
716
+ predict_dataset = predict_dataset.with_options(dataset_options)
717
+ else:
718
+ predict_dataset = None
719
+
720
+ # endregion
721
+
722
+ # region Preparing push_to_hub and model card
723
+ push_to_hub_model_id = training_args.push_to_hub_model_id
724
+ model_name = model_args.model_name_or_path.split("/")[-1]
725
+ if not push_to_hub_model_id:
726
+ if data_args.dataset_name is not None:
727
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}"
728
+ else:
729
+ push_to_hub_model_id = f"{model_name}-finetuned-question-answering"
730
+
731
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "question-answering"}
732
+ if data_args.dataset_name is not None:
733
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
734
+ if data_args.dataset_config_name is not None:
735
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
736
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
737
+ else:
738
+ model_card_kwargs["dataset"] = data_args.dataset_name
739
+
740
+ if training_args.push_to_hub:
741
+ callbacks = [
742
+ PushToHubCallback(
743
+ output_dir=training_args.output_dir,
744
+ hub_model_id=push_to_hub_model_id,
745
+ hub_token=training_args.push_to_hub_token,
746
+ tokenizer=tokenizer,
747
+ **model_card_kwargs,
748
+ )
749
+ ]
750
+ else:
751
+ callbacks = []
752
+ # endregion
753
+
754
+ # region Training and Evaluation
755
+
756
+ if training_args.do_train:
757
+ # Note that the validation and test datasets have been processed in a different way to the
758
+ # training datasets in this example, and so they don't have the same label structure.
759
+ # As such, we don't pass them directly to Keras, but instead get model predictions to evaluate
760
+ # after training.
761
+ model.fit(training_dataset, epochs=int(training_args.num_train_epochs), callbacks=callbacks)
762
+
763
+ if training_args.do_eval:
764
+ logger.info("*** Evaluation ***")
765
+
766
+ # In this example, we compute advanced metrics at the end of training, but
767
+ # if you'd like to compute metrics every epoch that are too complex to be written as
768
+ # standard Keras metrics, you can use our KerasMetricCallback. See
769
+ # https://huggingface.co/docs/transformers/main/en/main_classes/keras_callbacks
770
+
771
+ eval_predictions = model.predict(eval_dataset)
772
+ if isinstance(eval_predictions.start_logits, tf.RaggedTensor):
773
+ # If predictions are RaggedTensor, we densify them. Since they are logits, padding with 0 is a bad idea!
774
+ # The reason is that a logit of 0 can often end up as quite a high probability value, sometimes even
775
+ # the highest probability in a sample. Instead, we use a large negative value, which ensures that the
776
+ # padding positions are correctly masked.
777
+ eval_start_logits = eval_predictions.start_logits.to_tensor(default_value=-1000).numpy()
778
+ eval_end_logits = eval_predictions.end_logits.to_tensor(default_value=-1000).numpy()
779
+ else:
780
+ eval_start_logits = eval_predictions.start_logits
781
+ eval_end_logits = eval_predictions.end_logits
782
+
783
+ post_processed_eval = post_processing_function(
784
+ datasets["validation"],
785
+ processed_datasets["validation"],
786
+ (eval_start_logits, eval_end_logits),
787
+ )
788
+ metrics = compute_metrics(post_processed_eval)
789
+ logging.info("Evaluation metrics:")
790
+ for metric, value in metrics.items():
791
+ logging.info(f"{metric}: {value:.3f}")
792
+ if training_args.output_dir is not None:
793
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
794
+ with open(output_eval_file, "w") as writer:
795
+ writer.write(json.dumps(metrics))
796
+ # endregion
797
+
798
+ # region Prediction
799
+ if training_args.do_predict:
800
+ logger.info("*** Predict ***")
801
+
802
+ test_predictions = model.predict(predict_dataset)
803
+ if isinstance(test_predictions.start_logits, tf.RaggedTensor):
804
+ # If predictions are RaggedTensor, we densify them. Since they are logits, padding with 0 is a bad idea!
805
+ # The reason is that a logit of 0 can often end up as quite a high probability value, sometimes even
806
+ # the highest probability in a sample. Instead, we use a large negative value, which ensures that the
807
+ # padding positions are correctly masked.
808
+ test_start_logits = test_predictions.start_logits.to_tensor(default_value=-1000).numpy()
809
+ test_end_logits = test_predictions.end_logits.to_tensor(default_value=-1000).numpy()
810
+ else:
811
+ test_start_logits = test_predictions.start_logits
812
+ test_end_logits = test_predictions.end_logits
813
+ post_processed_test = post_processing_function(
814
+ datasets["test"],
815
+ processed_datasets["test"],
816
+ (test_start_logits, test_end_logits),
817
+ )
818
+ metrics = compute_metrics(post_processed_test)
819
+
820
+ logging.info("Test metrics:")
821
+ for metric, value in metrics.items():
822
+ logging.info(f"{metric}: {value:.3f}")
823
+ # endregion
824
+
825
+ if training_args.output_dir is not None and not training_args.push_to_hub:
826
+ # If we're not pushing to hub, at least save a local copy when we're done
827
+ model.save_pretrained(training_args.output_dir)
828
+
829
+
830
+ if __name__ == "__main__":
831
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/question-answering/utils_qa.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Team All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Post-processing utilities for question answering.
17
+ """
18
+
19
+ import collections
20
+ import json
21
+ import logging
22
+ import os
23
+ from typing import Optional, Tuple
24
+
25
+ import numpy as np
26
+ from tqdm.auto import tqdm
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def postprocess_qa_predictions(
33
+ examples,
34
+ features,
35
+ predictions: Tuple[np.ndarray, np.ndarray],
36
+ version_2_with_negative: bool = False,
37
+ n_best_size: int = 20,
38
+ max_answer_length: int = 30,
39
+ null_score_diff_threshold: float = 0.0,
40
+ output_dir: Optional[str] = None,
41
+ prefix: Optional[str] = None,
42
+ log_level: Optional[int] = logging.WARNING,
43
+ ):
44
+ """
45
+ Post-processes the predictions of a question-answering model to convert them to answers that are substrings of the
46
+ original contexts. This is the base postprocessing functions for models that only return start and end logits.
47
+
48
+ Args:
49
+ examples: The non-preprocessed dataset (see the main script for more information).
50
+ features: The processed dataset (see the main script for more information).
51
+ predictions (:obj:`Tuple[np.ndarray, np.ndarray]`):
52
+ The predictions of the model: two arrays containing the start logits and the end logits respectively. Its
53
+ first dimension must match the number of elements of :obj:`features`.
54
+ version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`):
55
+ Whether or not the underlying dataset contains examples with no answers.
56
+ n_best_size (:obj:`int`, `optional`, defaults to 20):
57
+ The total number of n-best predictions to generate when looking for an answer.
58
+ max_answer_length (:obj:`int`, `optional`, defaults to 30):
59
+ The maximum length of an answer that can be generated. This is needed because the start and end predictions
60
+ are not conditioned on one another.
61
+ null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0):
62
+ The threshold used to select the null answer: if the best answer has a score that is less than the score of
63
+ the null answer minus this threshold, the null answer is selected for this example (note that the score of
64
+ the null answer for an example giving several features is the minimum of the scores for the null answer on
65
+ each feature: all features must be aligned on the fact they `want` to predict a null answer).
66
+
67
+ Only useful when :obj:`version_2_with_negative` is :obj:`True`.
68
+ output_dir (:obj:`str`, `optional`):
69
+ If provided, the dictionaries of predictions, n_best predictions (with their scores and logits) and, if
70
+ :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null
71
+ answers, are saved in `output_dir`.
72
+ prefix (:obj:`str`, `optional`):
73
+ If provided, the dictionaries mentioned above are saved with `prefix` added to their names.
74
+ log_level (:obj:`int`, `optional`, defaults to ``logging.WARNING``):
75
+ ``logging`` log level (e.g., ``logging.WARNING``)
76
+ """
77
+ if len(predictions) != 2:
78
+ raise ValueError("`predictions` should be a tuple with two elements (start_logits, end_logits).")
79
+ all_start_logits, all_end_logits = predictions
80
+
81
+ if len(predictions[0]) != len(features):
82
+ raise ValueError(f"Got {len(predictions[0])} predictions and {len(features)} features.")
83
+
84
+ # Build a map example to its corresponding features.
85
+ example_id_to_index = {k: i for i, k in enumerate(examples["id"])}
86
+ features_per_example = collections.defaultdict(list)
87
+ for i, feature in enumerate(features):
88
+ features_per_example[example_id_to_index[feature["example_id"]]].append(i)
89
+
90
+ # The dictionaries we have to fill.
91
+ all_predictions = collections.OrderedDict()
92
+ all_nbest_json = collections.OrderedDict()
93
+ if version_2_with_negative:
94
+ scores_diff_json = collections.OrderedDict()
95
+
96
+ # Logging.
97
+ logger.setLevel(log_level)
98
+ logger.info(f"Post-processing {len(examples)} example predictions split into {len(features)} features.")
99
+
100
+ # Let's loop over all the examples!
101
+ for example_index, example in enumerate(tqdm(examples)):
102
+ # Those are the indices of the features associated to the current example.
103
+ feature_indices = features_per_example[example_index]
104
+
105
+ min_null_prediction = None
106
+ prelim_predictions = []
107
+
108
+ # Looping through all the features associated to the current example.
109
+ for feature_index in feature_indices:
110
+ # We grab the predictions of the model for this feature.
111
+ start_logits = all_start_logits[feature_index]
112
+ end_logits = all_end_logits[feature_index]
113
+ # This is what will allow us to map some the positions in our logits to span of texts in the original
114
+ # context.
115
+ offset_mapping = features[feature_index]["offset_mapping"]
116
+ # Optional `token_is_max_context`, if provided we will remove answers that do not have the maximum context
117
+ # available in the current feature.
118
+ token_is_max_context = features[feature_index].get("token_is_max_context", None)
119
+
120
+ # Update minimum null prediction.
121
+ feature_null_score = start_logits[0] + end_logits[0]
122
+ if min_null_prediction is None or min_null_prediction["score"] > feature_null_score:
123
+ min_null_prediction = {
124
+ "offsets": (0, 0),
125
+ "score": feature_null_score,
126
+ "start_logit": start_logits[0],
127
+ "end_logit": end_logits[0],
128
+ }
129
+
130
+ # Go through all possibilities for the `n_best_size` greater start and end logits.
131
+ start_indexes = np.argsort(start_logits)[-1 : -n_best_size - 1 : -1].tolist()
132
+ end_indexes = np.argsort(end_logits)[-1 : -n_best_size - 1 : -1].tolist()
133
+ for start_index in start_indexes:
134
+ for end_index in end_indexes:
135
+ # Don't consider out-of-scope answers, either because the indices are out of bounds or correspond
136
+ # to part of the input_ids that are not in the context.
137
+ if (
138
+ start_index >= len(offset_mapping)
139
+ or end_index >= len(offset_mapping)
140
+ or offset_mapping[start_index] is None
141
+ or len(offset_mapping[start_index]) < 2
142
+ or offset_mapping[end_index] is None
143
+ or len(offset_mapping[end_index]) < 2
144
+ ):
145
+ continue
146
+ # Don't consider answers with a length that is either < 0 or > max_answer_length.
147
+ if end_index < start_index or end_index - start_index + 1 > max_answer_length:
148
+ continue
149
+ # Don't consider answer that don't have the maximum context available (if such information is
150
+ # provided).
151
+ if token_is_max_context is not None and not token_is_max_context.get(str(start_index), False):
152
+ continue
153
+
154
+ prelim_predictions.append(
155
+ {
156
+ "offsets": (offset_mapping[start_index][0], offset_mapping[end_index][1]),
157
+ "score": start_logits[start_index] + end_logits[end_index],
158
+ "start_logit": start_logits[start_index],
159
+ "end_logit": end_logits[end_index],
160
+ }
161
+ )
162
+ if version_2_with_negative and min_null_prediction is not None:
163
+ # Add the minimum null prediction
164
+ prelim_predictions.append(min_null_prediction)
165
+ null_score = min_null_prediction["score"]
166
+
167
+ # Only keep the best `n_best_size` predictions.
168
+ predictions = sorted(prelim_predictions, key=lambda x: x["score"], reverse=True)[:n_best_size]
169
+
170
+ # Add back the minimum null prediction if it was removed because of its low score.
171
+ if (
172
+ version_2_with_negative
173
+ and min_null_prediction is not None
174
+ and not any(p["offsets"] == (0, 0) for p in predictions)
175
+ ):
176
+ predictions.append(min_null_prediction)
177
+
178
+ # Use the offsets to gather the answer text in the original context.
179
+ context = example["context"]
180
+ for pred in predictions:
181
+ offsets = pred.pop("offsets")
182
+ pred["text"] = context[offsets[0] : offsets[1]]
183
+
184
+ # In the very rare edge case we have not a single non-null prediction, we create a fake prediction to avoid
185
+ # failure.
186
+ if len(predictions) == 0 or (len(predictions) == 1 and predictions[0]["text"] == ""):
187
+ predictions.insert(0, {"text": "empty", "start_logit": 0.0, "end_logit": 0.0, "score": 0.0})
188
+
189
+ # Compute the softmax of all scores (we do it with numpy to stay independent from torch/tf in this file, using
190
+ # the LogSumExp trick).
191
+ scores = np.array([pred.pop("score") for pred in predictions])
192
+ exp_scores = np.exp(scores - np.max(scores))
193
+ probs = exp_scores / exp_scores.sum()
194
+
195
+ # Include the probabilities in our predictions.
196
+ for prob, pred in zip(probs, predictions):
197
+ pred["probability"] = prob
198
+
199
+ # Pick the best prediction. If the null answer is not possible, this is easy.
200
+ if not version_2_with_negative:
201
+ all_predictions[example["id"]] = predictions[0]["text"]
202
+ else:
203
+ # Otherwise we first need to find the best non-empty prediction.
204
+ i = 0
205
+ while predictions[i]["text"] == "":
206
+ i += 1
207
+ best_non_null_pred = predictions[i]
208
+
209
+ # Then we compare to the null prediction using the threshold.
210
+ score_diff = null_score - best_non_null_pred["start_logit"] - best_non_null_pred["end_logit"]
211
+ scores_diff_json[example["id"]] = float(score_diff) # To be JSON-serializable.
212
+ if score_diff > null_score_diff_threshold:
213
+ all_predictions[example["id"]] = ""
214
+ else:
215
+ all_predictions[example["id"]] = best_non_null_pred["text"]
216
+
217
+ # Make `predictions` JSON-serializable by casting np.float back to float.
218
+ all_nbest_json[example["id"]] = [
219
+ {k: (float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v) for k, v in pred.items()}
220
+ for pred in predictions
221
+ ]
222
+
223
+ # If we have an output_dir, let's save all those dicts.
224
+ if output_dir is not None:
225
+ if not os.path.isdir(output_dir):
226
+ raise EnvironmentError(f"{output_dir} is not a directory.")
227
+
228
+ prediction_file = os.path.join(
229
+ output_dir, "predictions.json" if prefix is None else f"{prefix}_predictions.json"
230
+ )
231
+ nbest_file = os.path.join(
232
+ output_dir, "nbest_predictions.json" if prefix is None else f"{prefix}_nbest_predictions.json"
233
+ )
234
+ if version_2_with_negative:
235
+ null_odds_file = os.path.join(
236
+ output_dir, "null_odds.json" if prefix is None else f"{prefix}_null_odds.json"
237
+ )
238
+
239
+ logger.info(f"Saving predictions to {prediction_file}.")
240
+ with open(prediction_file, "w") as writer:
241
+ writer.write(json.dumps(all_predictions, indent=4) + "\n")
242
+ logger.info(f"Saving nbest_preds to {nbest_file}.")
243
+ with open(nbest_file, "w") as writer:
244
+ writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
245
+ if version_2_with_negative:
246
+ logger.info(f"Saving null_odds to {null_odds_file}.")
247
+ with open(null_odds_file, "w") as writer:
248
+ writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
249
+
250
+ return all_predictions
251
+
252
+
253
+ def postprocess_qa_predictions_with_beam_search(
254
+ examples,
255
+ features,
256
+ predictions: Tuple[np.ndarray, np.ndarray],
257
+ version_2_with_negative: bool = False,
258
+ n_best_size: int = 20,
259
+ max_answer_length: int = 30,
260
+ start_n_top: int = 5,
261
+ end_n_top: int = 5,
262
+ output_dir: Optional[str] = None,
263
+ prefix: Optional[str] = None,
264
+ log_level: Optional[int] = logging.WARNING,
265
+ ):
266
+ """
267
+ Post-processes the predictions of a question-answering model with beam search to convert them to answers that are substrings of the
268
+ original contexts. This is the postprocessing functions for models that return start and end logits, indices, as well as
269
+ cls token predictions.
270
+
271
+ Args:
272
+ examples: The non-preprocessed dataset (see the main script for more information).
273
+ features: The processed dataset (see the main script for more information).
274
+ predictions (:obj:`Tuple[np.ndarray, np.ndarray]`):
275
+ The predictions of the model: two arrays containing the start logits and the end logits respectively. Its
276
+ first dimension must match the number of elements of :obj:`features`.
277
+ version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`):
278
+ Whether or not the underlying dataset contains examples with no answers.
279
+ n_best_size (:obj:`int`, `optional`, defaults to 20):
280
+ The total number of n-best predictions to generate when looking for an answer.
281
+ max_answer_length (:obj:`int`, `optional`, defaults to 30):
282
+ The maximum length of an answer that can be generated. This is needed because the start and end predictions
283
+ are not conditioned on one another.
284
+ start_n_top (:obj:`int`, `optional`, defaults to 5):
285
+ The number of top start logits too keep when searching for the :obj:`n_best_size` predictions.
286
+ end_n_top (:obj:`int`, `optional`, defaults to 5):
287
+ The number of top end logits too keep when searching for the :obj:`n_best_size` predictions.
288
+ output_dir (:obj:`str`, `optional`):
289
+ If provided, the dictionaries of predictions, n_best predictions (with their scores and logits) and, if
290
+ :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null
291
+ answers, are saved in `output_dir`.
292
+ prefix (:obj:`str`, `optional`):
293
+ If provided, the dictionaries mentioned above are saved with `prefix` added to their names.
294
+ log_level (:obj:`int`, `optional`, defaults to ``logging.WARNING``):
295
+ ``logging`` log level (e.g., ``logging.WARNING``)
296
+ """
297
+ if len(predictions) != 5:
298
+ raise ValueError("`predictions` should be a tuple with five elements.")
299
+ start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits = predictions
300
+
301
+ if len(predictions[0]) != len(features):
302
+ raise ValueError(f"Got {len(predictions[0])} predictions and {len(features)} features.")
303
+
304
+ # Build a map example to its corresponding features.
305
+ example_id_to_index = {k: i for i, k in enumerate(examples["id"])}
306
+ features_per_example = collections.defaultdict(list)
307
+ for i, feature in enumerate(features):
308
+ features_per_example[example_id_to_index[feature["example_id"]]].append(i)
309
+
310
+ # The dictionaries we have to fill.
311
+ all_predictions = collections.OrderedDict()
312
+ all_nbest_json = collections.OrderedDict()
313
+ scores_diff_json = collections.OrderedDict() if version_2_with_negative else None
314
+
315
+ # Logging.
316
+ logger.setLevel(log_level)
317
+ logger.info(f"Post-processing {len(examples)} example predictions split into {len(features)} features.")
318
+
319
+ # Let's loop over all the examples!
320
+ for example_index, example in enumerate(tqdm(examples)):
321
+ # Those are the indices of the features associated to the current example.
322
+ feature_indices = features_per_example[example_index]
323
+
324
+ min_null_score = None
325
+ prelim_predictions = []
326
+
327
+ # Looping through all the features associated to the current example.
328
+ for feature_index in feature_indices:
329
+ # We grab the predictions of the model for this feature.
330
+ start_log_prob = start_top_log_probs[feature_index]
331
+ start_indexes = start_top_index[feature_index]
332
+ end_log_prob = end_top_log_probs[feature_index]
333
+ end_indexes = end_top_index[feature_index]
334
+ feature_null_score = cls_logits[feature_index]
335
+ # This is what will allow us to map some the positions in our logits to span of texts in the original
336
+ # context.
337
+ offset_mapping = features[feature_index]["offset_mapping"]
338
+ # Optional `token_is_max_context`, if provided we will remove answers that do not have the maximum context
339
+ # available in the current feature.
340
+ token_is_max_context = features[feature_index].get("token_is_max_context", None)
341
+
342
+ # Update minimum null prediction
343
+ if min_null_score is None or feature_null_score < min_null_score:
344
+ min_null_score = feature_null_score
345
+
346
+ # Go through all possibilities for the `n_start_top`/`n_end_top` greater start and end logits.
347
+ for i in range(start_n_top):
348
+ for j in range(end_n_top):
349
+ start_index = int(start_indexes[i])
350
+ j_index = i * end_n_top + j
351
+ end_index = int(end_indexes[j_index])
352
+ # Don't consider out-of-scope answers (last part of the test should be unnecessary because of the
353
+ # p_mask but let's not take any risk)
354
+ if (
355
+ start_index >= len(offset_mapping)
356
+ or end_index >= len(offset_mapping)
357
+ or offset_mapping[start_index] is None
358
+ or len(offset_mapping[start_index]) < 2
359
+ or offset_mapping[end_index] is None
360
+ or len(offset_mapping[end_index]) < 2
361
+ ):
362
+ continue
363
+
364
+ # Don't consider answers with a length negative or > max_answer_length.
365
+ if end_index < start_index or end_index - start_index + 1 > max_answer_length:
366
+ continue
367
+ # Don't consider answer that don't have the maximum context available (if such information is
368
+ # provided).
369
+ if token_is_max_context is not None and not token_is_max_context.get(str(start_index), False):
370
+ continue
371
+ prelim_predictions.append(
372
+ {
373
+ "offsets": (offset_mapping[start_index][0], offset_mapping[end_index][1]),
374
+ "score": start_log_prob[i] + end_log_prob[j_index],
375
+ "start_log_prob": start_log_prob[i],
376
+ "end_log_prob": end_log_prob[j_index],
377
+ }
378
+ )
379
+
380
+ # Only keep the best `n_best_size` predictions.
381
+ predictions = sorted(prelim_predictions, key=lambda x: x["score"], reverse=True)[:n_best_size]
382
+
383
+ # Use the offsets to gather the answer text in the original context.
384
+ context = example["context"]
385
+ for pred in predictions:
386
+ offsets = pred.pop("offsets")
387
+ pred["text"] = context[offsets[0] : offsets[1]]
388
+
389
+ # In the very rare edge case we have not a single non-null prediction, we create a fake prediction to avoid
390
+ # failure.
391
+ if len(predictions) == 0:
392
+ # Without predictions min_null_score is going to be None and None will cause an exception later
393
+ min_null_score = -2e-6
394
+ predictions.insert(0, {"text": "", "start_logit": -1e-6, "end_logit": -1e-6, "score": min_null_score})
395
+
396
+ # Compute the softmax of all scores (we do it with numpy to stay independent from torch/tf in this file, using
397
+ # the LogSumExp trick).
398
+ scores = np.array([pred.pop("score") for pred in predictions])
399
+ exp_scores = np.exp(scores - np.max(scores))
400
+ probs = exp_scores / exp_scores.sum()
401
+
402
+ # Include the probabilities in our predictions.
403
+ for prob, pred in zip(probs, predictions):
404
+ pred["probability"] = prob
405
+
406
+ # Pick the best prediction and set the probability for the null answer.
407
+ all_predictions[example["id"]] = predictions[0]["text"]
408
+ if version_2_with_negative:
409
+ scores_diff_json[example["id"]] = float(min_null_score)
410
+
411
+ # Make `predictions` JSON-serializable by casting np.float back to float.
412
+ all_nbest_json[example["id"]] = [
413
+ {k: (float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v) for k, v in pred.items()}
414
+ for pred in predictions
415
+ ]
416
+
417
+ # If we have an output_dir, let's save all those dicts.
418
+ if output_dir is not None:
419
+ if not os.path.isdir(output_dir):
420
+ raise EnvironmentError(f"{output_dir} is not a directory.")
421
+
422
+ prediction_file = os.path.join(
423
+ output_dir, "predictions.json" if prefix is None else f"{prefix}_predictions.json"
424
+ )
425
+ nbest_file = os.path.join(
426
+ output_dir, "nbest_predictions.json" if prefix is None else f"{prefix}_nbest_predictions.json"
427
+ )
428
+ if version_2_with_negative:
429
+ null_odds_file = os.path.join(
430
+ output_dir, "null_odds.json" if prefix is None else f"{prefix}_null_odds.json"
431
+ )
432
+
433
+ logger.info(f"Saving predictions to {prediction_file}.")
434
+ with open(prediction_file, "w") as writer:
435
+ writer.write(json.dumps(all_predictions, indent=4) + "\n")
436
+ logger.info(f"Saving nbest_preds to {nbest_file}.")
437
+ with open(nbest_file, "w") as writer:
438
+ writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
439
+ if version_2_with_negative:
440
+ logger.info(f"Saving null_odds to {null_odds_file}.")
441
+ with open(null_odds_file, "w") as writer:
442
+ writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
443
+
444
+ return all_predictions, scores_diff_json
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/summarization/README.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Summarization example
18
+
19
+ This script shows an example of training a *summarization* model with the 🤗 Transformers library.
20
+ For straightforward use-cases you may be able to use these scripts without modification, although we have also
21
+ included comments in the code to indicate areas that you may need to adapt to your own projects.
22
+
23
+ ### Multi-GPU and TPU usage
24
+
25
+ By default, these scripts use a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
26
+ can also be used by passing the name of the TPU resource with the `--tpu` argument.
27
+
28
+ ### Example command
29
+ ```
30
+ python run_summarization.py \
31
+ --model_name_or_path facebook/bart-base \
32
+ --dataset_name cnn_dailymail \
33
+ --dataset_config "3.0.0" \
34
+ --output_dir /tmp/tst-summarization \
35
+ --per_device_train_batch_size 8 \
36
+ --per_device_eval_batch_size 16 \
37
+ --num_train_epochs 3 \
38
+ --do_train \
39
+ --do_eval
40
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/summarization/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets >= 1.4.0
2
+ tensorflow >= 2.3.0
3
+ evaluate >= 0.2.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/summarization/run_summarization.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 summarization.
18
+ """
19
+ # You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from typing import Optional
27
+
28
+ import datasets
29
+ import evaluate
30
+ import nltk # Here to have a nice missing dependency error message early on
31
+ import numpy as np
32
+ import tensorflow as tf
33
+ from datasets import load_dataset
34
+ from filelock import FileLock
35
+
36
+ import transformers
37
+ from transformers import (
38
+ AutoConfig,
39
+ AutoTokenizer,
40
+ DataCollatorForSeq2Seq,
41
+ HfArgumentParser,
42
+ KerasMetricCallback,
43
+ PushToHubCallback,
44
+ TFAutoModelForSeq2SeqLM,
45
+ TFTrainingArguments,
46
+ create_optimizer,
47
+ set_seed,
48
+ )
49
+ from transformers.trainer_utils import get_last_checkpoint
50
+ from transformers.utils import check_min_version, is_offline_mode, send_example_telemetry
51
+ from transformers.utils.versions import require_version
52
+
53
+
54
+ # region Checking dependencies
55
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
56
+ check_min_version("4.50.0.dev0")
57
+
58
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+ try:
63
+ nltk.data.find("tokenizers/punkt")
64
+ except (LookupError, OSError):
65
+ if is_offline_mode():
66
+ raise LookupError(
67
+ "Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files"
68
+ )
69
+ with FileLock(".lock") as lock:
70
+ nltk.download("punkt", quiet=True)
71
+ # endregion
72
+
73
+
74
+ # region Arguments
75
+ @dataclass
76
+ class ModelArguments:
77
+ """
78
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
79
+ """
80
+
81
+ model_name_or_path: str = field(
82
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
83
+ )
84
+ config_name: Optional[str] = field(
85
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
86
+ )
87
+ tokenizer_name: Optional[str] = field(
88
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
89
+ )
90
+ cache_dir: Optional[str] = field(
91
+ default=None,
92
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
93
+ )
94
+ use_fast_tokenizer: bool = field(
95
+ default=True,
96
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
97
+ )
98
+ model_revision: str = field(
99
+ default="main",
100
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
101
+ )
102
+ token: str = field(
103
+ default=None,
104
+ metadata={
105
+ "help": (
106
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
107
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
108
+ )
109
+ },
110
+ )
111
+ trust_remote_code: bool = field(
112
+ default=False,
113
+ metadata={
114
+ "help": (
115
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
116
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
117
+ " code, as it will execute code present on the Hub on your local machine."
118
+ )
119
+ },
120
+ )
121
+
122
+
123
+ @dataclass
124
+ class DataTrainingArguments:
125
+ """
126
+ Arguments pertaining to what data we are going to input our model for training and eval.
127
+ """
128
+
129
+ dataset_name: Optional[str] = field(
130
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
131
+ )
132
+ dataset_config_name: Optional[str] = field(
133
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
134
+ )
135
+ text_column: Optional[str] = field(
136
+ default=None,
137
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
138
+ )
139
+ summary_column: Optional[str] = field(
140
+ default=None,
141
+ metadata={"help": "The name of the column in the datasets containing the summaries (for summarization)."},
142
+ )
143
+ train_file: Optional[str] = field(
144
+ default=None, metadata={"help": "The input training data file (a jsonlines or csv file)."}
145
+ )
146
+ validation_file: Optional[str] = field(
147
+ default=None,
148
+ metadata={
149
+ "help": (
150
+ "An optional input evaluation data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
151
+ )
152
+ },
153
+ )
154
+ test_file: Optional[str] = field(
155
+ default=None,
156
+ metadata={
157
+ "help": "An optional input test data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
158
+ },
159
+ )
160
+ overwrite_cache: bool = field(
161
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
162
+ )
163
+ preprocessing_num_workers: Optional[int] = field(
164
+ default=None,
165
+ metadata={"help": "The number of processes to use for the preprocessing."},
166
+ )
167
+ max_source_length: Optional[int] = field(
168
+ default=1024,
169
+ metadata={
170
+ "help": (
171
+ "The maximum total input sequence length after tokenization. Sequences longer "
172
+ "than this will be truncated, sequences shorter will be padded."
173
+ )
174
+ },
175
+ )
176
+ max_target_length: Optional[int] = field(
177
+ default=128,
178
+ metadata={
179
+ "help": (
180
+ "The maximum total sequence length for target text after tokenization. Sequences longer "
181
+ "than this will be truncated, sequences shorter will be padded."
182
+ )
183
+ },
184
+ )
185
+ val_max_target_length: Optional[int] = field(
186
+ default=None,
187
+ metadata={
188
+ "help": (
189
+ "The maximum total sequence length for validation target text after tokenization. Sequences longer "
190
+ "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`. "
191
+ "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
192
+ "during ``evaluate`` and ``predict``."
193
+ )
194
+ },
195
+ )
196
+ pad_to_max_length: bool = field(
197
+ default=False,
198
+ metadata={
199
+ "help": (
200
+ "Whether to pad all samples to model maximum sentence length. "
201
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
202
+ "efficient on GPU but very bad for TPU."
203
+ )
204
+ },
205
+ )
206
+ max_train_samples: Optional[int] = field(
207
+ default=None,
208
+ metadata={
209
+ "help": (
210
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
211
+ "value if set."
212
+ )
213
+ },
214
+ )
215
+ max_eval_samples: Optional[int] = field(
216
+ default=None,
217
+ metadata={
218
+ "help": (
219
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
220
+ "value if set."
221
+ )
222
+ },
223
+ )
224
+ max_predict_samples: Optional[int] = field(
225
+ default=None,
226
+ metadata={
227
+ "help": (
228
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
229
+ "value if set."
230
+ )
231
+ },
232
+ )
233
+ num_beams: Optional[int] = field(
234
+ default=1,
235
+ metadata={
236
+ "help": (
237
+ "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
238
+ "which is used during ``evaluate`` and ``predict``."
239
+ )
240
+ },
241
+ )
242
+ ignore_pad_token_for_loss: bool = field(
243
+ default=True,
244
+ metadata={
245
+ "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
246
+ },
247
+ )
248
+ source_prefix: Optional[str] = field(
249
+ default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
250
+ )
251
+
252
+ def __post_init__(self):
253
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
254
+ raise ValueError("Need either a dataset name or a training/validation file.")
255
+ else:
256
+ if self.train_file is not None:
257
+ extension = self.train_file.split(".")[-1]
258
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
259
+ if self.validation_file is not None:
260
+ extension = self.validation_file.split(".")[-1]
261
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
262
+ if self.val_max_target_length is None:
263
+ self.val_max_target_length = self.max_target_length
264
+
265
+
266
+ # endregion
267
+
268
+ # region Dataset name mappings
269
+ summarization_name_mapping = {
270
+ "amazon_reviews_multi": ("review_body", "review_title"),
271
+ "big_patent": ("description", "abstract"),
272
+ "cnn_dailymail": ("article", "highlights"),
273
+ "orange_sum": ("text", "summary"),
274
+ "pn_summary": ("article", "summary"),
275
+ "psc": ("extract_text", "summary_text"),
276
+ "samsum": ("dialogue", "summary"),
277
+ "thaisum": ("body", "summary"),
278
+ "xglue": ("news_body", "news_title"),
279
+ "xsum": ("document", "summary"),
280
+ "wiki_summary": ("article", "highlights"),
281
+ "multi_news": ("document", "summary"),
282
+ }
283
+ # endregion
284
+
285
+
286
+ def main():
287
+ # region Argument parsing
288
+ # See all possible arguments in src/transformers/training_args.py
289
+ # or by passing the --help flag to this script.
290
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
291
+
292
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
293
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
294
+ # If we pass only one argument to the script and it's the path to a json file,
295
+ # let's parse it to get our arguments.
296
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
297
+ else:
298
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
299
+
300
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
301
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
302
+ send_example_telemetry("run_summarization", model_args, data_args, framework="tensorflow")
303
+ # endregion
304
+
305
+ # region Logging
306
+ logging.basicConfig(
307
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
308
+ datefmt="%m/%d/%Y %H:%M:%S",
309
+ handlers=[logging.StreamHandler(sys.stdout)],
310
+ )
311
+ logger.setLevel(logging.INFO)
312
+ datasets.utils.logging.set_verbosity(logging.INFO)
313
+ transformers.utils.logging.set_verbosity(logging.INFO)
314
+
315
+ # Log on each process the small summary:
316
+ logger.info(f"Training/evaluation parameters {training_args}")
317
+ # endregion
318
+
319
+ # region T5 special-casing
320
+ if data_args.source_prefix is None and model_args.model_name_or_path in [
321
+ "google-t5/t5-small",
322
+ "google-t5/t5-base",
323
+ "google-t5/t5-large",
324
+ "google-t5/t5-3b",
325
+ "google-t5/t5-11b",
326
+ ]:
327
+ logger.warning(
328
+ "You're running a t5 model but didn't provide a source prefix, which is the expected, e.g. with "
329
+ "`--source_prefix 'summarize: ' `"
330
+ )
331
+ # endregion
332
+
333
+ # region Detecting last checkpoint
334
+ last_checkpoint = None
335
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
336
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
337
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
338
+ raise ValueError(
339
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
340
+ "Use --overwrite_output_dir to overcome."
341
+ )
342
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
343
+ logger.info(
344
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
345
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
346
+ )
347
+ # endregion
348
+
349
+ # Set seed before initializing model.
350
+ set_seed(training_args.seed)
351
+
352
+ # region Load datasets
353
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
354
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
355
+ # (the dataset will be downloaded automatically from the datasets Hub).
356
+ #
357
+ # For CSV/JSON files this script will use the first column for the full texts and the second column for the
358
+ # summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments).
359
+ #
360
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
361
+ # download the dataset.
362
+ if data_args.dataset_name is not None:
363
+ # Downloading and loading a dataset from the hub.
364
+ raw_datasets = load_dataset(
365
+ data_args.dataset_name,
366
+ data_args.dataset_config_name,
367
+ cache_dir=model_args.cache_dir,
368
+ token=model_args.token,
369
+ trust_remote_code=model_args.trust_remote_code,
370
+ )
371
+ else:
372
+ data_files = {}
373
+ if data_args.train_file is not None:
374
+ data_files["train"] = data_args.train_file
375
+ extension = data_args.train_file.split(".")[-1]
376
+ if data_args.validation_file is not None:
377
+ data_files["validation"] = data_args.validation_file
378
+ extension = data_args.validation_file.split(".")[-1]
379
+ if data_args.test_file is not None:
380
+ data_files["test"] = data_args.test_file
381
+ extension = data_args.test_file.split(".")[-1]
382
+ raw_datasets = load_dataset(
383
+ extension,
384
+ data_files=data_files,
385
+ cache_dir=model_args.cache_dir,
386
+ token=model_args.token,
387
+ )
388
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
389
+ # https://huggingface.co/docs/datasets/loading_datasets.
390
+ # endregion
391
+
392
+ # region Load model config and tokenizer
393
+ #
394
+ # Distributed training:
395
+ # The .from_pretrained methods guarantee that only one local process can concurrently
396
+ # download model & vocab.
397
+
398
+ config = AutoConfig.from_pretrained(
399
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
400
+ cache_dir=model_args.cache_dir,
401
+ revision=model_args.model_revision,
402
+ token=model_args.token,
403
+ trust_remote_code=model_args.trust_remote_code,
404
+ )
405
+ tokenizer = AutoTokenizer.from_pretrained(
406
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
407
+ cache_dir=model_args.cache_dir,
408
+ use_fast=model_args.use_fast_tokenizer,
409
+ revision=model_args.model_revision,
410
+ token=model_args.token,
411
+ trust_remote_code=model_args.trust_remote_code,
412
+ )
413
+
414
+ prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
415
+ # endregion
416
+
417
+ # region Dataset preprocessing
418
+ # We need to tokenize inputs and targets.
419
+ if training_args.do_train:
420
+ column_names = raw_datasets["train"].column_names
421
+ elif training_args.do_eval:
422
+ column_names = raw_datasets["validation"].column_names
423
+ else:
424
+ logger.info("There is nothing to do. Please pass `do_train`, and/or `do_eval`.")
425
+ return
426
+
427
+ # Get the column names for input/target.
428
+ dataset_columns = summarization_name_mapping.get(data_args.dataset_name, None)
429
+ if data_args.text_column is None:
430
+ text_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
431
+ else:
432
+ text_column = data_args.text_column
433
+ if text_column not in column_names:
434
+ raise ValueError(
435
+ f"--text_column' value '{data_args.text_column}' needs to be one of: {', '.join(column_names)}"
436
+ )
437
+ if data_args.summary_column is None:
438
+ summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
439
+ else:
440
+ summary_column = data_args.summary_column
441
+ if summary_column not in column_names:
442
+ raise ValueError(
443
+ f"--summary_column' value '{data_args.summary_column}' needs to be one of: {', '.join(column_names)}"
444
+ )
445
+
446
+ # Temporarily set max_target_length for training.
447
+ max_target_length = data_args.max_target_length
448
+ padding = "max_length" if data_args.pad_to_max_length else False
449
+
450
+ def preprocess_function(examples):
451
+ inputs = examples[text_column]
452
+ targets = examples[summary_column]
453
+ inputs = [prefix + inp for inp in inputs]
454
+ model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True)
455
+
456
+ # Tokenize targets with the `text_target` keyword argument
457
+ labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True)
458
+
459
+ # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
460
+ # padding in the loss.
461
+ if padding == "max_length" and data_args.ignore_pad_token_for_loss:
462
+ labels["input_ids"] = [
463
+ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
464
+ ]
465
+
466
+ model_inputs["labels"] = labels["input_ids"]
467
+ return model_inputs
468
+
469
+ if training_args.do_train:
470
+ if "train" not in raw_datasets:
471
+ raise ValueError("--do_train requires a train dataset")
472
+ train_dataset = raw_datasets["train"]
473
+ if data_args.max_train_samples is not None:
474
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
475
+ train_dataset = train_dataset.select(range(max_train_samples))
476
+ train_dataset = train_dataset.map(
477
+ preprocess_function,
478
+ batched=True,
479
+ num_proc=data_args.preprocessing_num_workers,
480
+ remove_columns=column_names,
481
+ load_from_cache_file=not data_args.overwrite_cache,
482
+ desc="Running tokenizer on train dataset",
483
+ )
484
+ else:
485
+ train_dataset = None
486
+
487
+ if training_args.do_eval:
488
+ max_target_length = data_args.val_max_target_length
489
+ if "validation" not in raw_datasets:
490
+ raise ValueError("--do_eval requires a validation dataset")
491
+ eval_dataset = raw_datasets["validation"]
492
+ if data_args.max_eval_samples is not None:
493
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
494
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
495
+ eval_dataset = eval_dataset.map(
496
+ preprocess_function,
497
+ batched=True,
498
+ num_proc=data_args.preprocessing_num_workers,
499
+ remove_columns=column_names,
500
+ load_from_cache_file=not data_args.overwrite_cache,
501
+ desc="Running tokenizer on validation dataset",
502
+ )
503
+ else:
504
+ eval_dataset = None
505
+ # endregion
506
+
507
+ # region Text preprocessing
508
+ def postprocess_text(preds, labels):
509
+ preds = [pred.strip() for pred in preds]
510
+ labels = [label.strip() for label in labels]
511
+
512
+ # rougeLSum expects newline after each sentence
513
+ preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds]
514
+ labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels]
515
+
516
+ return preds, labels
517
+
518
+ # endregion
519
+
520
+ with training_args.strategy.scope():
521
+ # region Prepare model
522
+ model = TFAutoModelForSeq2SeqLM.from_pretrained(
523
+ model_args.model_name_or_path,
524
+ config=config,
525
+ cache_dir=model_args.cache_dir,
526
+ revision=model_args.model_revision,
527
+ token=model_args.token,
528
+ trust_remote_code=model_args.trust_remote_code,
529
+ )
530
+
531
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
532
+ # on a small vocab and want a smaller embedding size, remove this test.
533
+ embeddings = model.get_input_embeddings()
534
+
535
+ # Matt: This is a temporary workaround as we transition our models to exclusively using Keras embeddings.
536
+ # As soon as the transition is complete, all embeddings should be keras.Embeddings layers, and
537
+ # the weights will always be in embeddings.embeddings.
538
+ if hasattr(embeddings, "embeddings"):
539
+ embedding_size = embeddings.embeddings.shape[0]
540
+ else:
541
+ embedding_size = embeddings.weight.shape[0]
542
+ if len(tokenizer) > embedding_size:
543
+ model.resize_token_embeddings(len(tokenizer))
544
+ # endregion
545
+
546
+ # region Prepare TF Dataset objects
547
+ if model.config.decoder_start_token_id is None:
548
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
549
+
550
+ label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id
551
+ data_collator = DataCollatorForSeq2Seq(
552
+ tokenizer,
553
+ model=model,
554
+ label_pad_token_id=label_pad_token_id,
555
+ pad_to_multiple_of=128, # Reduce the number of unique shapes for XLA, especially for generation
556
+ return_tensors="np",
557
+ )
558
+
559
+ dataset_options = tf.data.Options()
560
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
561
+
562
+ num_replicas = training_args.strategy.num_replicas_in_sync
563
+ total_train_batch_size = training_args.per_device_train_batch_size * num_replicas
564
+ total_eval_batch_size = training_args.per_device_eval_batch_size * num_replicas
565
+
566
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
567
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
568
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
569
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
570
+ # using model.prepare_tf_dataset()
571
+ # For more info see the docs:
572
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
573
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
574
+
575
+ tf_train_dataset = model.prepare_tf_dataset(
576
+ train_dataset,
577
+ collate_fn=data_collator,
578
+ batch_size=total_train_batch_size,
579
+ shuffle=True,
580
+ ).with_options(dataset_options)
581
+ tf_eval_dataset = model.prepare_tf_dataset(
582
+ eval_dataset,
583
+ collate_fn=data_collator,
584
+ batch_size=total_eval_batch_size,
585
+ shuffle=False,
586
+ ).with_options(dataset_options)
587
+ # endregion
588
+
589
+ # region Optimizer, loss and LR scheduling
590
+ num_train_steps = int(len(tf_train_dataset) * training_args.num_train_epochs)
591
+ if training_args.warmup_steps > 0:
592
+ num_warmup_steps = training_args.warmup_steps
593
+ elif training_args.warmup_ratio > 0:
594
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
595
+ else:
596
+ num_warmup_steps = 0
597
+ if training_args.do_train:
598
+ optimizer, lr_schedule = create_optimizer(
599
+ init_lr=training_args.learning_rate,
600
+ num_train_steps=num_train_steps,
601
+ num_warmup_steps=num_warmup_steps,
602
+ adam_beta1=training_args.adam_beta1,
603
+ adam_beta2=training_args.adam_beta2,
604
+ adam_epsilon=training_args.adam_epsilon,
605
+ weight_decay_rate=training_args.weight_decay,
606
+ adam_global_clipnorm=training_args.max_grad_norm,
607
+ )
608
+ else:
609
+ optimizer = "sgd" # Just write anything because we won't be using it
610
+
611
+ # endregion
612
+
613
+ # region Metric and KerasMetricCallback
614
+ if training_args.do_eval:
615
+ metric = evaluate.load("rouge", cache_dir=model_args.cache_dir)
616
+
617
+ if data_args.val_max_target_length is None:
618
+ data_args.val_max_target_length = data_args.max_target_length
619
+
620
+ gen_kwargs = {
621
+ "max_length": data_args.val_max_target_length if data_args is not None else config.max_length,
622
+ "num_beams": data_args.num_beams,
623
+ "no_repeat_ngram_size": 0, # Not supported under XLA right now, and some models set it by default
624
+ }
625
+
626
+ def compute_metrics(preds):
627
+ predictions, labels = preds
628
+ if isinstance(predictions, tuple):
629
+ predictions = predictions[0]
630
+ decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
631
+ labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
632
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
633
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
634
+ metrics = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
635
+ # Only print the mid f-measures, but there are a lot of other statistics in there too!
636
+ metrics = {key: round(val.mid.fmeasure * 100, 4) for key, val in metrics.items()}
637
+ return metrics
638
+
639
+ # The KerasMetricCallback allows metrics that are too complex to write as standard Keras metrics
640
+ # to be computed each epoch. Any Python code can be included in the metric_fn. This is especially
641
+ # useful for metrics like BLEU and ROUGE that perform string comparisons on decoded model outputs.
642
+ # For more information, see the docs at
643
+ # https://huggingface.co/docs/transformers/main_classes/keras_callbacks#transformers.KerasMetricCallback
644
+
645
+ metric_callback = KerasMetricCallback(
646
+ metric_fn=compute_metrics,
647
+ eval_dataset=tf_eval_dataset,
648
+ predict_with_generate=True,
649
+ use_xla_generation=True,
650
+ generate_kwargs=gen_kwargs,
651
+ )
652
+ callbacks = [metric_callback]
653
+ else:
654
+ callbacks = []
655
+ # endregion
656
+
657
+ # region Preparing push_to_hub and model card
658
+ push_to_hub_model_id = training_args.push_to_hub_model_id
659
+ model_name = model_args.model_name_or_path.split("/")[-1]
660
+ if not push_to_hub_model_id:
661
+ if data_args.dataset_name is not None:
662
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}"
663
+ else:
664
+ push_to_hub_model_id = f"{model_name}-finetuned-summarization"
665
+
666
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "summarization"}
667
+ if data_args.dataset_name is not None:
668
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
669
+ if data_args.dataset_config_name is not None:
670
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
671
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
672
+ else:
673
+ model_card_kwargs["dataset"] = data_args.dataset_name
674
+
675
+ if training_args.push_to_hub:
676
+ # Because this training can be quite long, we save once per epoch.
677
+ callbacks.append(
678
+ PushToHubCallback(
679
+ output_dir=training_args.output_dir,
680
+ hub_model_id=push_to_hub_model_id,
681
+ hub_token=training_args.push_to_hub_token,
682
+ tokenizer=tokenizer,
683
+ **model_card_kwargs,
684
+ )
685
+ )
686
+ # endregion
687
+
688
+ # region Training
689
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
690
+ # use this for training unless you specify your own loss function in compile().
691
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
692
+ eval_metrics = None
693
+ if training_args.do_train:
694
+ logger.info("***** Running training *****")
695
+ logger.info(f" Num examples = {len(train_dataset)}")
696
+ logger.info(f" Num Epochs = {training_args.num_train_epochs}")
697
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
698
+ logger.info(f" Total train batch size = {total_train_batch_size}")
699
+ logger.info(f" Total optimization steps = {num_train_steps}")
700
+
701
+ if training_args.xla and not data_args.pad_to_max_length:
702
+ logger.warning(
703
+ "XLA training may be slow at first when --pad_to_max_length is not set "
704
+ "until all possible shapes have been compiled."
705
+ )
706
+ history = model.fit(tf_train_dataset, epochs=int(training_args.num_train_epochs), callbacks=callbacks)
707
+ eval_metrics = {key: val[-1] for key, val in history.history.items()}
708
+ # endregion
709
+
710
+ # region Validation
711
+
712
+ if training_args.do_eval and not training_args.do_train:
713
+ # Do a standalone evaluation run
714
+ logger.info("Evaluation...")
715
+
716
+ # Compiling generation with XLA yields enormous speedups, see https://huggingface.co/blog/tf-xla-generate
717
+ @tf.function(jit_compile=True)
718
+ def generate(**kwargs):
719
+ return model.generate(**kwargs)
720
+
721
+ for batch, labels in tf_eval_dataset:
722
+ batch.update(gen_kwargs)
723
+ generated_tokens = generate(**batch)
724
+ if isinstance(generated_tokens, tuple):
725
+ generated_tokens = generated_tokens[0]
726
+ decoded_preds = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
727
+ labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
728
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
729
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
730
+
731
+ metric.add_batch(predictions=decoded_preds, references=decoded_labels)
732
+
733
+ eval_metrics = metric.compute(use_stemmer=True)
734
+
735
+ result = {key: round(val.mid.fmeasure * 100, 4) for key, val in eval_metrics.items()}
736
+ logger.info(result)
737
+ # endregion
738
+
739
+ if training_args.output_dir is not None and eval_metrics is not None:
740
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
741
+ with open(output_eval_file, "w") as writer:
742
+ writer.write(json.dumps(eval_metrics))
743
+
744
+ if training_args.output_dir is not None and not training_args.push_to_hub:
745
+ # If we're not pushing to hub, at least save a local copy when we're done
746
+ model.save_pretrained(training_args.output_dir)
747
+
748
+
749
+ if __name__ == "__main__":
750
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/test_tensorflow_examples.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import argparse
18
+ import json
19
+ import logging
20
+ import os
21
+ import sys
22
+ from unittest import skip
23
+ from unittest.mock import patch
24
+
25
+ import tensorflow as tf
26
+ from packaging.version import parse
27
+
28
+
29
+ try:
30
+ import tf_keras as keras
31
+ except (ModuleNotFoundError, ImportError):
32
+ import keras
33
+
34
+ if parse(keras.__version__).major > 2:
35
+ raise ValueError(
36
+ "Your currently installed version of Keras is Keras 3, but this is not yet supported in "
37
+ "Transformers. Please install the backwards-compatible tf-keras package with "
38
+ "`pip install tf-keras`."
39
+ )
40
+
41
+ from transformers.testing_utils import TestCasePlus, get_gpu_count, slow
42
+
43
+
44
+ SRC_DIRS = [
45
+ os.path.join(os.path.dirname(__file__), dirname)
46
+ for dirname in [
47
+ "text-generation",
48
+ "text-classification",
49
+ "token-classification",
50
+ "language-modeling",
51
+ "multiple-choice",
52
+ "question-answering",
53
+ "summarization",
54
+ "translation",
55
+ "image-classification",
56
+ ]
57
+ ]
58
+ sys.path.extend(SRC_DIRS)
59
+
60
+
61
+ if SRC_DIRS is not None:
62
+ import run_clm
63
+ import run_image_classification
64
+ import run_mlm
65
+ import run_ner
66
+ import run_qa as run_squad
67
+ import run_summarization
68
+ import run_swag
69
+ import run_text_classification
70
+ import run_translation
71
+
72
+
73
+ logging.basicConfig(level=logging.DEBUG)
74
+
75
+ logger = logging.getLogger()
76
+
77
+
78
+ def get_setup_file():
79
+ parser = argparse.ArgumentParser()
80
+ parser.add_argument("-f")
81
+ args = parser.parse_args()
82
+ return args.f
83
+
84
+
85
+ def get_results(output_dir):
86
+ results = {}
87
+ path = os.path.join(output_dir, "all_results.json")
88
+ if os.path.exists(path):
89
+ with open(path, "r") as f:
90
+ results = json.load(f)
91
+ else:
92
+ raise ValueError(f"can't find {path}")
93
+ return results
94
+
95
+
96
+ def is_cuda_available():
97
+ return bool(tf.config.list_physical_devices("GPU"))
98
+
99
+
100
+ stream_handler = logging.StreamHandler(sys.stdout)
101
+ logger.addHandler(stream_handler)
102
+
103
+
104
+ class ExamplesTests(TestCasePlus):
105
+ @skip("Skipping until shape inference for to_tf_dataset PR is merged.")
106
+ def test_run_text_classification(self):
107
+ tmp_dir = self.get_auto_remove_tmp_dir()
108
+ testargs = f"""
109
+ run_text_classification.py
110
+ --model_name_or_path distilbert/distilbert-base-uncased
111
+ --output_dir {tmp_dir}
112
+ --overwrite_output_dir
113
+ --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
114
+ --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
115
+ --do_train
116
+ --do_eval
117
+ --per_device_train_batch_size=2
118
+ --per_device_eval_batch_size=1
119
+ --learning_rate=1e-4
120
+ --max_steps=10
121
+ --warmup_steps=2
122
+ --seed=42
123
+ --max_seq_length=128
124
+ """.split()
125
+
126
+ if is_cuda_available():
127
+ testargs.append("--fp16")
128
+
129
+ with patch.object(sys, "argv", testargs):
130
+ run_text_classification.main()
131
+ # Reset the mixed precision policy so we don't break other tests
132
+ keras.mixed_precision.set_global_policy("float32")
133
+ result = get_results(tmp_dir)
134
+ self.assertGreaterEqual(result["eval_accuracy"], 0.75)
135
+
136
+ def test_run_clm(self):
137
+ tmp_dir = self.get_auto_remove_tmp_dir()
138
+ testargs = f"""
139
+ run_clm.py
140
+ --model_name_or_path distilbert/distilgpt2
141
+ --train_file ./tests/fixtures/sample_text.txt
142
+ --validation_file ./tests/fixtures/sample_text.txt
143
+ --do_train
144
+ --do_eval
145
+ --block_size 128
146
+ --per_device_train_batch_size 2
147
+ --per_device_eval_batch_size 1
148
+ --num_train_epochs 2
149
+ --output_dir {tmp_dir}
150
+ --overwrite_output_dir
151
+ """.split()
152
+
153
+ if len(tf.config.list_physical_devices("GPU")) > 1:
154
+ # Skipping because there are not enough batches to train the model + would need a drop_last to work.
155
+ return
156
+
157
+ with patch.object(sys, "argv", testargs):
158
+ run_clm.main()
159
+ result = get_results(tmp_dir)
160
+ self.assertLess(result["eval_perplexity"], 100)
161
+
162
+ def test_run_mlm(self):
163
+ tmp_dir = self.get_auto_remove_tmp_dir()
164
+ testargs = f"""
165
+ run_mlm.py
166
+ --model_name_or_path distilbert/distilroberta-base
167
+ --train_file ./tests/fixtures/sample_text.txt
168
+ --validation_file ./tests/fixtures/sample_text.txt
169
+ --max_seq_length 64
170
+ --output_dir {tmp_dir}
171
+ --overwrite_output_dir
172
+ --do_train
173
+ --do_eval
174
+ --prediction_loss_only
175
+ --num_train_epochs=1
176
+ --learning_rate=1e-4
177
+ """.split()
178
+
179
+ with patch.object(sys, "argv", testargs):
180
+ run_mlm.main()
181
+ result = get_results(tmp_dir)
182
+ self.assertLess(result["eval_perplexity"], 42)
183
+
184
+ def test_run_ner(self):
185
+ # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
186
+ epochs = 7 if get_gpu_count() > 1 else 2
187
+
188
+ tmp_dir = self.get_auto_remove_tmp_dir()
189
+ testargs = f"""
190
+ run_ner.py
191
+ --model_name_or_path google-bert/bert-base-uncased
192
+ --train_file tests/fixtures/tests_samples/conll/sample.json
193
+ --validation_file tests/fixtures/tests_samples/conll/sample.json
194
+ --output_dir {tmp_dir}
195
+ --overwrite_output_dir
196
+ --do_train
197
+ --do_eval
198
+ --warmup_steps=2
199
+ --learning_rate=2e-4
200
+ --per_device_train_batch_size=2
201
+ --per_device_eval_batch_size=2
202
+ --num_train_epochs={epochs}
203
+ --seed 7
204
+ """.split()
205
+
206
+ with patch.object(sys, "argv", testargs):
207
+ run_ner.main()
208
+ result = get_results(tmp_dir)
209
+ self.assertGreaterEqual(result["accuracy"], 0.75)
210
+
211
+ def test_run_squad(self):
212
+ tmp_dir = self.get_auto_remove_tmp_dir()
213
+ testargs = f"""
214
+ run_qa.py
215
+ --model_name_or_path google-bert/bert-base-uncased
216
+ --version_2_with_negative
217
+ --train_file tests/fixtures/tests_samples/SQUAD/sample.json
218
+ --validation_file tests/fixtures/tests_samples/SQUAD/sample.json
219
+ --output_dir {tmp_dir}
220
+ --overwrite_output_dir
221
+ --max_steps=10
222
+ --warmup_steps=2
223
+ --do_train
224
+ --do_eval
225
+ --learning_rate=2e-4
226
+ --per_device_train_batch_size=2
227
+ --per_device_eval_batch_size=1
228
+ """.split()
229
+
230
+ with patch.object(sys, "argv", testargs):
231
+ run_squad.main()
232
+ result = get_results(tmp_dir)
233
+ self.assertGreaterEqual(result["f1"], 30)
234
+ self.assertGreaterEqual(result["exact"], 30)
235
+
236
+ def test_run_swag(self):
237
+ tmp_dir = self.get_auto_remove_tmp_dir()
238
+ testargs = f"""
239
+ run_swag.py
240
+ --model_name_or_path google-bert/bert-base-uncased
241
+ --train_file tests/fixtures/tests_samples/swag/sample.json
242
+ --validation_file tests/fixtures/tests_samples/swag/sample.json
243
+ --output_dir {tmp_dir}
244
+ --overwrite_output_dir
245
+ --max_steps=20
246
+ --warmup_steps=2
247
+ --do_train
248
+ --do_eval
249
+ --learning_rate=2e-4
250
+ --per_device_train_batch_size=2
251
+ --per_device_eval_batch_size=1
252
+ """.split()
253
+
254
+ with patch.object(sys, "argv", testargs):
255
+ run_swag.main()
256
+ result = get_results(tmp_dir)
257
+ self.assertGreaterEqual(result["val_accuracy"], 0.8)
258
+
259
+ @slow
260
+ def test_run_summarization(self):
261
+ tmp_dir = self.get_auto_remove_tmp_dir()
262
+ testargs = f"""
263
+ run_summarization.py
264
+ --model_name_or_path google-t5/t5-small
265
+ --train_file tests/fixtures/tests_samples/xsum/sample.json
266
+ --validation_file tests/fixtures/tests_samples/xsum/sample.json
267
+ --output_dir {tmp_dir}
268
+ --overwrite_output_dir
269
+ --max_steps=50
270
+ --warmup_steps=8
271
+ --do_train
272
+ --do_eval
273
+ --learning_rate=2e-4
274
+ --per_device_train_batch_size=2
275
+ --per_device_eval_batch_size=1
276
+ """.split()
277
+
278
+ with patch.object(sys, "argv", testargs):
279
+ run_summarization.main()
280
+ result = get_results(tmp_dir)
281
+ self.assertGreaterEqual(result["rouge1"], 10)
282
+ self.assertGreaterEqual(result["rouge2"], 2)
283
+ self.assertGreaterEqual(result["rougeL"], 7)
284
+ self.assertGreaterEqual(result["rougeLsum"], 7)
285
+
286
+ @slow
287
+ def test_run_translation(self):
288
+ tmp_dir = self.get_auto_remove_tmp_dir()
289
+ testargs = f"""
290
+ run_translation.py
291
+ --model_name_or_path Rocketknight1/student_marian_en_ro_6_1
292
+ --source_lang en
293
+ --target_lang ro
294
+ --train_file tests/fixtures/tests_samples/wmt16/sample.json
295
+ --validation_file tests/fixtures/tests_samples/wmt16/sample.json
296
+ --output_dir {tmp_dir}
297
+ --overwrite_output_dir
298
+ --warmup_steps=8
299
+ --do_train
300
+ --do_eval
301
+ --learning_rate=3e-3
302
+ --num_train_epochs 12
303
+ --per_device_train_batch_size=2
304
+ --per_device_eval_batch_size=1
305
+ --source_lang en_XX
306
+ --target_lang ro_RO
307
+ """.split()
308
+
309
+ with patch.object(sys, "argv", testargs):
310
+ run_translation.main()
311
+ result = get_results(tmp_dir)
312
+ self.assertGreaterEqual(result["bleu"], 30)
313
+
314
+ def test_run_image_classification(self):
315
+ tmp_dir = self.get_auto_remove_tmp_dir()
316
+ testargs = f"""
317
+ run_image_classification.py
318
+ --dataset_name hf-internal-testing/cats_vs_dogs_sample
319
+ --trust_remote_code
320
+ --model_name_or_path microsoft/resnet-18
321
+ --do_train
322
+ --do_eval
323
+ --learning_rate 1e-4
324
+ --per_device_train_batch_size 2
325
+ --per_device_eval_batch_size 1
326
+ --output_dir {tmp_dir}
327
+ --overwrite_output_dir
328
+ --dataloader_num_workers 16
329
+ --num_train_epochs 2
330
+ --train_val_split 0.1
331
+ --seed 42
332
+ --ignore_mismatched_sizes True
333
+ """.split()
334
+
335
+ with patch.object(sys, "argv", testargs):
336
+ run_image_classification.main()
337
+ result = get_results(tmp_dir)
338
+ self.assertGreaterEqual(result["accuracy"], 0.7)
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Text classification examples
18
+
19
+ This folder contains some scripts showing examples of *text classification* with the 🤗 Transformers library.
20
+ For straightforward use-cases you may be able to use these scripts without modification, although we have also
21
+ included comments in the code to indicate areas that you may need to adapt to your own projects.
22
+
23
+ ## run_text_classification.py
24
+
25
+ This script handles perhaps the single most common use-case for this entire library: Training an NLP classifier
26
+ on your own training data. This can be whatever you want - you could classify text as abusive/hateful or
27
+ allowable, or forum posts as spam or not-spam, or classify the genre of a headline as politics, sports or any
28
+ number of other categories. Any task that involves classifying natural language into two or more different categories
29
+ can work with this! You can even do regression, such as predicting the score on a 1-10 scale that a user gave,
30
+ given the text of their review.
31
+
32
+ The preferred input format is either a CSV or newline-delimited JSON file that contains a `sentence1` and
33
+ `label` field. If your task involves comparing two texts (for example, if your classifier
34
+ is deciding whether two sentences are paraphrases of each other, or were written by the same author) then you should also include a `sentence2` field in each example. If you do not have a `sentence1` field then the script will assume the non-label fields are the input text, which
35
+ may not always be what you want, especially if you have more than two fields!
36
+
37
+ Here is a snippet of a valid input JSON file, though note that your texts can be much longer than these, and are not constrained
38
+ (despite the field name) to being single grammatical sentences:
39
+ ```json
40
+ {"sentence1": "COVID-19 vaccine updates: How is the rollout proceeding?", "label": "news"}
41
+ {"sentence1": "Manchester United celebrates Europa League success", "label": "sports"}
42
+ ```
43
+
44
+ ### Usage notes
45
+ If your inputs are long (more than ~60-70 words), you may wish to increase the `--max_seq_length` argument
46
+ beyond the default value of 128. The maximum supported value for most models is 512 (about 200-300 words),
47
+ and some can handle even longer. This will come at a cost in runtime and memory use, however.
48
+
49
+ We assume that your labels represent *categories*, even if they are integers, since text classification
50
+ is a much more common task than text regression. If your labels are floats, however, the script will assume
51
+ you want to do regression. This is something you can edit yourself if your use-case requires it!
52
+
53
+ After training, the model will be saved to `--output_dir`. Once your model is trained, you can get predictions
54
+ by calling the script without a `--train_file` or `--validation_file`; simply pass it the output_dir containing
55
+ the trained model and a `--test_file` and it will write its predictions to a text file for you.
56
+
57
+ ### Multi-GPU and TPU usage
58
+
59
+ By default, the script uses a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
60
+ can also be used by passing the name of the TPU resource with the `--tpu` argument.
61
+
62
+ ### Memory usage and data loading
63
+
64
+ One thing to note is that all data is loaded into memory in this script. Most text classification datasets are small
65
+ enough that this is not an issue, but if you have a very large dataset you will need to modify the script to handle
66
+ data streaming. This is particularly challenging for TPUs, given the stricter requirements and the sheer volume of data
67
+ required to keep them fed. A full explanation of all the possible pitfalls is a bit beyond this example script and
68
+ README, but for more information you can see the 'Input Datasets' section of
69
+ [this document](https://www.tensorflow.org/guide/tpu).
70
+
71
+ ### Example command
72
+ ```bash
73
+ python run_text_classification.py \
74
+ --model_name_or_path distilbert/distilbert-base-cased \
75
+ --train_file training_data.json \
76
+ --validation_file validation_data.json \
77
+ --output_dir output/ \
78
+ --test_file data_to_predict.json \
79
+ --do_train \
80
+ --do_eval \
81
+ --do_predict
82
+ ```
83
+
84
+ ## run_glue.py
85
+
86
+ This script handles training on the GLUE dataset for various text classification and regression tasks. The GLUE datasets will be loaded automatically, so you only need to specify the task you want (with the `--task_name` argument). You can also supply your own files for prediction with the `--predict_file` argument, for example if you want to train a model on GLUE for e.g. paraphrase detection and then predict whether your own data contains paraphrases or not. Please ensure the names of your input fields match the names of the features in the relevant GLUE dataset - you can see a list of the column names in the `task_to_keys` dict in the `run_glue.py` file.
87
+
88
+ ### Usage notes
89
+
90
+ The `--do_train`, `--do_eval` and `--do_predict` arguments control whether training, evaluations or predictions are performed. After training, the model will be saved to `--output_dir`. Once your model is trained, you can call the script without the `--do_train` or `--do_eval` arguments to quickly get predictions from your saved model.
91
+
92
+ ### Multi-GPU and TPU usage
93
+
94
+ By default, the script uses a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
95
+ can also be used by passing the name of the TPU resource with the `--tpu` argument.
96
+
97
+ ### Memory usage and data loading
98
+
99
+ One thing to note is that all data is loaded into memory in this script. Most text classification datasets are small
100
+ enough that this is not an issue, but if you have a very large dataset you will need to modify the script to handle
101
+ data streaming. This is particularly challenging for TPUs, given the stricter requirements and the sheer volume of data
102
+ required to keep them fed. A full explanation of all the possible pitfalls is a bit beyond this example script and
103
+ README, but for more information you can see the 'Input Datasets' section of
104
+ [this document](https://www.tensorflow.org/guide/tpu).
105
+
106
+ ### Example command
107
+ ```bash
108
+ python run_glue.py \
109
+ --model_name_or_path distilbert/distilbert-base-cased \
110
+ --task_name mnli \
111
+ --do_train \
112
+ --do_eval \
113
+ --do_predict \
114
+ --predict_file data_to_predict.json
115
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ datasets >= 1.1.3
2
+ sentencepiece != 0.1.92
3
+ protobuf
4
+ tensorflow >= 2.3
5
+ evaluate >= 0.2.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/run_glue.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2020 The HuggingFace Inc. 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
+ """Finetuning the library models for sequence classification on GLUE."""
17
+ # You can also adapt this script on your own text classification task. Pointers for this are left as comments.
18
+
19
+ import json
20
+ import logging
21
+ import os
22
+ import sys
23
+ from dataclasses import dataclass, field
24
+ from typing import Optional
25
+
26
+ import evaluate
27
+ import numpy as np
28
+ import tensorflow as tf
29
+ from datasets import load_dataset
30
+
31
+ import transformers
32
+ from transformers import (
33
+ AutoConfig,
34
+ AutoTokenizer,
35
+ DataCollatorWithPadding,
36
+ DefaultDataCollator,
37
+ HfArgumentParser,
38
+ PretrainedConfig,
39
+ PushToHubCallback,
40
+ TFAutoModelForSequenceClassification,
41
+ TFTrainingArguments,
42
+ create_optimizer,
43
+ set_seed,
44
+ )
45
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
46
+ from transformers.utils import check_min_version, send_example_telemetry
47
+
48
+
49
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
50
+ check_min_version("4.50.0.dev0")
51
+
52
+ task_to_keys = {
53
+ "cola": ("sentence", None),
54
+ "mnli": ("premise", "hypothesis"),
55
+ "mrpc": ("sentence1", "sentence2"),
56
+ "qnli": ("question", "sentence"),
57
+ "qqp": ("question1", "question2"),
58
+ "rte": ("sentence1", "sentence2"),
59
+ "sst2": ("sentence", None),
60
+ "stsb": ("sentence1", "sentence2"),
61
+ "wnli": ("sentence1", "sentence2"),
62
+ }
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+
67
+ # region Command-line arguments
68
+ @dataclass
69
+ class DataTrainingArguments:
70
+ """
71
+ Arguments pertaining to what data we are going to input our model for training and eval.
72
+
73
+ Using `HfArgumentParser` we can turn this class
74
+ into argparse arguments to be able to specify them on
75
+ the command line.
76
+ """
77
+
78
+ task_name: str = field(
79
+ metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())},
80
+ )
81
+ predict_file: str = field(
82
+ metadata={"help": "A file containing user-supplied examples to make predictions for"},
83
+ default=None,
84
+ )
85
+ max_seq_length: int = field(
86
+ default=128,
87
+ metadata={
88
+ "help": (
89
+ "The maximum total input sequence length after tokenization. Sequences longer "
90
+ "than this will be truncated, sequences shorter will be padded."
91
+ )
92
+ },
93
+ )
94
+ overwrite_cache: bool = field(
95
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
96
+ )
97
+ pad_to_max_length: bool = field(
98
+ default=False,
99
+ metadata={
100
+ "help": (
101
+ "Whether to pad all samples to `max_seq_length`. "
102
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
103
+ )
104
+ },
105
+ )
106
+ max_train_samples: Optional[int] = field(
107
+ default=None,
108
+ metadata={
109
+ "help": (
110
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
111
+ "value if set."
112
+ )
113
+ },
114
+ )
115
+ max_eval_samples: Optional[int] = field(
116
+ default=None,
117
+ metadata={
118
+ "help": (
119
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
120
+ "value if set."
121
+ )
122
+ },
123
+ )
124
+ max_predict_samples: Optional[int] = field(
125
+ default=None,
126
+ metadata={
127
+ "help": (
128
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
129
+ "value if set."
130
+ )
131
+ },
132
+ )
133
+
134
+ def __post_init__(self):
135
+ self.task_name = self.task_name.lower()
136
+ if self.task_name not in task_to_keys.keys():
137
+ raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys()))
138
+
139
+
140
+ @dataclass
141
+ class ModelArguments:
142
+ """
143
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
144
+ """
145
+
146
+ model_name_or_path: str = field(
147
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
148
+ )
149
+ config_name: Optional[str] = field(
150
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
151
+ )
152
+ tokenizer_name: Optional[str] = field(
153
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
154
+ )
155
+ cache_dir: Optional[str] = field(
156
+ default=None,
157
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
158
+ )
159
+ use_fast_tokenizer: bool = field(
160
+ default=True,
161
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
162
+ )
163
+ model_revision: str = field(
164
+ default="main",
165
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
166
+ )
167
+ token: str = field(
168
+ default=None,
169
+ metadata={
170
+ "help": (
171
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
172
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
173
+ )
174
+ },
175
+ )
176
+ trust_remote_code: bool = field(
177
+ default=False,
178
+ metadata={
179
+ "help": (
180
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option "
181
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will "
182
+ "execute code present on the Hub on your local machine."
183
+ )
184
+ },
185
+ )
186
+
187
+
188
+ # endregion
189
+
190
+
191
+ def main():
192
+ # region Argument parsing
193
+ # See all possible arguments in src/transformers/training_args.py
194
+ # or by passing the --help flag to this script.
195
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
196
+
197
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
198
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
199
+ # If we pass only one argument to the script and it's the path to a json file,
200
+ # let's parse it to get our arguments.
201
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
202
+ else:
203
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
204
+
205
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
206
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
207
+ send_example_telemetry("run_glue", model_args, data_args, framework="tensorflow")
208
+
209
+ if not (training_args.do_train or training_args.do_eval or training_args.do_predict):
210
+ exit("Must specify at least one of --do_train, --do_eval or --do_predict!")
211
+ # endregion
212
+
213
+ # region Checkpoints
214
+ checkpoint = None
215
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
216
+ checkpoint = get_last_checkpoint(training_args.output_dir)
217
+ if checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
218
+ raise ValueError(
219
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
220
+ "Use --overwrite_output_dir to overcome."
221
+ )
222
+ elif checkpoint is not None and training_args.resume_from_checkpoint is None:
223
+ logger.info(
224
+ f"Checkpoint detected, resuming training at {checkpoint}. To avoid this behavior, change "
225
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
226
+ )
227
+ # endregion
228
+
229
+ # region Logging
230
+ logging.basicConfig(
231
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
232
+ datefmt="%m/%d/%Y %H:%M:%S",
233
+ handlers=[logging.StreamHandler(sys.stdout)],
234
+ )
235
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
236
+
237
+ # Set the verbosity to info of the Transformers logger (on main process only):
238
+ if is_main_process(training_args.local_rank):
239
+ transformers.utils.logging.set_verbosity_info()
240
+ transformers.utils.logging.enable_default_handler()
241
+ transformers.utils.logging.enable_explicit_format()
242
+ logger.info(f"Training/evaluation parameters {training_args}")
243
+ # endregion
244
+
245
+ # region Dataset and labels
246
+ # Set seed before initializing model.
247
+ set_seed(training_args.seed)
248
+
249
+ # Downloading and loading a dataset from the hub. In distributed training, the load_dataset function guarantee
250
+ # that only one local process can concurrently download the dataset.
251
+ datasets = load_dataset(
252
+ "nyu-mll/glue",
253
+ data_args.task_name,
254
+ cache_dir=model_args.cache_dir,
255
+ token=model_args.token,
256
+ )
257
+ # See more about loading any type of standard or custom dataset at
258
+ # https://huggingface.co/docs/datasets/loading_datasets.
259
+
260
+ is_regression = data_args.task_name == "stsb"
261
+ if not is_regression:
262
+ label_list = datasets["train"].features["label"].names
263
+ num_labels = len(label_list)
264
+ else:
265
+ num_labels = 1
266
+
267
+ if data_args.predict_file is not None:
268
+ logger.info("Preparing user-supplied file for predictions...")
269
+
270
+ data_files = {"data": data_args.predict_file}
271
+
272
+ for key in data_files.keys():
273
+ logger.info(f"Loading a local file for {key}: {data_files[key]}")
274
+
275
+ if data_args.predict_file.endswith(".csv"):
276
+ # Loading a dataset from local csv files
277
+ user_dataset = load_dataset("csv", data_files=data_files, cache_dir=model_args.cache_dir)
278
+ else:
279
+ # Loading a dataset from local json files
280
+ user_dataset = load_dataset("json", data_files=data_files, cache_dir=model_args.cache_dir)
281
+ needed_keys = task_to_keys[data_args.task_name]
282
+ for key in needed_keys:
283
+ assert key in user_dataset["data"].features, f"Your supplied predict_file is missing the {key} key!"
284
+ datasets["user_data"] = user_dataset["data"]
285
+ # endregion
286
+
287
+ # region Load model config and tokenizer
288
+ #
289
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
290
+ # download model & vocab.
291
+ config = AutoConfig.from_pretrained(
292
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
293
+ num_labels=num_labels,
294
+ finetuning_task=data_args.task_name,
295
+ cache_dir=model_args.cache_dir,
296
+ revision=model_args.model_revision,
297
+ token=model_args.token,
298
+ trust_remote_code=model_args.trust_remote_code,
299
+ )
300
+ tokenizer = AutoTokenizer.from_pretrained(
301
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
302
+ cache_dir=model_args.cache_dir,
303
+ use_fast=model_args.use_fast_tokenizer,
304
+ revision=model_args.model_revision,
305
+ token=model_args.token,
306
+ trust_remote_code=model_args.trust_remote_code,
307
+ )
308
+ # endregion
309
+
310
+ # region Dataset preprocessing
311
+ sentence1_key, sentence2_key = task_to_keys[data_args.task_name]
312
+
313
+ # Padding strategy
314
+ if data_args.pad_to_max_length:
315
+ padding = "max_length"
316
+ else:
317
+ # We will pad later, dynamically at batch creation, to the max sequence length in each batch
318
+ padding = False
319
+
320
+ # Some models have set the order of the labels to use, so let's make sure we do use it.
321
+ label_to_id = None
322
+ if config.label2id != PretrainedConfig(num_labels=num_labels).label2id and not is_regression:
323
+ # Some have all caps in their config, some don't.
324
+ label_name_to_id = {k.lower(): v for k, v in config.label2id.items()}
325
+ if sorted(label_name_to_id.keys()) == sorted(label_list):
326
+ label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)}
327
+ else:
328
+ logger.warning(
329
+ "Your model seems to have been trained with labels, but they don't match the dataset: "
330
+ f"model labels: {sorted(label_name_to_id.keys())}, dataset labels: {sorted(label_list)}."
331
+ "\nIgnoring the model labels as a result.",
332
+ )
333
+ label_to_id = {label: i for i, label in enumerate(label_list)}
334
+ if label_to_id is not None:
335
+ config.label2id = label_to_id
336
+ config.id2label = {id: label for label, id in config.label2id.items()}
337
+ elif data_args.task_name is not None and not is_regression:
338
+ config.label2id = {l: i for i, l in enumerate(label_list)}
339
+ config.id2label = {id: label for label, id in config.label2id.items()}
340
+
341
+ if data_args.max_seq_length > tokenizer.model_max_length:
342
+ logger.warning(
343
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the "
344
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
345
+ )
346
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
347
+
348
+ def preprocess_function(examples):
349
+ # Tokenize the texts
350
+ args = (
351
+ (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
352
+ )
353
+ result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)
354
+
355
+ return result
356
+
357
+ datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache)
358
+
359
+ if data_args.pad_to_max_length:
360
+ data_collator = DefaultDataCollator(return_tensors="np")
361
+ else:
362
+ data_collator = DataCollatorWithPadding(tokenizer, return_tensors="np")
363
+ # endregion
364
+
365
+ # region Metric function
366
+ metric = evaluate.load("glue", data_args.task_name, cache_dir=model_args.cache_dir)
367
+
368
+ def compute_metrics(preds, label_ids):
369
+ preds = preds["logits"]
370
+ preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
371
+ result = metric.compute(predictions=preds, references=label_ids)
372
+ if len(result) > 1:
373
+ result["combined_score"] = np.mean(list(result.values())).item()
374
+ return result
375
+
376
+ # endregion
377
+
378
+ with training_args.strategy.scope():
379
+ # region Load pretrained model
380
+ if checkpoint is None:
381
+ model_path = model_args.model_name_or_path
382
+ else:
383
+ model_path = checkpoint
384
+ model = TFAutoModelForSequenceClassification.from_pretrained(
385
+ model_path,
386
+ config=config,
387
+ cache_dir=model_args.cache_dir,
388
+ revision=model_args.model_revision,
389
+ token=model_args.token,
390
+ trust_remote_code=model_args.trust_remote_code,
391
+ )
392
+ # endregion
393
+
394
+ # region Convert data to a tf.data.Dataset
395
+ dataset_options = tf.data.Options()
396
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
397
+ num_replicas = training_args.strategy.num_replicas_in_sync
398
+
399
+ tf_data = {}
400
+ max_samples = {
401
+ "train": data_args.max_train_samples,
402
+ "validation": data_args.max_eval_samples,
403
+ "validation_matched": data_args.max_eval_samples,
404
+ "validation_mismatched": data_args.max_eval_samples,
405
+ "test": data_args.max_predict_samples,
406
+ "test_matched": data_args.max_predict_samples,
407
+ "test_mismatched": data_args.max_predict_samples,
408
+ "user_data": None,
409
+ }
410
+ for key in datasets.keys():
411
+ if key == "train" or key.startswith("validation"):
412
+ assert "label" in datasets[key].features, f"Missing labels from {key} data!"
413
+ if key == "train":
414
+ shuffle = True
415
+ batch_size = training_args.per_device_train_batch_size * num_replicas
416
+ else:
417
+ shuffle = False
418
+ batch_size = training_args.per_device_eval_batch_size * num_replicas
419
+ samples_limit = max_samples[key]
420
+ dataset = datasets[key]
421
+ if samples_limit is not None:
422
+ dataset = dataset.select(range(samples_limit))
423
+
424
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
425
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
426
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
427
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
428
+ # using model.prepare_tf_dataset()
429
+ # For more info see the docs:
430
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
431
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
432
+ data = model.prepare_tf_dataset(
433
+ dataset,
434
+ shuffle=shuffle,
435
+ batch_size=batch_size,
436
+ collate_fn=data_collator,
437
+ tokenizer=tokenizer,
438
+ )
439
+ data = data.with_options(dataset_options)
440
+ tf_data[key] = data
441
+ # endregion
442
+
443
+ # region Optimizer, loss and compilation
444
+ if training_args.do_train:
445
+ num_train_steps = len(tf_data["train"]) * training_args.num_train_epochs
446
+ if training_args.warmup_steps > 0:
447
+ num_warmup_steps = training_args.warmup_steps
448
+ elif training_args.warmup_ratio > 0:
449
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
450
+ else:
451
+ num_warmup_steps = 0
452
+
453
+ optimizer, schedule = create_optimizer(
454
+ init_lr=training_args.learning_rate,
455
+ num_train_steps=num_train_steps,
456
+ num_warmup_steps=num_warmup_steps,
457
+ adam_beta1=training_args.adam_beta1,
458
+ adam_beta2=training_args.adam_beta2,
459
+ adam_epsilon=training_args.adam_epsilon,
460
+ weight_decay_rate=training_args.weight_decay,
461
+ adam_global_clipnorm=training_args.max_grad_norm,
462
+ )
463
+ else:
464
+ optimizer = "sgd" # Just write anything because we won't be using it
465
+ if is_regression:
466
+ metrics = []
467
+ else:
468
+ metrics = ["accuracy"]
469
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
470
+ # use this for training unless you specify your own loss function in compile().
471
+ model.compile(optimizer=optimizer, metrics=metrics, jit_compile=training_args.xla)
472
+ # endregion
473
+
474
+ # region Preparing push_to_hub and model card
475
+ push_to_hub_model_id = training_args.push_to_hub_model_id
476
+ model_name = model_args.model_name_or_path.split("/")[-1]
477
+ if not push_to_hub_model_id:
478
+ push_to_hub_model_id = f"{model_name}-finetuned-glue"
479
+
480
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"}
481
+ model_card_kwargs["task_name"] = data_args.task_name
482
+
483
+ if training_args.push_to_hub:
484
+ callbacks = [
485
+ PushToHubCallback(
486
+ output_dir=training_args.output_dir,
487
+ hub_model_id=push_to_hub_model_id,
488
+ hub_token=training_args.push_to_hub_token,
489
+ tokenizer=tokenizer,
490
+ **model_card_kwargs,
491
+ )
492
+ ]
493
+ else:
494
+ callbacks = []
495
+ # endregion
496
+
497
+ # region Training and validation
498
+ if training_args.do_train:
499
+ if training_args.do_eval and not data_args.task_name == "mnli":
500
+ # Do both evaluation and training in the Keras fit loop, unless the task is MNLI
501
+ # because MNLI has two validation sets
502
+ validation_data = tf_data["validation"]
503
+ else:
504
+ validation_data = None
505
+ model.fit(
506
+ tf_data["train"],
507
+ validation_data=validation_data,
508
+ epochs=int(training_args.num_train_epochs),
509
+ callbacks=callbacks,
510
+ )
511
+ # endregion
512
+
513
+ # region Evaluation
514
+ if training_args.do_eval:
515
+ # We normally do validation as part of the Keras fit loop, but we run it independently
516
+ # if there was no fit() step (because we didn't train the model) or if the task is MNLI,
517
+ # because MNLI has a separate validation-mismatched validation set
518
+
519
+ # In this example, we compute advanced metrics only at the end of training, and only compute
520
+ # loss and accuracy on the validation set each epoch, but
521
+ # if you'd like to compute metrics every epoch that are too complex to be written as
522
+ # standard Keras metrics, you can use our KerasMetricCallback. See
523
+ # https://huggingface.co/docs/transformers/main/en/main_classes/keras_callbacks
524
+ logger.info("*** Evaluate ***")
525
+
526
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
527
+ if data_args.task_name == "mnli":
528
+ tasks = ["mnli", "mnli-mm"]
529
+ tf_datasets = [tf_data["validation_matched"], tf_data["validation_mismatched"]]
530
+ raw_datasets = [datasets["validation_matched"], datasets["validation_mismatched"]]
531
+ else:
532
+ tasks = [data_args.task_name]
533
+ tf_datasets = [tf_data["validation"]]
534
+ raw_datasets = [datasets["validation"]]
535
+
536
+ for raw_dataset, tf_dataset, task in zip(raw_datasets, tf_datasets, tasks):
537
+ eval_predictions = model.predict(tf_dataset)
538
+ eval_metrics = compute_metrics(eval_predictions, raw_dataset["label"])
539
+ print(f"Evaluation metrics ({task}):")
540
+ print(eval_metrics)
541
+ if training_args.output_dir is not None:
542
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
543
+ with open(output_eval_file, "w") as writer:
544
+ writer.write(json.dumps(eval_metrics))
545
+
546
+ # endregion
547
+
548
+ # region Prediction
549
+ if training_args.do_predict or data_args.predict_file:
550
+ logger.info("*** Predict ***")
551
+
552
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
553
+ tasks = []
554
+ tf_datasets = []
555
+ raw_datasets = []
556
+ if training_args.do_predict:
557
+ if data_args.task_name == "mnli":
558
+ tasks.extend(["mnli", "mnli-mm"])
559
+ tf_datasets.extend([tf_data["test_matched"], tf_data["test_mismatched"]])
560
+ raw_datasets.extend([datasets["test_matched"], datasets["test_mismatched"]])
561
+ else:
562
+ tasks.append(data_args.task_name)
563
+ tf_datasets.append(tf_data["test"])
564
+ raw_datasets.append(datasets["test"])
565
+ if data_args.predict_file:
566
+ tasks.append("user_data")
567
+ tf_datasets.append(tf_data["user_data"])
568
+ raw_datasets.append(datasets["user_data"])
569
+
570
+ for raw_dataset, tf_dataset, task in zip(raw_datasets, tf_datasets, tasks):
571
+ test_predictions = model.predict(tf_dataset)
572
+ if "label" in raw_dataset:
573
+ test_metrics = compute_metrics(test_predictions, raw_dataset["label"])
574
+ print(f"Test metrics ({task}):")
575
+ print(test_metrics)
576
+
577
+ if is_regression:
578
+ predictions_to_write = np.squeeze(test_predictions["logits"])
579
+ else:
580
+ predictions_to_write = np.argmax(test_predictions["logits"], axis=1)
581
+
582
+ output_predict_file = os.path.join(training_args.output_dir, f"predict_results_{task}.txt")
583
+ with open(output_predict_file, "w") as writer:
584
+ logger.info(f"***** Writing prediction results for {task} *****")
585
+ writer.write("index\tprediction\n")
586
+ for index, item in enumerate(predictions_to_write):
587
+ if is_regression:
588
+ writer.write(f"{index}\t{item:3.3f}\n")
589
+ else:
590
+ item = model.config.id2label[item]
591
+ writer.write(f"{index}\t{item}\n")
592
+ # endregion
593
+
594
+ if training_args.output_dir is not None and not training_args.push_to_hub:
595
+ # If we're not pushing to hub, at least save a local copy when we're done
596
+ model.save_pretrained(training_args.output_dir)
597
+
598
+
599
+ if __name__ == "__main__":
600
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/text-classification/run_text_classification.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. 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
+ """Fine-tuning the library models for sequence classification."""
17
+ # You can also adapt this script on your own text classification task. Pointers for this are left as comments.
18
+
19
+ import json
20
+ import logging
21
+ import os
22
+ import sys
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+ from typing import Optional
26
+
27
+ import numpy as np
28
+ from datasets import load_dataset
29
+ from packaging.version import parse
30
+
31
+ from transformers import (
32
+ AutoConfig,
33
+ AutoTokenizer,
34
+ HfArgumentParser,
35
+ PretrainedConfig,
36
+ PushToHubCallback,
37
+ TFAutoModelForSequenceClassification,
38
+ TFTrainingArguments,
39
+ create_optimizer,
40
+ set_seed,
41
+ )
42
+ from transformers.utils import CONFIG_NAME, TF2_WEIGHTS_NAME, send_example_telemetry
43
+
44
+
45
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1" # Reduce the amount of console output from TF
46
+ import tensorflow as tf # noqa: E402
47
+
48
+
49
+ try:
50
+ import tf_keras as keras
51
+ except (ModuleNotFoundError, ImportError):
52
+ import keras
53
+
54
+ if parse(keras.__version__).major > 2:
55
+ raise ValueError(
56
+ "Your currently installed version of Keras is Keras 3, but this is not yet supported in "
57
+ "Transformers. Please install the backwards-compatible tf-keras package with "
58
+ "`pip install tf-keras`."
59
+ )
60
+
61
+
62
+ logger = logging.getLogger(__name__)
63
+
64
+
65
+ # region Helper classes
66
+ class SavePretrainedCallback(keras.callbacks.Callback):
67
+ # Hugging Face models have a save_pretrained() method that saves both the weights and the necessary
68
+ # metadata to allow them to be loaded as a pretrained model in future. This is a simple Keras callback
69
+ # that saves the model with this method after each epoch.
70
+ def __init__(self, output_dir, **kwargs):
71
+ super().__init__()
72
+ self.output_dir = output_dir
73
+
74
+ def on_epoch_end(self, epoch, logs=None):
75
+ self.model.save_pretrained(self.output_dir)
76
+
77
+
78
+ # endregion
79
+
80
+
81
+ # region Command-line arguments
82
+ @dataclass
83
+ class DataTrainingArguments:
84
+ """
85
+ Arguments pertaining to what data we are going to input our model for training and eval.
86
+
87
+ Using `HfArgumentParser` we can turn this class
88
+ into argparse arguments to be able to specify them on
89
+ the command line.
90
+ """
91
+
92
+ train_file: Optional[str] = field(
93
+ default=None, metadata={"help": "A csv or a json file containing the training data."}
94
+ )
95
+ validation_file: Optional[str] = field(
96
+ default=None, metadata={"help": "A csv or a json file containing the validation data."}
97
+ )
98
+ test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."})
99
+
100
+ max_seq_length: int = field(
101
+ default=128,
102
+ metadata={
103
+ "help": (
104
+ "The maximum total input sequence length after tokenization. Sequences longer "
105
+ "than this will be truncated, sequences shorter will be padded."
106
+ )
107
+ },
108
+ )
109
+ overwrite_cache: bool = field(
110
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
111
+ )
112
+ pad_to_max_length: bool = field(
113
+ default=False,
114
+ metadata={
115
+ "help": (
116
+ "Whether to pad all samples to `max_seq_length`. "
117
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch. "
118
+ "Data will always be padded when using TPUs."
119
+ )
120
+ },
121
+ )
122
+ max_train_samples: Optional[int] = field(
123
+ default=None,
124
+ metadata={
125
+ "help": (
126
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
127
+ "value if set."
128
+ )
129
+ },
130
+ )
131
+ max_val_samples: Optional[int] = field(
132
+ default=None,
133
+ metadata={
134
+ "help": (
135
+ "For debugging purposes or quicker training, truncate the number of validation examples to this "
136
+ "value if set."
137
+ )
138
+ },
139
+ )
140
+ max_test_samples: Optional[int] = field(
141
+ default=None,
142
+ metadata={
143
+ "help": (
144
+ "For debugging purposes or quicker training, truncate the number of test examples to this "
145
+ "value if set."
146
+ )
147
+ },
148
+ )
149
+
150
+ def __post_init__(self):
151
+ train_extension = self.train_file.split(".")[-1].lower() if self.train_file is not None else None
152
+ validation_extension = (
153
+ self.validation_file.split(".")[-1].lower() if self.validation_file is not None else None
154
+ )
155
+ test_extension = self.test_file.split(".")[-1].lower() if self.test_file is not None else None
156
+ extensions = {train_extension, validation_extension, test_extension}
157
+ extensions.discard(None)
158
+ assert len(extensions) != 0, "Need to supply at least one of --train_file, --validation_file or --test_file!"
159
+ assert len(extensions) == 1, "All input files should have the same file extension, either csv or json!"
160
+ assert "csv" in extensions or "json" in extensions, "Input files should have either .csv or .json extensions!"
161
+ self.input_file_extension = extensions.pop()
162
+
163
+
164
+ @dataclass
165
+ class ModelArguments:
166
+ """
167
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
168
+ """
169
+
170
+ model_name_or_path: str = field(
171
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
172
+ )
173
+ config_name: Optional[str] = field(
174
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
175
+ )
176
+ tokenizer_name: Optional[str] = field(
177
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
178
+ )
179
+ cache_dir: Optional[str] = field(
180
+ default=None,
181
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
182
+ )
183
+ model_revision: str = field(
184
+ default="main",
185
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
186
+ )
187
+ token: str = field(
188
+ default=None,
189
+ metadata={
190
+ "help": (
191
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
192
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
193
+ )
194
+ },
195
+ )
196
+ trust_remote_code: bool = field(
197
+ default=False,
198
+ metadata={
199
+ "help": (
200
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option "
201
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will "
202
+ "execute code present on the Hub on your local machine."
203
+ )
204
+ },
205
+ )
206
+
207
+
208
+ # endregion
209
+
210
+
211
+ def main():
212
+ # region Argument parsing
213
+ # See all possible arguments in src/transformers/training_args.py
214
+ # or by passing the --help flag to this script.
215
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
216
+
217
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
218
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
219
+ # If we pass only one argument to the script and it's the path to a json file,
220
+ # let's parse it to get our arguments.
221
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
222
+ else:
223
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
224
+
225
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
226
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
227
+ send_example_telemetry("run_text_classification", model_args, data_args, framework="tensorflow")
228
+
229
+ output_dir = Path(training_args.output_dir)
230
+ output_dir.mkdir(parents=True, exist_ok=True)
231
+ # endregion
232
+
233
+ # region Checkpoints
234
+ # Detecting last checkpoint.
235
+ checkpoint = None
236
+ if len(os.listdir(training_args.output_dir)) > 0 and not training_args.overwrite_output_dir:
237
+ if (output_dir / CONFIG_NAME).is_file() and (output_dir / TF2_WEIGHTS_NAME).is_file():
238
+ checkpoint = output_dir
239
+ logger.info(
240
+ f"Checkpoint detected, resuming training from checkpoint in {training_args.output_dir}. To avoid this"
241
+ " behavior, change the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
242
+ )
243
+ else:
244
+ raise ValueError(
245
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
246
+ "Use --overwrite_output_dir to continue regardless."
247
+ )
248
+
249
+ # endregion
250
+
251
+ # region Logging
252
+ logging.basicConfig(
253
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
254
+ datefmt="%m/%d/%Y %H:%M:%S",
255
+ handlers=[logging.StreamHandler(sys.stdout)],
256
+ )
257
+ logger.setLevel(logging.INFO)
258
+
259
+ logger.info(f"Training/evaluation parameters {training_args}")
260
+ # endregion
261
+
262
+ # region Loading data
263
+ # For CSV/JSON files, this script will use the 'label' field as the label and the 'sentence1' and optionally
264
+ # 'sentence2' fields as inputs if they exist. If not, the first two fields not named label are used if at least two
265
+ # columns are provided. Note that the term 'sentence' can be slightly misleading, as they often contain more than
266
+ # a single grammatical sentence, when the task requires it.
267
+ #
268
+ # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
269
+ # single column. You can easily tweak this behavior (see below)
270
+ #
271
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
272
+ # download the dataset.
273
+ data_files = {"train": data_args.train_file, "validation": data_args.validation_file, "test": data_args.test_file}
274
+ data_files = {key: file for key, file in data_files.items() if file is not None}
275
+
276
+ for key in data_files.keys():
277
+ logger.info(f"Loading a local file for {key}: {data_files[key]}")
278
+
279
+ if data_args.input_file_extension == "csv":
280
+ # Loading a dataset from local csv files
281
+ datasets = load_dataset(
282
+ "csv",
283
+ data_files=data_files,
284
+ cache_dir=model_args.cache_dir,
285
+ token=model_args.token,
286
+ )
287
+ else:
288
+ # Loading a dataset from local json files
289
+ datasets = load_dataset("json", data_files=data_files, cache_dir=model_args.cache_dir)
290
+ # See more about loading any type of standard or custom dataset at
291
+ # https://huggingface.co/docs/datasets/loading_datasets.
292
+ # endregion
293
+
294
+ # region Label preprocessing
295
+ # If you've passed us a training set, we try to infer your labels from it
296
+ if "train" in datasets:
297
+ # By default we assume that if your label column looks like a float then you're doing regression,
298
+ # and if not then you're doing classification. This is something you may want to change!
299
+ is_regression = datasets["train"].features["label"].dtype in ["float32", "float64"]
300
+ if is_regression:
301
+ num_labels = 1
302
+ else:
303
+ # A useful fast method:
304
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique
305
+ label_list = datasets["train"].unique("label")
306
+ label_list.sort() # Let's sort it for determinism
307
+ num_labels = len(label_list)
308
+ # If you haven't passed a training set, we read label info from the saved model (this happens later)
309
+ else:
310
+ num_labels = None
311
+ label_list = None
312
+ is_regression = None
313
+ # endregion
314
+
315
+ # region Load model config and tokenizer
316
+ if checkpoint is not None:
317
+ config_path = training_args.output_dir
318
+ elif model_args.config_name:
319
+ config_path = model_args.config_name
320
+ else:
321
+ config_path = model_args.model_name_or_path
322
+ if num_labels is not None:
323
+ config = AutoConfig.from_pretrained(
324
+ config_path,
325
+ num_labels=num_labels,
326
+ cache_dir=model_args.cache_dir,
327
+ revision=model_args.model_revision,
328
+ token=model_args.token,
329
+ trust_remote_code=model_args.trust_remote_code,
330
+ )
331
+ else:
332
+ config = AutoConfig.from_pretrained(
333
+ config_path,
334
+ cache_dir=model_args.cache_dir,
335
+ revision=model_args.model_revision,
336
+ token=model_args.token,
337
+ trust_remote_code=model_args.trust_remote_code,
338
+ )
339
+ tokenizer = AutoTokenizer.from_pretrained(
340
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
341
+ cache_dir=model_args.cache_dir,
342
+ revision=model_args.model_revision,
343
+ token=model_args.token,
344
+ trust_remote_code=model_args.trust_remote_code,
345
+ )
346
+ # endregion
347
+
348
+ # region Dataset preprocessing
349
+ # Again, we try to have some nice defaults but don't hesitate to tweak to your use case.
350
+ column_names = {col for cols in datasets.column_names.values() for col in cols}
351
+ non_label_column_names = [name for name in column_names if name != "label"]
352
+ if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
353
+ sentence1_key, sentence2_key = "sentence1", "sentence2"
354
+ elif "sentence1" in non_label_column_names:
355
+ sentence1_key, sentence2_key = "sentence1", None
356
+ else:
357
+ if len(non_label_column_names) >= 2:
358
+ sentence1_key, sentence2_key = non_label_column_names[:2]
359
+ else:
360
+ sentence1_key, sentence2_key = non_label_column_names[0], None
361
+
362
+ if data_args.max_seq_length > tokenizer.model_max_length:
363
+ logger.warning(
364
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the "
365
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
366
+ )
367
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
368
+
369
+ # Ensure that our labels match the model's, if it has some pre-specified
370
+ if "train" in datasets:
371
+ if not is_regression and config.label2id != PretrainedConfig(num_labels=num_labels).label2id:
372
+ label_name_to_id = config.label2id
373
+ if sorted(label_name_to_id.keys()) == sorted(label_list):
374
+ label_to_id = label_name_to_id # Use the model's labels
375
+ else:
376
+ logger.warning(
377
+ "Your model seems to have been trained with labels, but they don't match the dataset: "
378
+ f"model labels: {sorted(label_name_to_id.keys())}, dataset labels:"
379
+ f" {sorted(label_list)}.\nIgnoring the model labels as a result.",
380
+ )
381
+ label_to_id = {v: i for i, v in enumerate(label_list)}
382
+ elif not is_regression:
383
+ label_to_id = {v: i for i, v in enumerate(label_list)}
384
+ else:
385
+ label_to_id = None
386
+ # Now we've established our label2id, let's overwrite the model config with it.
387
+ config.label2id = label_to_id
388
+ if config.label2id is not None:
389
+ config.id2label = {id: label for label, id in label_to_id.items()}
390
+ else:
391
+ config.id2label = None
392
+ else:
393
+ label_to_id = config.label2id # Just load the data from the model
394
+
395
+ if "validation" in datasets and config.label2id is not None:
396
+ validation_label_list = datasets["validation"].unique("label")
397
+ for val_label in validation_label_list:
398
+ assert val_label in label_to_id, f"Label {val_label} is in the validation set but not the training set!"
399
+
400
+ def preprocess_function(examples):
401
+ # Tokenize the texts
402
+ args = (
403
+ (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
404
+ )
405
+ result = tokenizer(*args, max_length=max_seq_length, truncation=True)
406
+
407
+ # Map labels to IDs
408
+ if config.label2id is not None and "label" in examples:
409
+ result["label"] = [(config.label2id[l] if l != -1 else -1) for l in examples["label"]]
410
+ return result
411
+
412
+ datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache)
413
+
414
+ # endregion
415
+
416
+ with training_args.strategy.scope():
417
+ # region Load pretrained model
418
+ # Set seed before initializing model
419
+ set_seed(training_args.seed)
420
+ #
421
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
422
+ # download model & vocab.
423
+ if checkpoint is None:
424
+ model_path = model_args.model_name_or_path
425
+ else:
426
+ model_path = checkpoint
427
+ model = TFAutoModelForSequenceClassification.from_pretrained(
428
+ model_path,
429
+ config=config,
430
+ cache_dir=model_args.cache_dir,
431
+ revision=model_args.model_revision,
432
+ token=model_args.token,
433
+ trust_remote_code=model_args.trust_remote_code,
434
+ )
435
+ # endregion
436
+
437
+ # region Convert data to a tf.data.Dataset
438
+ dataset_options = tf.data.Options()
439
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
440
+ num_replicas = training_args.strategy.num_replicas_in_sync
441
+
442
+ tf_data = {}
443
+ max_samples = {
444
+ "train": data_args.max_train_samples,
445
+ "validation": data_args.max_val_samples,
446
+ "test": data_args.max_test_samples,
447
+ }
448
+ for key in ("train", "validation", "test"):
449
+ if key not in datasets:
450
+ tf_data[key] = None
451
+ continue
452
+ if (
453
+ (key == "train" and not training_args.do_train)
454
+ or (key == "validation" and not training_args.do_eval)
455
+ or (key == "test" and not training_args.do_predict)
456
+ ):
457
+ tf_data[key] = None
458
+ continue
459
+ if key in ("train", "validation"):
460
+ assert "label" in datasets[key].features, f"Missing labels from {key} data!"
461
+ if key == "train":
462
+ shuffle = True
463
+ batch_size = training_args.per_device_train_batch_size * num_replicas
464
+ else:
465
+ shuffle = False
466
+ batch_size = training_args.per_device_eval_batch_size * num_replicas
467
+ samples_limit = max_samples[key]
468
+ dataset = datasets[key]
469
+ if samples_limit is not None:
470
+ dataset = dataset.select(range(samples_limit))
471
+
472
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
473
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
474
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
475
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
476
+ # using model.prepare_tf_dataset()
477
+ # For more info see the docs:
478
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
479
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
480
+
481
+ data = model.prepare_tf_dataset(
482
+ dataset,
483
+ shuffle=shuffle,
484
+ batch_size=batch_size,
485
+ tokenizer=tokenizer,
486
+ )
487
+ data = data.with_options(dataset_options)
488
+ tf_data[key] = data
489
+ # endregion
490
+
491
+ # region Optimizer, loss and compilation
492
+
493
+ if training_args.do_train:
494
+ num_train_steps = len(tf_data["train"]) * training_args.num_train_epochs
495
+ if training_args.warmup_steps > 0:
496
+ num_warmup_steps = training_args.warmup_steps
497
+ elif training_args.warmup_ratio > 0:
498
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
499
+ else:
500
+ num_warmup_steps = 0
501
+
502
+ optimizer, schedule = create_optimizer(
503
+ init_lr=training_args.learning_rate,
504
+ num_train_steps=num_train_steps,
505
+ num_warmup_steps=num_warmup_steps,
506
+ adam_beta1=training_args.adam_beta1,
507
+ adam_beta2=training_args.adam_beta2,
508
+ adam_epsilon=training_args.adam_epsilon,
509
+ weight_decay_rate=training_args.weight_decay,
510
+ adam_global_clipnorm=training_args.max_grad_norm,
511
+ )
512
+ else:
513
+ optimizer = "sgd" # Just use any default
514
+ if is_regression:
515
+ metrics = []
516
+ else:
517
+ metrics = ["accuracy"]
518
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
519
+ # use this for training unless you specify your own loss function in compile().
520
+ model.compile(optimizer=optimizer, metrics=metrics)
521
+ # endregion
522
+
523
+ # region Preparing push_to_hub and model card
524
+ push_to_hub_model_id = training_args.push_to_hub_model_id
525
+ model_name = model_args.model_name_or_path.split("/")[-1]
526
+ if not push_to_hub_model_id:
527
+ push_to_hub_model_id = f"{model_name}-finetuned-text-classification"
528
+
529
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"}
530
+
531
+ if training_args.push_to_hub:
532
+ callbacks = [
533
+ PushToHubCallback(
534
+ output_dir=training_args.output_dir,
535
+ hub_model_id=push_to_hub_model_id,
536
+ hub_token=training_args.push_to_hub_token,
537
+ tokenizer=tokenizer,
538
+ **model_card_kwargs,
539
+ )
540
+ ]
541
+ else:
542
+ callbacks = []
543
+ # endregion
544
+
545
+ # region Training and validation
546
+ if tf_data["train"] is not None:
547
+ model.fit(
548
+ tf_data["train"],
549
+ validation_data=tf_data["validation"],
550
+ epochs=int(training_args.num_train_epochs),
551
+ callbacks=callbacks,
552
+ )
553
+ if tf_data["validation"] is not None:
554
+ logger.info("Computing metrics on validation data...")
555
+ if is_regression:
556
+ loss = model.evaluate(tf_data["validation"])
557
+ logger.info(f"Eval loss: {loss:.5f}")
558
+ else:
559
+ loss, accuracy = model.evaluate(tf_data["validation"])
560
+ logger.info(f"Eval loss: {loss:.5f}, Eval accuracy: {accuracy * 100:.4f}%")
561
+ if training_args.output_dir is not None:
562
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
563
+ eval_dict = {"eval_loss": loss}
564
+ if not is_regression:
565
+ eval_dict["eval_accuracy"] = accuracy
566
+ with open(output_eval_file, "w") as writer:
567
+ writer.write(json.dumps(eval_dict))
568
+ # endregion
569
+
570
+ # region Prediction
571
+ if tf_data["test"] is not None:
572
+ logger.info("Doing predictions on test dataset...")
573
+ predictions = model.predict(tf_data["test"])["logits"]
574
+ predicted_class = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1)
575
+ output_test_file = os.path.join(training_args.output_dir, "test_results.txt")
576
+ with open(output_test_file, "w") as writer:
577
+ writer.write("index\tprediction\n")
578
+ for index, item in enumerate(predicted_class):
579
+ if is_regression:
580
+ writer.write(f"{index}\t{item:3.3f}\n")
581
+ else:
582
+ item = config.id2label[item]
583
+ writer.write(f"{index}\t{item}\n")
584
+ logger.info(f"Wrote predictions to {output_test_file}!")
585
+ # endregion
586
+
587
+ if training_args.output_dir is not None and not training_args.push_to_hub:
588
+ # If we're not pushing to hub, at least save a local copy when we're done
589
+ model.save_pretrained(training_args.output_dir)
590
+
591
+
592
+ if __name__ == "__main__":
593
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/token-classification/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Token classification
18
+
19
+ Fine-tuning the library models for token classification task such as Named Entity Recognition (NER), Parts-of-speech
20
+ tagging (POS) or phrase extraction (CHUNKS). The main script `run_ner.py` leverages the [🤗 Datasets](https://github.com/huggingface/datasets) library. You can easily
21
+ customize it to your needs if you need extra processing on your datasets.
22
+
23
+ It will either run on a datasets hosted on our [hub](https://huggingface.co/datasets) or with your own text files for
24
+ training and validation, you might just need to add some tweaks in the data preprocessing.
25
+
26
+ The following example fine-tunes BERT on CoNLL-2003:
27
+
28
+ ```bash
29
+ python run_ner.py \
30
+ --model_name_or_path google-bert/bert-base-uncased \
31
+ --dataset_name conll2003 \
32
+ --output_dir /tmp/test-ner
33
+ ```
34
+
35
+ To run on your own training and validation files, use the following command:
36
+
37
+ ```bash
38
+ python run_ner.py \
39
+ --model_name_or_path google-bert/bert-base-uncased \
40
+ --train_file path_to_train_file \
41
+ --validation_file path_to_validation_file \
42
+ --output_dir /tmp/test-ner
43
+ ```
44
+
45
+ **Note:** This script only works with models that have a fast tokenizer (backed by the [🤗 Tokenizers](https://github.com/huggingface/tokenizers) library) as it
46
+ uses special features of those tokenizers. You can check if your favorite model has a fast tokenizer in
47
+ [this table](https://huggingface.co/transformers/index.html#supported-frameworks).
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/token-classification/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets >= 1.4.0
2
+ tensorflow >= 2.3.0
3
+ evaluate >= 0.2.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/token-classification/run_ner.py ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. 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 a 🤗 Transformers model on token classification tasks (NER, POS, CHUNKS)
18
+ """
19
+
20
+ import json
21
+ import logging
22
+ import os
23
+ import random
24
+ from dataclasses import dataclass, field
25
+ from typing import Optional
26
+
27
+ import datasets
28
+ import evaluate
29
+ import tensorflow as tf
30
+ from datasets import ClassLabel, load_dataset
31
+
32
+ import transformers
33
+ from transformers import (
34
+ CONFIG_MAPPING,
35
+ AutoConfig,
36
+ AutoTokenizer,
37
+ DataCollatorForTokenClassification,
38
+ HfArgumentParser,
39
+ PushToHubCallback,
40
+ TFAutoModelForTokenClassification,
41
+ TFTrainingArguments,
42
+ create_optimizer,
43
+ set_seed,
44
+ )
45
+ from transformers.utils import send_example_telemetry
46
+ from transformers.utils.versions import require_version
47
+
48
+
49
+ logger = logging.getLogger(__name__)
50
+ logger.addHandler(logging.StreamHandler())
51
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/tensorflow/token-classification/requirements.txt")
52
+
53
+
54
+ # region Command-line arguments
55
+ @dataclass
56
+ class ModelArguments:
57
+ """
58
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
59
+ """
60
+
61
+ model_name_or_path: str = field(
62
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
63
+ )
64
+ config_name: Optional[str] = field(
65
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
66
+ )
67
+ tokenizer_name: Optional[str] = field(
68
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
69
+ )
70
+ cache_dir: Optional[str] = field(
71
+ default=None,
72
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
73
+ )
74
+ model_revision: str = field(
75
+ default="main",
76
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
77
+ )
78
+ token: str = field(
79
+ default=None,
80
+ metadata={
81
+ "help": (
82
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
83
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
84
+ )
85
+ },
86
+ )
87
+ trust_remote_code: bool = field(
88
+ default=False,
89
+ metadata={
90
+ "help": (
91
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
92
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
93
+ " code, as it will execute code present on the Hub on your local machine."
94
+ )
95
+ },
96
+ )
97
+
98
+
99
+ @dataclass
100
+ class DataTrainingArguments:
101
+ """
102
+ Arguments pertaining to what data we are going to input our model for training and eval.
103
+ """
104
+
105
+ task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."})
106
+ dataset_name: Optional[str] = field(
107
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
108
+ )
109
+ dataset_config_name: Optional[str] = field(
110
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
111
+ )
112
+ train_file: Optional[str] = field(
113
+ default=None, metadata={"help": "The input training data file (a csv or JSON file)."}
114
+ )
115
+ validation_file: Optional[str] = field(
116
+ default=None,
117
+ metadata={"help": "An optional input evaluation data file to evaluate on (a csv or JSON file)."},
118
+ )
119
+ test_file: Optional[str] = field(
120
+ default=None,
121
+ metadata={"help": "An optional input test data file to predict on (a csv or JSON file)."},
122
+ )
123
+ text_column_name: Optional[str] = field(
124
+ default=None, metadata={"help": "The column name of text to input in the file (a csv or JSON file)."}
125
+ )
126
+ label_column_name: Optional[str] = field(
127
+ default=None, metadata={"help": "The column name of label to input in the file (a csv or JSON file)."}
128
+ )
129
+ overwrite_cache: bool = field(
130
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
131
+ )
132
+ preprocessing_num_workers: Optional[int] = field(
133
+ default=None,
134
+ metadata={"help": "The number of processes to use for the preprocessing."},
135
+ )
136
+ max_length: Optional[int] = field(default=256, metadata={"help": "Max length (in tokens) for truncation/padding"})
137
+ pad_to_max_length: bool = field(
138
+ default=False,
139
+ metadata={
140
+ "help": (
141
+ "Whether to pad all samples to model maximum sentence length. "
142
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
143
+ "efficient on GPU but very bad for TPU."
144
+ )
145
+ },
146
+ )
147
+ max_train_samples: Optional[int] = field(
148
+ default=None,
149
+ metadata={
150
+ "help": (
151
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
152
+ "value if set."
153
+ )
154
+ },
155
+ )
156
+ max_eval_samples: Optional[int] = field(
157
+ default=None,
158
+ metadata={
159
+ "help": (
160
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
161
+ "value if set."
162
+ )
163
+ },
164
+ )
165
+ max_predict_samples: Optional[int] = field(
166
+ default=None,
167
+ metadata={
168
+ "help": (
169
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
170
+ "value if set."
171
+ )
172
+ },
173
+ )
174
+ label_all_tokens: bool = field(
175
+ default=False,
176
+ metadata={
177
+ "help": (
178
+ "Whether to put the label for one word on all tokens of generated by that word or just on the "
179
+ "one (in which case the other tokens will have a padding index)."
180
+ )
181
+ },
182
+ )
183
+ return_entity_level_metrics: bool = field(
184
+ default=False,
185
+ metadata={"help": "Whether to return all the entity levels during evaluation or just the overall ones."},
186
+ )
187
+
188
+ def __post_init__(self):
189
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
190
+ raise ValueError("Need either a dataset name or a training/validation file.")
191
+ else:
192
+ if self.train_file is not None:
193
+ extension = self.train_file.split(".")[-1]
194
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
195
+ if self.validation_file is not None:
196
+ extension = self.validation_file.split(".")[-1]
197
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
198
+ self.task_name = self.task_name.lower()
199
+
200
+
201
+ # endregion
202
+
203
+
204
+ def main():
205
+ # region Argument Parsing
206
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
207
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
208
+
209
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
210
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
211
+ send_example_telemetry("run_ner", model_args, data_args, framework="tensorflow")
212
+ # endregion
213
+
214
+ # region Setup logging
215
+ # we only want one process per machine to log things on the screen.
216
+ # accelerator.is_local_main_process is only True for one process per machine.
217
+ logger.setLevel(logging.INFO)
218
+ datasets.utils.logging.set_verbosity_warning()
219
+ transformers.utils.logging.set_verbosity_info()
220
+
221
+ # If passed along, set the training seed now.
222
+ if training_args.seed is not None:
223
+ set_seed(training_args.seed)
224
+ # endregion
225
+
226
+ # region Loading datasets
227
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
228
+ # or just provide the name of one of the public datasets for token classification task available on the hub at https://huggingface.co/datasets/
229
+ # (the dataset will be downloaded automatically from the datasets Hub).
230
+ #
231
+ # For CSV/JSON files, this script will use the column called 'tokens' or the first column if no column called
232
+ # 'tokens' is found. You can easily tweak this behavior (see below).
233
+ #
234
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
235
+ # download the dataset.
236
+ if data_args.dataset_name is not None:
237
+ # Downloading and loading a dataset from the hub.
238
+ raw_datasets = load_dataset(
239
+ data_args.dataset_name,
240
+ data_args.dataset_config_name,
241
+ token=model_args.token,
242
+ trust_remote_code=model_args.trust_remote_code,
243
+ )
244
+ else:
245
+ data_files = {}
246
+ if data_args.train_file is not None:
247
+ data_files["train"] = data_args.train_file
248
+ extension = data_args.train_file.split(".")[-1]
249
+ if data_args.validation_file is not None:
250
+ data_files["validation"] = data_args.validation_file
251
+ extension = data_args.validation_file.split(".")[-1]
252
+ raw_datasets = load_dataset(
253
+ extension,
254
+ data_files=data_files,
255
+ token=model_args.token,
256
+ )
257
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
258
+ # https://huggingface.co/docs/datasets/loading_datasets.
259
+
260
+ if raw_datasets["train"] is not None:
261
+ column_names = raw_datasets["train"].column_names
262
+ features = raw_datasets["train"].features
263
+ else:
264
+ column_names = raw_datasets["validation"].column_names
265
+ features = raw_datasets["validation"].features
266
+
267
+ if data_args.text_column_name is not None:
268
+ text_column_name = data_args.text_column_name
269
+ elif "tokens" in column_names:
270
+ text_column_name = "tokens"
271
+ else:
272
+ text_column_name = column_names[0]
273
+
274
+ if data_args.label_column_name is not None:
275
+ label_column_name = data_args.label_column_name
276
+ elif f"{data_args.task_name}_tags" in column_names:
277
+ label_column_name = f"{data_args.task_name}_tags"
278
+ else:
279
+ label_column_name = column_names[1]
280
+
281
+ # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the
282
+ # unique labels.
283
+ def get_label_list(labels):
284
+ unique_labels = set()
285
+ for label in labels:
286
+ unique_labels = unique_labels | set(label)
287
+ label_list = list(unique_labels)
288
+ label_list.sort()
289
+ return label_list
290
+
291
+ if isinstance(features[label_column_name].feature, ClassLabel):
292
+ label_list = features[label_column_name].feature.names
293
+ # No need to convert the labels since they are already ints.
294
+ label_to_id = {i: i for i in range(len(label_list))}
295
+ else:
296
+ label_list = get_label_list(raw_datasets["train"][label_column_name])
297
+ label_to_id = {l: i for i, l in enumerate(label_list)}
298
+ num_labels = len(label_list)
299
+ # endregion
300
+
301
+ # region Load config and tokenizer
302
+ #
303
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
304
+ # download model & vocab.
305
+ if model_args.config_name:
306
+ config = AutoConfig.from_pretrained(
307
+ model_args.config_name,
308
+ num_labels=num_labels,
309
+ token=model_args.token,
310
+ trust_remote_code=model_args.trust_remote_code,
311
+ )
312
+ elif model_args.model_name_or_path:
313
+ config = AutoConfig.from_pretrained(
314
+ model_args.model_name_or_path,
315
+ num_labels=num_labels,
316
+ token=model_args.token,
317
+ trust_remote_code=model_args.trust_remote_code,
318
+ )
319
+ else:
320
+ config = CONFIG_MAPPING[model_args.model_type]()
321
+ logger.warning("You are instantiating a new config instance from scratch.")
322
+
323
+ tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path
324
+ if not tokenizer_name_or_path:
325
+ raise ValueError(
326
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
327
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
328
+ )
329
+
330
+ if config.model_type in {"gpt2", "roberta"}:
331
+ tokenizer = AutoTokenizer.from_pretrained(
332
+ tokenizer_name_or_path,
333
+ use_fast=True,
334
+ add_prefix_space=True,
335
+ token=model_args.token,
336
+ trust_remote_code=model_args.trust_remote_code,
337
+ )
338
+ else:
339
+ tokenizer = AutoTokenizer.from_pretrained(
340
+ tokenizer_name_or_path,
341
+ use_fast=True,
342
+ token=model_args.token,
343
+ trust_remote_code=model_args.trust_remote_code,
344
+ )
345
+ # endregion
346
+
347
+ # region Preprocessing the raw datasets
348
+ # First we tokenize all the texts.
349
+ padding = "max_length" if data_args.pad_to_max_length else False
350
+
351
+ # Tokenize all texts and align the labels with them.
352
+
353
+ def tokenize_and_align_labels(examples):
354
+ tokenized_inputs = tokenizer(
355
+ examples[text_column_name],
356
+ max_length=data_args.max_length,
357
+ padding=padding,
358
+ truncation=True,
359
+ # We use this argument because the texts in our dataset are lists of words (with a label for each word).
360
+ is_split_into_words=True,
361
+ )
362
+
363
+ labels = []
364
+ for i, label in enumerate(examples[label_column_name]):
365
+ word_ids = tokenized_inputs.word_ids(batch_index=i)
366
+ previous_word_idx = None
367
+ label_ids = []
368
+ for word_idx in word_ids:
369
+ # Special tokens have a word id that is None. We set the label to -100 so they are automatically
370
+ # ignored in the loss function.
371
+ if word_idx is None:
372
+ label_ids.append(-100)
373
+ # We set the label for the first token of each word.
374
+ elif word_idx != previous_word_idx:
375
+ label_ids.append(label_to_id[label[word_idx]])
376
+ # For the other tokens in a word, we set the label to either the current label or -100, depending on
377
+ # the label_all_tokens flag.
378
+ else:
379
+ label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100)
380
+ previous_word_idx = word_idx
381
+
382
+ labels.append(label_ids)
383
+ tokenized_inputs["labels"] = labels
384
+ return tokenized_inputs
385
+
386
+ processed_raw_datasets = raw_datasets.map(
387
+ tokenize_and_align_labels,
388
+ batched=True,
389
+ remove_columns=raw_datasets["train"].column_names,
390
+ desc="Running tokenizer on dataset",
391
+ )
392
+
393
+ train_dataset = processed_raw_datasets["train"]
394
+ eval_dataset = processed_raw_datasets["validation"]
395
+
396
+ if data_args.max_train_samples is not None:
397
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
398
+ train_dataset = train_dataset.select(range(max_train_samples))
399
+
400
+ if data_args.max_eval_samples is not None:
401
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
402
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
403
+
404
+ # Log a few random samples from the training set:
405
+ for index in random.sample(range(len(train_dataset)), 3):
406
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
407
+ # endregion
408
+
409
+ with training_args.strategy.scope():
410
+ # region Initialize model
411
+ if model_args.model_name_or_path:
412
+ model = TFAutoModelForTokenClassification.from_pretrained(
413
+ model_args.model_name_or_path,
414
+ config=config,
415
+ token=model_args.token,
416
+ trust_remote_code=model_args.trust_remote_code,
417
+ )
418
+ else:
419
+ logger.info("Training new model from scratch")
420
+ model = TFAutoModelForTokenClassification.from_config(
421
+ config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
422
+ )
423
+
424
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
425
+ # on a small vocab and want a smaller embedding size, remove this test.
426
+ embeddings = model.get_input_embeddings()
427
+
428
+ # Matt: This is a temporary workaround as we transition our models to exclusively using Keras embeddings.
429
+ # As soon as the transition is complete, all embeddings should be keras.Embeddings layers, and
430
+ # the weights will always be in embeddings.embeddings.
431
+ if hasattr(embeddings, "embeddings"):
432
+ embedding_size = embeddings.embeddings.shape[0]
433
+ else:
434
+ embedding_size = embeddings.weight.shape[0]
435
+ if len(tokenizer) > embedding_size:
436
+ model.resize_token_embeddings(len(tokenizer))
437
+ # endregion
438
+
439
+ # region Create TF datasets
440
+
441
+ # We need the DataCollatorForTokenClassification here, as we need to correctly pad labels as
442
+ # well as inputs.
443
+ collate_fn = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="np")
444
+ num_replicas = training_args.strategy.num_replicas_in_sync
445
+ total_train_batch_size = training_args.per_device_train_batch_size * num_replicas
446
+
447
+ dataset_options = tf.data.Options()
448
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
449
+
450
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
451
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
452
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
453
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
454
+ # using model.prepare_tf_dataset()
455
+ # For more info see the docs:
456
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
457
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
458
+
459
+ tf_train_dataset = model.prepare_tf_dataset(
460
+ train_dataset,
461
+ collate_fn=collate_fn,
462
+ batch_size=total_train_batch_size,
463
+ shuffle=True,
464
+ ).with_options(dataset_options)
465
+ total_eval_batch_size = training_args.per_device_eval_batch_size * num_replicas
466
+ tf_eval_dataset = model.prepare_tf_dataset(
467
+ eval_dataset,
468
+ collate_fn=collate_fn,
469
+ batch_size=total_eval_batch_size,
470
+ shuffle=False,
471
+ ).with_options(dataset_options)
472
+
473
+ # endregion
474
+
475
+ # region Optimizer, loss and compilation
476
+ num_train_steps = int(len(tf_train_dataset) * training_args.num_train_epochs)
477
+ if training_args.warmup_steps > 0:
478
+ num_warmup_steps = training_args.warmup_steps
479
+ elif training_args.warmup_ratio > 0:
480
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
481
+ else:
482
+ num_warmup_steps = 0
483
+
484
+ optimizer, lr_schedule = create_optimizer(
485
+ init_lr=training_args.learning_rate,
486
+ num_train_steps=num_train_steps,
487
+ num_warmup_steps=num_warmup_steps,
488
+ adam_beta1=training_args.adam_beta1,
489
+ adam_beta2=training_args.adam_beta2,
490
+ adam_epsilon=training_args.adam_epsilon,
491
+ weight_decay_rate=training_args.weight_decay,
492
+ adam_global_clipnorm=training_args.max_grad_norm,
493
+ )
494
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
495
+ # use this for training unless you specify your own loss function in compile().
496
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
497
+ # endregion
498
+
499
+ # Metrics
500
+ metric = evaluate.load("seqeval", cache_dir=model_args.cache_dir)
501
+
502
+ def get_labels(y_pred, y_true):
503
+ # Transform predictions and references tensos to numpy arrays
504
+
505
+ # Remove ignored index (special tokens)
506
+ true_predictions = [
507
+ [label_list[p] for (p, l) in zip(pred, gold_label) if l != -100]
508
+ for pred, gold_label in zip(y_pred, y_true)
509
+ ]
510
+ true_labels = [
511
+ [label_list[l] for (p, l) in zip(pred, gold_label) if l != -100]
512
+ for pred, gold_label in zip(y_pred, y_true)
513
+ ]
514
+ return true_predictions, true_labels
515
+
516
+ def compute_metrics():
517
+ results = metric.compute()
518
+ if data_args.return_entity_level_metrics:
519
+ # Unpack nested dictionaries
520
+ final_results = {}
521
+ for key, value in results.items():
522
+ if isinstance(value, dict):
523
+ for n, v in value.items():
524
+ final_results[f"{key}_{n}"] = v
525
+ else:
526
+ final_results[key] = value
527
+ return final_results
528
+ else:
529
+ return {
530
+ "precision": results["overall_precision"],
531
+ "recall": results["overall_recall"],
532
+ "f1": results["overall_f1"],
533
+ "accuracy": results["overall_accuracy"],
534
+ }
535
+
536
+ # endregion
537
+
538
+ # region Preparing push_to_hub and model card
539
+ push_to_hub_model_id = training_args.push_to_hub_model_id
540
+ model_name = model_args.model_name_or_path.split("/")[-1]
541
+ if not push_to_hub_model_id:
542
+ if data_args.dataset_name is not None:
543
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.dataset_name}"
544
+ else:
545
+ push_to_hub_model_id = f"{model_name}-finetuned-token-classification"
546
+
547
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "token-classification"}
548
+ if data_args.dataset_name is not None:
549
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
550
+ if data_args.dataset_config_name is not None:
551
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
552
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
553
+ else:
554
+ model_card_kwargs["dataset"] = data_args.dataset_name
555
+
556
+ if training_args.push_to_hub:
557
+ callbacks = [
558
+ PushToHubCallback(
559
+ output_dir=training_args.output_dir,
560
+ hub_model_id=push_to_hub_model_id,
561
+ hub_token=training_args.push_to_hub_token,
562
+ tokenizer=tokenizer,
563
+ **model_card_kwargs,
564
+ )
565
+ ]
566
+ else:
567
+ callbacks = []
568
+ # endregion
569
+
570
+ # region Training
571
+ logger.info("***** Running training *****")
572
+ logger.info(f" Num examples = {len(train_dataset)}")
573
+ logger.info(f" Num Epochs = {training_args.num_train_epochs}")
574
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
575
+ logger.info(f" Total train batch size = {total_train_batch_size}")
576
+ # Only show the progress bar once on each machine.
577
+
578
+ model.fit(
579
+ tf_train_dataset,
580
+ validation_data=tf_eval_dataset,
581
+ epochs=int(training_args.num_train_epochs),
582
+ callbacks=callbacks,
583
+ )
584
+ # endregion
585
+
586
+ # region Predictions
587
+ # If you have variable batch sizes (i.e. not using pad_to_max_length), then
588
+ # this bit might fail on TF < 2.8 because TF can't concatenate outputs of varying seq
589
+ # length from predict().
590
+
591
+ try:
592
+ predictions = model.predict(tf_eval_dataset, batch_size=training_args.per_device_eval_batch_size)["logits"]
593
+ except tf.python.framework.errors_impl.InvalidArgumentError:
594
+ raise ValueError(
595
+ "Concatenating predictions failed! If your version of TensorFlow is 2.8.0 or older "
596
+ "then you will need to use --pad_to_max_length to generate predictions, as older "
597
+ "versions of TensorFlow cannot concatenate variable-length predictions as RaggedTensor."
598
+ )
599
+ if isinstance(predictions, tf.RaggedTensor):
600
+ predictions = predictions.to_tensor(default_value=-100)
601
+ predictions = tf.math.argmax(predictions, axis=-1).numpy()
602
+ if "label" in eval_dataset:
603
+ labels = eval_dataset.with_format("tf")["label"]
604
+ else:
605
+ labels = eval_dataset.with_format("tf")["labels"]
606
+ if isinstance(labels, tf.RaggedTensor):
607
+ labels = labels.to_tensor(default_value=-100)
608
+ labels = labels.numpy()
609
+ attention_mask = eval_dataset.with_format("tf")["attention_mask"]
610
+ if isinstance(attention_mask, tf.RaggedTensor):
611
+ attention_mask = attention_mask.to_tensor(default_value=-100)
612
+ attention_mask = attention_mask.numpy()
613
+ labels[attention_mask == 0] = -100
614
+ preds, refs = get_labels(predictions, labels)
615
+ metric.add_batch(
616
+ predictions=preds,
617
+ references=refs,
618
+ )
619
+ eval_metric = compute_metrics()
620
+ logger.info("Evaluation metrics:")
621
+ for key, val in eval_metric.items():
622
+ logger.info(f"{key}: {val:.4f}")
623
+
624
+ if training_args.output_dir is not None:
625
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
626
+ with open(output_eval_file, "w") as writer:
627
+ writer.write(json.dumps(eval_metric))
628
+ # endregion
629
+
630
+ if training_args.output_dir is not None and not training_args.push_to_hub:
631
+ # If we're not pushing to hub, at least save a local copy when we're done
632
+ model.save_pretrained(training_args.output_dir)
633
+
634
+
635
+ if __name__ == "__main__":
636
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/translation/README.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # Translation example
18
+
19
+ This script shows an example of training a *translation* model with the 🤗 Transformers library.
20
+ For straightforward use-cases you may be able to use these scripts without modification, although we have also
21
+ included comments in the code to indicate areas that you may need to adapt to your own projects.
22
+
23
+ ### Multi-GPU and TPU usage
24
+
25
+ By default, these scripts use a `MirroredStrategy` and will use multiple GPUs effectively if they are available. TPUs
26
+ can also be used by passing the name of the TPU resource with the `--tpu` argument.
27
+
28
+ ### Example commands and caveats
29
+
30
+ MBart and some T5 models require special handling.
31
+
32
+ T5 models `google-t5/t5-small`, `google-t5/t5-base`, `google-t5/t5-large`, `google-t5/t5-3b` and `google-t5/t5-11b` must use an additional argument: `--source_prefix "translate {source_lang} to {target_lang}"`. For example:
33
+
34
+ ```bash
35
+ python run_translation.py \
36
+ --model_name_or_path google-t5/t5-small \
37
+ --do_train \
38
+ --do_eval \
39
+ --source_lang en \
40
+ --target_lang ro \
41
+ --source_prefix "translate English to Romanian: " \
42
+ --dataset_name wmt16 \
43
+ --dataset_config_name ro-en \
44
+ --output_dir /tmp/tst-translation \
45
+ --per_device_train_batch_size=16 \
46
+ --per_device_eval_batch_size=16 \
47
+ --overwrite_output_dir
48
+ ```
49
+
50
+ If you get a terrible BLEU score, make sure that you didn't forget to use the `--source_prefix` argument.
51
+
52
+ For the aforementioned group of T5 models it's important to remember that if you switch to a different language pair, make sure to adjust the source and target values in all 3 language-specific command line argument: `--source_lang`, `--target_lang` and `--source_prefix`.
53
+
54
+ MBart models require a different format for `--source_lang` and `--target_lang` values, e.g. instead of `en` it expects `en_XX`, for `ro` it expects `ro_RO`. The full MBart specification for language codes can be found [here](https://huggingface.co/facebook/mbart-large-cc25). For example:
55
+
56
+ ```bash
57
+ python run_translation.py \
58
+ --model_name_or_path facebook/mbart-large-en-ro \
59
+ --do_train \
60
+ --do_eval \
61
+ --dataset_name wmt16 \
62
+ --dataset_config_name ro-en \
63
+ --source_lang en_XX \
64
+ --target_lang ro_RO \
65
+ --output_dir /tmp/tst-translation \
66
+ --per_device_train_batch_size=16 \
67
+ --per_device_eval_batch_size=16 \
68
+ --overwrite_output_dir
69
+ ```
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/translation/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets >= 1.4.0
2
+ tensorflow >= 2.3.0
3
+ evaluate >= 0.2.0
tasks/tasksmith-441eeab80047/tests/source/examples/tensorflow/translation/run_translation.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 translation.
18
+ """
19
+ # You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
20
+
21
+ import json
22
+ import logging
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from typing import Optional
27
+
28
+ import datasets
29
+ import evaluate
30
+ import numpy as np
31
+ import tensorflow as tf
32
+ from datasets import load_dataset
33
+
34
+ import transformers
35
+ from transformers import (
36
+ AutoConfig,
37
+ AutoTokenizer,
38
+ DataCollatorForSeq2Seq,
39
+ HfArgumentParser,
40
+ KerasMetricCallback,
41
+ M2M100Tokenizer,
42
+ MBart50Tokenizer,
43
+ MBart50TokenizerFast,
44
+ MBartTokenizer,
45
+ MBartTokenizerFast,
46
+ PushToHubCallback,
47
+ TFAutoModelForSeq2SeqLM,
48
+ TFTrainingArguments,
49
+ create_optimizer,
50
+ set_seed,
51
+ )
52
+ from transformers.trainer_utils import get_last_checkpoint
53
+ from transformers.utils import check_min_version, send_example_telemetry
54
+ from transformers.utils.versions import require_version
55
+
56
+
57
+ # region Dependencies and constants
58
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
59
+ check_min_version("4.50.0.dev0")
60
+
61
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
62
+
63
+ logger = logging.getLogger(__name__)
64
+ MULTILINGUAL_TOKENIZERS = [MBartTokenizer, MBartTokenizerFast, MBart50Tokenizer, MBart50TokenizerFast, M2M100Tokenizer]
65
+ # endregion
66
+
67
+
68
+ # region Arguments
69
+ @dataclass
70
+ class ModelArguments:
71
+ """
72
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
73
+ """
74
+
75
+ model_name_or_path: str = field(
76
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
77
+ )
78
+ config_name: Optional[str] = field(
79
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
80
+ )
81
+ tokenizer_name: Optional[str] = field(
82
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
83
+ )
84
+ cache_dir: Optional[str] = field(
85
+ default=None,
86
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
87
+ )
88
+ use_fast_tokenizer: bool = field(
89
+ default=True,
90
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
91
+ )
92
+ model_revision: str = field(
93
+ default="main",
94
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
95
+ )
96
+ token: str = field(
97
+ default=None,
98
+ metadata={
99
+ "help": (
100
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
101
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
102
+ )
103
+ },
104
+ )
105
+ trust_remote_code: bool = field(
106
+ default=False,
107
+ metadata={
108
+ "help": (
109
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
110
+ " This option should only be set to `True` for repositories you trust and in which you have read the"
111
+ " code, as it will execute code present on the Hub on your local machine."
112
+ )
113
+ },
114
+ )
115
+
116
+
117
+ @dataclass
118
+ class DataTrainingArguments:
119
+ """
120
+ Arguments pertaining to what data we are going to input our model for training and eval.
121
+ """
122
+
123
+ source_lang: str = field(default=None, metadata={"help": "Source language id for translation."})
124
+ target_lang: str = field(default=None, metadata={"help": "Target language id for translation."})
125
+ dataset_name: Optional[str] = field(
126
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
127
+ )
128
+ dataset_config_name: Optional[str] = field(
129
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
130
+ )
131
+ train_file: Optional[str] = field(
132
+ default=None, metadata={"help": "The input training data file (a jsonlines or csv file)."}
133
+ )
134
+ validation_file: Optional[str] = field(
135
+ default=None,
136
+ metadata={
137
+ "help": (
138
+ "An optional input evaluation data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
139
+ )
140
+ },
141
+ )
142
+ test_file: Optional[str] = field(
143
+ default=None,
144
+ metadata={
145
+ "help": "An optional input test data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
146
+ },
147
+ )
148
+ overwrite_cache: bool = field(
149
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
150
+ )
151
+ preprocessing_num_workers: Optional[int] = field(
152
+ default=None,
153
+ metadata={"help": "The number of processes to use for the preprocessing."},
154
+ )
155
+ max_source_length: Optional[int] = field(
156
+ default=1024,
157
+ metadata={
158
+ "help": (
159
+ "The maximum total input sequence length after tokenization. Sequences longer "
160
+ "than this will be truncated, sequences shorter will be padded."
161
+ )
162
+ },
163
+ )
164
+ max_target_length: Optional[int] = field(
165
+ default=128,
166
+ metadata={
167
+ "help": (
168
+ "The maximum total sequence length for target text after tokenization. Sequences longer "
169
+ "than this will be truncated, sequences shorter will be padded."
170
+ )
171
+ },
172
+ )
173
+ val_max_target_length: Optional[int] = field(
174
+ default=None,
175
+ metadata={
176
+ "help": (
177
+ "The maximum total sequence length for validation target text after tokenization. Sequences longer "
178
+ "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`. "
179
+ "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
180
+ "during ``evaluate`` and ``predict``."
181
+ )
182
+ },
183
+ )
184
+ pad_to_max_length: bool = field(
185
+ default=False,
186
+ metadata={
187
+ "help": (
188
+ "Whether to pad all samples to model maximum sentence length. "
189
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
190
+ "efficient on GPU but very bad for TPU."
191
+ )
192
+ },
193
+ )
194
+ max_train_samples: Optional[int] = field(
195
+ default=None,
196
+ metadata={
197
+ "help": (
198
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
199
+ "value if set."
200
+ )
201
+ },
202
+ )
203
+ max_eval_samples: Optional[int] = field(
204
+ default=None,
205
+ metadata={
206
+ "help": (
207
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
208
+ "value if set."
209
+ )
210
+ },
211
+ )
212
+ max_predict_samples: Optional[int] = field(
213
+ default=None,
214
+ metadata={
215
+ "help": (
216
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
217
+ "value if set."
218
+ )
219
+ },
220
+ )
221
+ num_beams: Optional[int] = field(
222
+ default=1,
223
+ metadata={
224
+ "help": (
225
+ "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
226
+ "which is used during ``evaluate`` and ``predict``."
227
+ )
228
+ },
229
+ )
230
+ ignore_pad_token_for_loss: bool = field(
231
+ default=True,
232
+ metadata={
233
+ "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
234
+ },
235
+ )
236
+ source_prefix: Optional[str] = field(
237
+ default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
238
+ )
239
+ forced_bos_token: Optional[str] = field(
240
+ default=None,
241
+ metadata={
242
+ "help": (
243
+ "The token to force as the first generated token after the :obj:`decoder_start_token_id`.Useful for"
244
+ " multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token needs to"
245
+ " be the target language token.(Usually it is the target language token)"
246
+ )
247
+ },
248
+ )
249
+
250
+ def __post_init__(self):
251
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
252
+ raise ValueError("Need either a dataset name or a training/validation file.")
253
+ else:
254
+ if self.train_file is not None:
255
+ extension = self.train_file.split(".")[-1]
256
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
257
+ if self.validation_file is not None:
258
+ extension = self.validation_file.split(".")[-1]
259
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
260
+ if self.val_max_target_length is None:
261
+ self.val_max_target_length = self.max_target_length
262
+
263
+
264
+ # endregion
265
+
266
+
267
+ def main():
268
+ # region Argument parsing
269
+ # See all possible arguments in src/transformers/training_args.py
270
+ # or by passing the --help flag to this script.
271
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
272
+
273
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
274
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
275
+ # If we pass only one argument to the script and it's the path to a json file,
276
+ # let's parse it to get our arguments.
277
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
278
+ else:
279
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
280
+
281
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
282
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
283
+ send_example_telemetry("run_translation", model_args, data_args, framework="tensorflow")
284
+ # endregion
285
+
286
+ # region Logging
287
+ logging.basicConfig(
288
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
289
+ datefmt="%m/%d/%Y %H:%M:%S",
290
+ handlers=[logging.StreamHandler(sys.stdout)],
291
+ )
292
+ logger.setLevel(logging.INFO)
293
+ datasets.utils.logging.set_verbosity(logging.INFO)
294
+ transformers.utils.logging.set_verbosity(logging.INFO)
295
+
296
+ # Log on each process the small summary:
297
+ logger.info(f"Training/evaluation parameters {training_args}")
298
+ # endregion
299
+
300
+ # region Detecting last checkpoint
301
+ last_checkpoint = None
302
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
303
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
304
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
305
+ raise ValueError(
306
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
307
+ "Use --overwrite_output_dir to overcome."
308
+ )
309
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
310
+ logger.info(
311
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
312
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
313
+ )
314
+ # endregion
315
+
316
+ # Set seed before initializing model.
317
+ set_seed(training_args.seed)
318
+
319
+ # region Load datasets
320
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
321
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
322
+ # (the dataset will be downloaded automatically from the datasets Hub).
323
+ #
324
+ # For CSV/JSON files this script will use the first column for the full texts and the second column for the
325
+ # summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments).
326
+ #
327
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
328
+ # download the dataset.
329
+ if data_args.dataset_name is not None:
330
+ # Downloading and loading a dataset from the hub.
331
+ raw_datasets = load_dataset(
332
+ data_args.dataset_name,
333
+ data_args.dataset_config_name,
334
+ cache_dir=model_args.cache_dir,
335
+ token=model_args.token,
336
+ trust_remote_code=model_args.trust_remote_code,
337
+ )
338
+ else:
339
+ data_files = {}
340
+ if data_args.train_file is not None:
341
+ data_files["train"] = data_args.train_file
342
+ extension = data_args.train_file.split(".")[-1]
343
+ if data_args.validation_file is not None:
344
+ data_files["validation"] = data_args.validation_file
345
+ extension = data_args.validation_file.split(".")[-1]
346
+ raw_datasets = load_dataset(
347
+ extension,
348
+ data_files=data_files,
349
+ cache_dir=model_args.cache_dir,
350
+ token=model_args.token,
351
+ )
352
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
353
+ # https://huggingface.co/docs/datasets/loading
354
+ # endregion
355
+
356
+ # region Load model config and tokenizer
357
+ #
358
+ # Distributed training:
359
+ # The .from_pretrained methods guarantee that only one local process can concurrently
360
+ # download model & vocab.
361
+
362
+ config = AutoConfig.from_pretrained(
363
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
364
+ cache_dir=model_args.cache_dir,
365
+ revision=model_args.model_revision,
366
+ token=model_args.token,
367
+ trust_remote_code=model_args.trust_remote_code,
368
+ )
369
+ tokenizer = AutoTokenizer.from_pretrained(
370
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
371
+ cache_dir=model_args.cache_dir,
372
+ use_fast=model_args.use_fast_tokenizer,
373
+ revision=model_args.model_revision,
374
+ token=model_args.token,
375
+ trust_remote_code=model_args.trust_remote_code,
376
+ )
377
+
378
+ prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
379
+ # endregion
380
+
381
+ # region Dataset preprocessing
382
+ # We need to tokenize inputs and targets.
383
+ if training_args.do_train:
384
+ column_names = raw_datasets["train"].column_names
385
+ elif training_args.do_eval:
386
+ column_names = raw_datasets["validation"].column_names
387
+ else:
388
+ logger.info("There is nothing to do. Please pass `do_train`, and/or `do_eval`.")
389
+ return
390
+
391
+ column_names = raw_datasets["train"].column_names
392
+
393
+ # For translation we set the codes of our source and target languages (only useful for mBART, the others will
394
+ # ignore those attributes).
395
+ if isinstance(tokenizer, tuple(MULTILINGUAL_TOKENIZERS)):
396
+ assert data_args.target_lang is not None and data_args.source_lang is not None, (
397
+ f"{tokenizer.__class__.__name__} is a multilingual tokenizer which requires --source_lang and "
398
+ "--target_lang arguments."
399
+ )
400
+ tokenizer.src_lang = data_args.source_lang
401
+ tokenizer.tgt_lang = data_args.target_lang
402
+ forced_bos_token_id = (
403
+ tokenizer.lang_code_to_id[data_args.forced_bos_token] if data_args.forced_bos_token is not None else None
404
+ )
405
+
406
+ # Get the language codes for input/target.
407
+ source_lang = data_args.source_lang.split("_")[0]
408
+ target_lang = data_args.target_lang.split("_")[0]
409
+
410
+ padding = "max_length" if data_args.pad_to_max_length else False
411
+
412
+ # Temporarily set max_target_length for training.
413
+ max_target_length = data_args.max_target_length
414
+ padding = "max_length" if data_args.pad_to_max_length else False
415
+
416
+ def preprocess_function(examples):
417
+ inputs = [ex[source_lang] for ex in examples["translation"]]
418
+ targets = [ex[target_lang] for ex in examples["translation"]]
419
+ inputs = [prefix + inp for inp in inputs]
420
+ model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True)
421
+
422
+ # Tokenize targets with the `text_target` keyword argument
423
+ labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True)
424
+
425
+ # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
426
+ # padding in the loss.
427
+ if padding == "max_length" and data_args.ignore_pad_token_for_loss:
428
+ labels["input_ids"] = [
429
+ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
430
+ ]
431
+
432
+ model_inputs["labels"] = labels["input_ids"]
433
+ return model_inputs
434
+
435
+ if training_args.do_train:
436
+ if "train" not in raw_datasets:
437
+ raise ValueError("--do_train requires a train dataset")
438
+ train_dataset = raw_datasets["train"]
439
+ if data_args.max_train_samples is not None:
440
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
441
+ train_dataset = train_dataset.select(range(max_train_samples))
442
+ train_dataset = train_dataset.map(
443
+ preprocess_function,
444
+ batched=True,
445
+ num_proc=data_args.preprocessing_num_workers,
446
+ remove_columns=column_names,
447
+ load_from_cache_file=not data_args.overwrite_cache,
448
+ desc="Running tokenizer on train dataset",
449
+ )
450
+ else:
451
+ train_dataset = None
452
+
453
+ if training_args.do_eval:
454
+ max_target_length = data_args.val_max_target_length
455
+ if "validation" not in raw_datasets:
456
+ raise ValueError("--do_eval requires a validation dataset")
457
+ eval_dataset = raw_datasets["validation"]
458
+ if data_args.max_eval_samples is not None:
459
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
460
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
461
+ eval_dataset = eval_dataset.map(
462
+ preprocess_function,
463
+ batched=True,
464
+ num_proc=data_args.preprocessing_num_workers,
465
+ remove_columns=column_names,
466
+ load_from_cache_file=not data_args.overwrite_cache,
467
+ desc="Running tokenizer on validation dataset",
468
+ )
469
+ else:
470
+ eval_dataset = None
471
+ # endregion
472
+
473
+ with training_args.strategy.scope():
474
+ # region Prepare model
475
+ model = TFAutoModelForSeq2SeqLM.from_pretrained(
476
+ model_args.model_name_or_path,
477
+ config=config,
478
+ cache_dir=model_args.cache_dir,
479
+ revision=model_args.model_revision,
480
+ token=model_args.token,
481
+ trust_remote_code=model_args.trust_remote_code,
482
+ )
483
+
484
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
485
+ # on a small vocab and want a smaller embedding size, remove this test.
486
+ embeddings = model.get_input_embeddings()
487
+
488
+ # Matt: This is a temporary workaround as we transition our models to exclusively using Keras embeddings.
489
+ # As soon as the transition is complete, all embeddings should be keras.Embeddings layers, and
490
+ # the weights will always be in embeddings.embeddings.
491
+ if hasattr(embeddings, "embeddings"):
492
+ embedding_size = embeddings.embeddings.shape[0]
493
+ else:
494
+ embedding_size = embeddings.weight.shape[0]
495
+ if len(tokenizer) > embedding_size:
496
+ model.resize_token_embeddings(len(tokenizer))
497
+
498
+ if isinstance(tokenizer, tuple(MULTILINGUAL_TOKENIZERS)):
499
+ model.config.forced_bos_token_id = forced_bos_token_id
500
+ # endregion
501
+
502
+ # region Set decoder_start_token_id
503
+ if model.config.decoder_start_token_id is None and isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)):
504
+ assert (
505
+ data_args.target_lang is not None and data_args.source_lang is not None
506
+ ), "mBart requires --target_lang and --source_lang"
507
+ if isinstance(tokenizer, MBartTokenizer):
508
+ model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.target_lang]
509
+ else:
510
+ model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(data_args.target_lang)
511
+
512
+ if model.config.decoder_start_token_id is None:
513
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
514
+ # endregion
515
+
516
+ # region Prepare TF Dataset objects
517
+ label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id
518
+ data_collator = DataCollatorForSeq2Seq(
519
+ tokenizer,
520
+ model=model,
521
+ label_pad_token_id=label_pad_token_id,
522
+ pad_to_multiple_of=64, # Reduce the number of unique shapes for XLA, especially for generation
523
+ return_tensors="np",
524
+ )
525
+ num_replicas = training_args.strategy.num_replicas_in_sync
526
+ total_train_batch_size = training_args.per_device_train_batch_size * num_replicas
527
+ total_eval_batch_size = training_args.per_device_eval_batch_size * num_replicas
528
+
529
+ dataset_options = tf.data.Options()
530
+ dataset_options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF
531
+
532
+ # model.prepare_tf_dataset() wraps a Hugging Face dataset in a tf.data.Dataset which is ready to use in
533
+ # training. This is the recommended way to use a Hugging Face dataset when training with Keras. You can also
534
+ # use the lower-level dataset.to_tf_dataset() method, but you will have to specify things like column names
535
+ # yourself if you use this method, whereas they are automatically inferred from the model input names when
536
+ # using model.prepare_tf_dataset()
537
+ # For more info see the docs:
538
+ # https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset
539
+ # https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset
540
+
541
+ tf_train_dataset = model.prepare_tf_dataset(
542
+ train_dataset,
543
+ collate_fn=data_collator,
544
+ batch_size=total_train_batch_size,
545
+ shuffle=True,
546
+ ).with_options(dataset_options)
547
+ tf_eval_dataset = model.prepare_tf_dataset(
548
+ eval_dataset, collate_fn=data_collator, batch_size=total_eval_batch_size, shuffle=False
549
+ ).with_options(dataset_options)
550
+ # endregion
551
+
552
+ # region Optimizer and LR scheduling
553
+ num_train_steps = int(len(tf_train_dataset) * training_args.num_train_epochs)
554
+ if training_args.warmup_steps > 0:
555
+ num_warmup_steps = training_args.warmup_steps
556
+ elif training_args.warmup_ratio > 0:
557
+ num_warmup_steps = int(num_train_steps * training_args.warmup_ratio)
558
+ else:
559
+ num_warmup_steps = 0
560
+ if training_args.do_train:
561
+ optimizer, lr_schedule = create_optimizer(
562
+ init_lr=training_args.learning_rate,
563
+ num_train_steps=num_train_steps,
564
+ num_warmup_steps=num_warmup_steps,
565
+ adam_beta1=training_args.adam_beta1,
566
+ adam_beta2=training_args.adam_beta2,
567
+ adam_epsilon=training_args.adam_epsilon,
568
+ weight_decay_rate=training_args.weight_decay,
569
+ adam_global_clipnorm=training_args.max_grad_norm,
570
+ )
571
+ else:
572
+ optimizer = "sgd" # Just write anything because we won't be using it
573
+ # endregion
574
+
575
+ # region Metric and postprocessing
576
+ if training_args.do_eval:
577
+ metric = evaluate.load("sacrebleu", cache_dir=model_args.cache_dir)
578
+
579
+ if data_args.val_max_target_length is None:
580
+ data_args.val_max_target_length = data_args.max_target_length
581
+
582
+ gen_kwargs = {
583
+ "max_length": data_args.val_max_target_length,
584
+ "num_beams": data_args.num_beams,
585
+ "no_repeat_ngram_size": 0, # Not supported under XLA right now, and some models set it by default
586
+ }
587
+
588
+ def postprocess_text(preds, labels):
589
+ preds = [pred.strip() for pred in preds]
590
+ labels = [[label.strip()] for label in labels]
591
+
592
+ return preds, labels
593
+
594
+ def compute_metrics(preds):
595
+ predictions, labels = preds
596
+ if isinstance(predictions, tuple):
597
+ predictions = predictions[0]
598
+ decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
599
+ labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
600
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
601
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
602
+ metrics = metric.compute(predictions=decoded_preds, references=decoded_labels)
603
+ return {"bleu": metrics["score"]}
604
+
605
+ # The KerasMetricCallback allows metrics that are too complex to write as standard Keras metrics
606
+ # to be computed each epoch. Any Python code can be included in the metric_fn. This is especially
607
+ # useful for metrics like BLEU and ROUGE that perform string comparisons on decoded model outputs.
608
+ # For more information, see the docs at
609
+ # https://huggingface.co/docs/transformers/main_classes/keras_callbacks#transformers.KerasMetricCallback
610
+
611
+ metric_callback = KerasMetricCallback(
612
+ metric_fn=compute_metrics,
613
+ eval_dataset=tf_eval_dataset,
614
+ predict_with_generate=True,
615
+ use_xla_generation=True,
616
+ generate_kwargs=gen_kwargs,
617
+ )
618
+ callbacks = [metric_callback]
619
+ else:
620
+ callbacks = []
621
+
622
+ # endregion
623
+
624
+ # region Preparing push_to_hub and model card
625
+ push_to_hub_model_id = training_args.push_to_hub_model_id
626
+ model_name = model_args.model_name_or_path.split("/")[-1]
627
+ if not push_to_hub_model_id:
628
+ push_to_hub_model_id = f"{model_name}-finetuned-{data_args.source_lang}-{data_args.target_lang}"
629
+
630
+ model_card_kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "translation"}
631
+ if data_args.dataset_name is not None:
632
+ model_card_kwargs["dataset_tags"] = data_args.dataset_name
633
+ if data_args.dataset_config_name is not None:
634
+ model_card_kwargs["dataset_args"] = data_args.dataset_config_name
635
+ model_card_kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
636
+ else:
637
+ model_card_kwargs["dataset"] = data_args.dataset_name
638
+
639
+ languages = [l for l in [data_args.source_lang, data_args.target_lang] if l is not None]
640
+ if len(languages) > 0:
641
+ model_card_kwargs["language"] = languages
642
+
643
+ if training_args.push_to_hub:
644
+ # Because this training can be quite long, we save once per epoch.
645
+ callbacks.append(
646
+ PushToHubCallback(
647
+ output_dir=training_args.output_dir,
648
+ hub_model_id=push_to_hub_model_id,
649
+ hub_token=training_args.push_to_hub_token,
650
+ tokenizer=tokenizer,
651
+ **model_card_kwargs,
652
+ )
653
+ )
654
+ # endregion
655
+
656
+ # region Training
657
+ eval_metrics = None
658
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
659
+ # use this for training unless you specify your own loss function in compile().
660
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
661
+
662
+ if training_args.do_train:
663
+ logger.info("***** Running training *****")
664
+ logger.info(f" Num examples = {len(train_dataset)}")
665
+ logger.info(f" Num Epochs = {training_args.num_train_epochs}")
666
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
667
+ logger.info(f" Total train batch size = {total_train_batch_size}")
668
+ logger.info(f" Total optimization steps = {num_train_steps}")
669
+
670
+ if training_args.xla and not data_args.pad_to_max_length:
671
+ logger.warning(
672
+ "XLA training may be slow at first when --pad_to_max_length is not set "
673
+ "until all possible shapes have been compiled."
674
+ )
675
+
676
+ history = model.fit(tf_train_dataset, epochs=int(training_args.num_train_epochs), callbacks=callbacks)
677
+ eval_metrics = {key: val[-1] for key, val in history.history.items()}
678
+ # endregion
679
+
680
+ # region Validation
681
+ if training_args.do_eval and not training_args.do_train:
682
+ # Compiling generation with XLA yields enormous speedups, see https://huggingface.co/blog/tf-xla-generate
683
+ @tf.function(jit_compile=True)
684
+ def generate(**kwargs):
685
+ return model.generate(**kwargs)
686
+
687
+ if training_args.do_eval:
688
+ logger.info("Evaluation...")
689
+ for batch, labels in tf_eval_dataset:
690
+ batch.update(gen_kwargs)
691
+ generated_tokens = generate(**batch)
692
+ if isinstance(generated_tokens, tuple):
693
+ generated_tokens = generated_tokens[0]
694
+ decoded_preds = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
695
+ labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
696
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
697
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
698
+
699
+ metric.add_batch(predictions=decoded_preds, references=decoded_labels)
700
+
701
+ eval_metrics = metric.compute()
702
+ logger.info({"bleu": eval_metrics["score"]})
703
+ # endregion
704
+
705
+ if training_args.output_dir is not None and eval_metrics is not None:
706
+ output_eval_file = os.path.join(training_args.output_dir, "all_results.json")
707
+ with open(output_eval_file, "w") as writer:
708
+ writer.write(json.dumps(eval_metrics))
709
+
710
+ if training_args.output_dir is not None and not training_args.push_to_hub:
711
+ # If we're not pushing to hub, at least save a local copy when we're done
712
+ model.save_pretrained(training_args.output_dir)
713
+
714
+
715
+ if __name__ == "__main__":
716
+ main()
tasks/tasksmith-441eeab80047/tests/source/examples/training/distributed_training.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+
7
+
8
+ # Environment variables set by torch.distributed.launch
9
+ LOCAL_RANK = int(os.environ["LOCAL_RANK"])
10
+ WORLD_SIZE = int(os.environ["WORLD_SIZE"])
11
+ WORLD_RANK = int(os.environ["RANK"])
12
+
13
+ LOCAL_RANK = int(os.environ["OMPI_COMM_WORLD_LOCAL_RANK"])
14
+ WORLD_SIZE = int(os.environ["OMPI_COMM_WORLD_SIZE"])
15
+ WORLD_RANK = int(os.environ["OMPI_COMM_WORLD_RANK"])
16
+
17
+
18
+ def run(backend):
19
+ tensor = torch.zeros(1)
20
+ # Need to put tensor on a GPU device for nccl backend
21
+ if backend == "nccl":
22
+ device = torch.device("cuda:{}".format(LOCAL_RANK))
23
+ tensor = tensor.to(device)
24
+
25
+ if WORLD_RANK == 0:
26
+ for rank_recv in range(1, WORLD_SIZE):
27
+ dist.send(tensor=tensor, dst=rank_recv)
28
+ print("worker_{} sent data to Rank {}\n".format(0, rank_recv))
29
+ else:
30
+ dist.recv(tensor=tensor, src=0)
31
+ print("worker_{} has received data from rank {}\n".format(WORLD_RANK, 0))
32
+
33
+
34
+ def init_processes(backend):
35
+ dist.init_process_group(backend, rank=WORLD_RANK, world_size=WORLD_SIZE)
36
+ run(backend)
37
+
38
+
39
+ if __name__ == "__main__":
40
+ parser = argparse.ArgumentParser()
41
+ parser.add_argument(
42
+ "--local_rank", type=int, help="Local rank. Necessary for using the torch.distributed.launch utility."
43
+ )
44
+ parser.add_argument("--backend", type=str, default="nccl", choices=["nccl", "gloo"])
45
+ args = parser.parse_args()
46
+
47
+ init_processes(backend=args.backend)
48
+
49
+ """"
50
+ python-m torch.distributed.launch \
51
+ --nproc_per_node=2 --nnodes=2 --node_rank=0 \
52
+ test_compile.py
53
+
54
+ python3 -m torch.distributed.launch \
55
+ --nproc_per_node=2 --nnodes=2 --node_rank=1 \
56
+ --master_addr=104.171.200.62 --master_port=1234 \
57
+ main.py \
58
+ --backend=nccl --use_syn --batch_size=8192 --arch=resnet152
59
+
60
+
61
+
62
+ mpirun -np 4 \
63
+ -H 104.171.200.62:2,104.171.200.182:2 \
64
+ -x MASTER_ADDR=104.171.200.62 \
65
+ -x MASTER_PORT=1234 \
66
+ -x PATH \
67
+ -bind-to none -map-by slot \
68
+ -mca pml ob1 -mca btl ^openib \
69
+ python3 main.py
70
+ """
71
+
72
+
73
+ """"
74
+ You need a host file with the name of hosts.
75
+ for example I have arthur@ip-26-0-162-46 and arthur@ip-26-0-162-239
76
+
77
+ ________
78
+ hostfile
79
+ ip-26-0-162-46 slots=8
80
+ ip-26-0-162-239 slots=8
81
+ ________
82
+
83
+ mpirun --hostfile hostfile -np 16 \
84
+ --bind-to none --map-by slot \
85
+ -x MASTER_ADDR=<master-node-ip> \
86
+ -x MASTER_PORT=29500 \
87
+ -x NCCL_DEBUG=INFO \
88
+ -x NCCL_SOCKET_IFNAME=^lo,docker0 \
89
+ -x CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
90
+ python your_script.py --backend nccl
91
+
92
+
93
+ to get the master IP you need to do a few things:
94
+ hostname -I | awk '{print $1}'
95
+
96
+
97
+ Use `ping ip-26-0-162-46` to check if connected
98
+
99
+ 26.0.162.46
100
+
101
+ mpirun --hostfile hostfile -np 16 \
102
+ --bind-to none --map-by slot \
103
+ -x MASTER_ADDR=26.0.162.46 \
104
+ -x MASTER_PORT=29500 \
105
+ -x NCCL_DEBUG=INFO \
106
+ -x NCCL_SOCKET_IFNAME=^lo,docker0 \
107
+ -x CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
108
+ python your_script.py --backend nccl
109
+
110
+
111
+ mpirun --hostfile hostfile -np 2 -x NCCL_DEBUG=INFO python -c "import os;print(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])" -b 8 -e 128M -f 2 -g 1
112
+ to test your setup
113
+ """
tasks/tasksmith-441eeab80047/tests/source/hubconf.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import sys
17
+
18
+
19
+ SRC_DIR = os.path.join(os.path.dirname(__file__), "src")
20
+ sys.path.append(SRC_DIR)
21
+
22
+
23
+ from transformers import (
24
+ AutoConfig,
25
+ AutoModel,
26
+ AutoModelForCausalLM,
27
+ AutoModelForMaskedLM,
28
+ AutoModelForQuestionAnswering,
29
+ AutoModelForSequenceClassification,
30
+ AutoTokenizer,
31
+ add_start_docstrings,
32
+ )
33
+
34
+
35
+ dependencies = ["torch", "numpy", "tokenizers", "filelock", "requests", "tqdm", "regex", "sentencepiece", "sacremoses", "importlib_metadata", "huggingface_hub"]
36
+
37
+
38
+ @add_start_docstrings(AutoConfig.__doc__)
39
+ def config(*args, **kwargs):
40
+ r"""
41
+ # Using torch.hub !
42
+ import torch
43
+
44
+ config = torch.hub.load('huggingface/transformers', 'config', 'google-bert/bert-base-uncased') # Download configuration from huggingface.co and cache.
45
+ config = torch.hub.load('huggingface/transformers', 'config', './test/bert_saved_model/') # E.g. config (or model) was saved using `save_pretrained('./test/saved_model/')`
46
+ config = torch.hub.load('huggingface/transformers', 'config', './test/bert_saved_model/my_configuration.json')
47
+ config = torch.hub.load('huggingface/transformers', 'config', 'google-bert/bert-base-uncased', output_attentions=True, foo=False)
48
+ assert config.output_attentions == True
49
+ config, unused_kwargs = torch.hub.load('huggingface/transformers', 'config', 'google-bert/bert-base-uncased', output_attentions=True, foo=False, return_unused_kwargs=True)
50
+ assert config.output_attentions == True
51
+ assert unused_kwargs == {'foo': False}
52
+
53
+ """
54
+
55
+ return AutoConfig.from_pretrained(*args, **kwargs)
56
+
57
+
58
+ @add_start_docstrings(AutoTokenizer.__doc__)
59
+ def tokenizer(*args, **kwargs):
60
+ r"""
61
+ # Using torch.hub !
62
+ import torch
63
+
64
+ tokenizer = torch.hub.load('huggingface/transformers', 'tokenizer', 'google-bert/bert-base-uncased') # Download vocabulary from huggingface.co and cache.
65
+ tokenizer = torch.hub.load('huggingface/transformers', 'tokenizer', './test/bert_saved_model/') # E.g. tokenizer was saved using `save_pretrained('./test/saved_model/')`
66
+
67
+ """
68
+
69
+ return AutoTokenizer.from_pretrained(*args, **kwargs)
70
+
71
+
72
+ @add_start_docstrings(AutoModel.__doc__)
73
+ def model(*args, **kwargs):
74
+ r"""
75
+ # Using torch.hub !
76
+ import torch
77
+
78
+ model = torch.hub.load('huggingface/transformers', 'model', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
79
+ model = torch.hub.load('huggingface/transformers', 'model', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
80
+ model = torch.hub.load('huggingface/transformers', 'model', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
81
+ assert model.config.output_attentions == True
82
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
83
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
84
+ model = torch.hub.load('huggingface/transformers', 'model', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
85
+
86
+ """
87
+
88
+ return AutoModel.from_pretrained(*args, **kwargs)
89
+
90
+
91
+ @add_start_docstrings(AutoModelForCausalLM.__doc__)
92
+ def modelForCausalLM(*args, **kwargs):
93
+ r"""
94
+ # Using torch.hub !
95
+ import torch
96
+
97
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', 'openai-community/gpt2') # Download model and configuration from huggingface.co and cache.
98
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', './test/saved_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
99
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', 'openai-community/gpt2', output_attentions=True) # Update configuration during loading
100
+ assert model.config.output_attentions == True
101
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
102
+ config = AutoConfig.from_pretrained('./tf_model/gpt_tf_model_config.json')
103
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', './tf_model/gpt_tf_checkpoint.ckpt.index', from_tf=True, config=config)
104
+
105
+ """
106
+ return AutoModelForCausalLM.from_pretrained(*args, **kwargs)
107
+
108
+
109
+ @add_start_docstrings(AutoModelForMaskedLM.__doc__)
110
+ def modelForMaskedLM(*args, **kwargs):
111
+ r"""
112
+ # Using torch.hub !
113
+ import torch
114
+
115
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
116
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
117
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
118
+ assert model.config.output_attentions == True
119
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
120
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
121
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
122
+
123
+ """
124
+
125
+ return AutoModelForMaskedLM.from_pretrained(*args, **kwargs)
126
+
127
+
128
+ @add_start_docstrings(AutoModelForSequenceClassification.__doc__)
129
+ def modelForSequenceClassification(*args, **kwargs):
130
+ r"""
131
+ # Using torch.hub !
132
+ import torch
133
+
134
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
135
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
136
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
137
+ assert model.config.output_attentions == True
138
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
139
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
140
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
141
+
142
+ """
143
+
144
+ return AutoModelForSequenceClassification.from_pretrained(*args, **kwargs)
145
+
146
+
147
+ @add_start_docstrings(AutoModelForQuestionAnswering.__doc__)
148
+ def modelForQuestionAnswering(*args, **kwargs):
149
+ r"""
150
+ # Using torch.hub !
151
+ import torch
152
+
153
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
154
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
155
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
156
+ assert model.config.output_attentions == True
157
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
158
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
159
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
160
+
161
+ """
162
+ return AutoModelForQuestionAnswering.from_pretrained(*args, **kwargs)