moved model from pere/nb-bert-roberta-base-scandinavian-long
Browse files- README.md +68 -0
- config.json +28 -0
- create_config.py +6 -0
- events.out.tfevents.1637101724.t1v-n-358ff5d1-w-0.857283.3.v2 +3 -0
- events.out.tfevents.1637157195.t1v-n-358ff5d1-w-0.908301.3.v2 +3 -0
- events.out.tfevents.1637704340.t1v-n-358ff5d1-w-0.1392746.3.v2 +3 -0
- flax_model.msgpack +3 -0
- generate_pytorch_model.py +7 -0
- merges.txt +0 -0
- pytorch_model.bin +3 -0
- run_mlm_flax.py +680 -0
- run_mlm_flax_stream.py +638 -0
- run_stream_128.sh +25 -0
- run_stream_512.sh +25 -0
- special_tokens_map.json +1 -0
- tokenizer.json +0 -0
- tokenizer_config.json +1 -0
- train_tokenizer.py +28 -0
- vocab.json +0 -0
README.md
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This is just a Test Model. Do NOT use for anything!
|
2 |
+
|
3 |
+
Continued pretrained from the nb-roberta-base.
|
4 |
+
|
5 |
+
The domain specific pretraining is done on the 102GB (Scandinavian corpus)[https://huggingface.co/datasets/NbAiLab/scandinavian].
|
6 |
+
|
7 |
+
## Train for 180k steps for 128 sequences:
|
8 |
+
```bash
|
9 |
+
./run_mlm_flax_stream.py \
|
10 |
+
--output_dir="./" \
|
11 |
+
--model_type="roberta" \
|
12 |
+
--config_name="./" \
|
13 |
+
--tokenizer_name="./" \
|
14 |
+
--model_name_or_path="./" \
|
15 |
+
--dataset_name="NbAiLab/scandinavian" \
|
16 |
+
--max_seq_length="128" \
|
17 |
+
--weight_decay="0.01" \
|
18 |
+
--per_device_train_batch_size="128" \
|
19 |
+
--per_device_eval_batch_size="128" \
|
20 |
+
--learning_rate="6e-5" \
|
21 |
+
--warmup_steps="5000" \
|
22 |
+
--overwrite_output_dir \
|
23 |
+
--cache_dir /mnt/disks/flaxdisk/cache/ \
|
24 |
+
--num_train_steps="180000" \
|
25 |
+
--adam_beta1="0.9" \
|
26 |
+
--adam_beta2="0.98" \
|
27 |
+
--logging_steps="10000" \
|
28 |
+
--save_steps="10000" \
|
29 |
+
--eval_steps="10000" \
|
30 |
+
--preprocessing_num_workers 96 \
|
31 |
+
--auth_token True \
|
32 |
+
--adafactor \
|
33 |
+
--push_to_hub
|
34 |
+
```
|
35 |
+
## Train for 20k steps for 512 sequences:
|
36 |
+
```bash
|
37 |
+
./run_mlm_flax_stream.py \
|
38 |
+
--output_dir="./" \
|
39 |
+
--model_type="roberta" \
|
40 |
+
--config_name="./" \
|
41 |
+
--tokenizer_name="./" \
|
42 |
+
--model_name_or_path="./" \
|
43 |
+
--dataset_name="NbAiLab/scandinavian" \
|
44 |
+
--max_seq_length="512" \
|
45 |
+
--weight_decay="0.01" \
|
46 |
+
--per_device_train_batch_size="48" \
|
47 |
+
--per_device_eval_batch_size="48" \
|
48 |
+
--learning_rate="3e-5" \
|
49 |
+
--warmup_steps="5000" \
|
50 |
+
--overwrite_output_dir \
|
51 |
+
--cache_dir /mnt/disks/flaxdisk/cache/ \
|
52 |
+
--num_train_steps="20000" \
|
53 |
+
--adam_beta1="0.9" \
|
54 |
+
--adam_beta2="0.98" \
|
55 |
+
--logging_steps="20000" \
|
56 |
+
--save_steps="10000" \
|
57 |
+
--eval_steps="10000" \
|
58 |
+
--preprocessing_num_workers 96 \
|
59 |
+
--auth_token True \
|
60 |
+
--adafactor \
|
61 |
+
--push_to_hub
|
62 |
+
```
|
63 |
+
|
64 |
+
|
65 |
+
|
66 |
+
Approximate additional training time: 1 week.
|
67 |
+
|
68 |
+
|
config.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": ".",
|
3 |
+
"architectures": [
|
4 |
+
"RobertaForMaskedLM"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"bos_token_id": 0,
|
8 |
+
"classifier_dropout": null,
|
9 |
+
"eos_token_id": 2,
|
10 |
+
"gradient_checkpointing": false,
|
11 |
+
"hidden_act": "gelu",
|
12 |
+
"hidden_dropout_prob": 0.1,
|
13 |
+
"hidden_size": 768,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 3072,
|
16 |
+
"layer_norm_eps": 1e-05,
|
17 |
+
"max_position_embeddings": 514,
|
18 |
+
"model_type": "roberta",
|
19 |
+
"num_attention_heads": 12,
|
20 |
+
"num_hidden_layers": 12,
|
21 |
+
"pad_token_id": 1,
|
22 |
+
"position_embedding_type": "absolute",
|
23 |
+
"torch_dtype": "float32",
|
24 |
+
"transformers_version": "4.13.0.dev0",
|
25 |
+
"type_vocab_size": 1,
|
26 |
+
"use_cache": true,
|
27 |
+
"vocab_size": 50265
|
28 |
+
}
|
create_config.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import RobertaConfig
|
2 |
+
|
3 |
+
model_dir = "./" # ${MODEL_DIR}
|
4 |
+
|
5 |
+
config = RobertaConfig.from_pretrained("roberta-base")
|
6 |
+
config.save_pretrained(model_dir)
|
events.out.tfevents.1637101724.t1v-n-358ff5d1-w-0.857283.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:44b63ae973927ce95868a7d7123f56e8e33d3e9dad9a5cabe627c84d796f9396
|
3 |
+
size 5928006
|
events.out.tfevents.1637157195.t1v-n-358ff5d1-w-0.908301.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d5a20f58ee9305c56b75e5ee15c4c982270549bc390b0fc331fd3605cb7b4b5a
|
3 |
+
size 105772210
|
events.out.tfevents.1637704340.t1v-n-358ff5d1-w-0.1392746.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:af735f4f4a2ddde9d5811f927ea089b226643a4a66a2491fcf160a17a8a785e3
|
3 |
+
size 8908221
|
flax_model.msgpack
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:64f7ff612ca7eb3abfe9ae1d2c0088df78d9a5ab1af89b2368ceabadf34e46d4
|
3 |
+
size 498796983
|
generate_pytorch_model.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This script overwrites any existing PyTorch model. Generates a new one with an LM head from the pretrained Flax model.
|
2 |
+
from transformers import RobertaForMaskedLM, AutoTokenizer
|
3 |
+
model = RobertaForMaskedLM.from_pretrained(".",from_flax=True)
|
4 |
+
tokenizer = AutoTokenizer.from_pretrained(".")
|
5 |
+
tokenizer.save_pretrained(".")
|
6 |
+
model.save_pretrained(".")
|
7 |
+
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:95e26332a282f00db4b34330bceaec2b4bc6c2a6166aeef8692dcf9ee7a5881a
|
3 |
+
size 498872555
|
run_mlm_flax.py
ADDED
@@ -0,0 +1,680 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2021 The HuggingFace Team All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""
|
17 |
+
Fine-tuning the library models for masked language modeling (BERT, ALBERT, RoBERTa...) with whole word masking on a
|
18 |
+
text file or a dataset.
|
19 |
+
|
20 |
+
Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
|
21 |
+
https://huggingface.co/models?filter=masked-lm
|
22 |
+
"""
|
23 |
+
import logging
|
24 |
+
import os
|
25 |
+
import sys
|
26 |
+
import time
|
27 |
+
from dataclasses import dataclass, field
|
28 |
+
|
29 |
+
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
|
30 |
+
from pathlib import Path
|
31 |
+
from typing import Dict, List, Optional, Tuple
|
32 |
+
|
33 |
+
import numpy as np
|
34 |
+
from datasets import load_dataset
|
35 |
+
from tqdm import tqdm
|
36 |
+
|
37 |
+
import flax
|
38 |
+
import jax
|
39 |
+
import jax.numpy as jnp
|
40 |
+
import optax
|
41 |
+
from flax import jax_utils, traverse_util
|
42 |
+
from flax.training import train_state
|
43 |
+
from flax.training.common_utils import get_metrics, onehot, shard
|
44 |
+
from transformers import (
|
45 |
+
CONFIG_MAPPING,
|
46 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING,
|
47 |
+
AutoConfig,
|
48 |
+
AutoTokenizer,
|
49 |
+
FlaxAutoModelForMaskedLM,
|
50 |
+
HfArgumentParser,
|
51 |
+
PreTrainedTokenizerBase,
|
52 |
+
TensorType,
|
53 |
+
TrainingArguments,
|
54 |
+
is_tensorboard_available,
|
55 |
+
set_seed,
|
56 |
+
)
|
57 |
+
|
58 |
+
|
59 |
+
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
|
60 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
61 |
+
|
62 |
+
|
63 |
+
@dataclass
|
64 |
+
class ModelArguments:
|
65 |
+
"""
|
66 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
67 |
+
"""
|
68 |
+
|
69 |
+
model_name_or_path: Optional[str] = field(
|
70 |
+
default=None,
|
71 |
+
metadata={
|
72 |
+
"help": "The model checkpoint for weights initialization."
|
73 |
+
"Don't set if you want to train a model from scratch."
|
74 |
+
},
|
75 |
+
)
|
76 |
+
model_type: Optional[str] = field(
|
77 |
+
default=None,
|
78 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
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, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
88 |
+
)
|
89 |
+
use_fast_tokenizer: bool = field(
|
90 |
+
default=True,
|
91 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
92 |
+
)
|
93 |
+
dtype: Optional[str] = field(
|
94 |
+
default="float32",
|
95 |
+
metadata={
|
96 |
+
"help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
|
97 |
+
},
|
98 |
+
)
|
99 |
+
|
100 |
+
|
101 |
+
@dataclass
|
102 |
+
class DataTrainingArguments:
|
103 |
+
"""
|
104 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
105 |
+
"""
|
106 |
+
|
107 |
+
dataset_name: Optional[str] = field(
|
108 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
109 |
+
)
|
110 |
+
dataset_config_name: Optional[str] = field(
|
111 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
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 |
+
train_ref_file: Optional[str] = field(
|
119 |
+
default=None,
|
120 |
+
metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
|
121 |
+
)
|
122 |
+
validation_ref_file: Optional[str] = field(
|
123 |
+
default=None,
|
124 |
+
metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
|
125 |
+
)
|
126 |
+
overwrite_cache: bool = field(
|
127 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
128 |
+
)
|
129 |
+
validation_split_percentage: Optional[int] = field(
|
130 |
+
default=5,
|
131 |
+
metadata={
|
132 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
133 |
+
},
|
134 |
+
)
|
135 |
+
max_seq_length: Optional[int] = field(
|
136 |
+
default=None,
|
137 |
+
metadata={
|
138 |
+
"help": "The maximum total input sequence length after tokenization. Sequences longer "
|
139 |
+
"than this will be truncated. Default to the max input length of the model."
|
140 |
+
},
|
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 |
+
mlm_probability: float = field(
|
147 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
|
148 |
+
)
|
149 |
+
pad_to_max_length: bool = field(
|
150 |
+
default=False,
|
151 |
+
metadata={
|
152 |
+
"help": "Whether to pad all samples to `max_seq_length`. "
|
153 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
154 |
+
},
|
155 |
+
)
|
156 |
+
line_by_line: bool = field(
|
157 |
+
default=False,
|
158 |
+
metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
|
159 |
+
)
|
160 |
+
|
161 |
+
def __post_init__(self):
|
162 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
163 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
164 |
+
else:
|
165 |
+
if self.train_file is not None:
|
166 |
+
extension = self.train_file.split(".")[-1]
|
167 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
|
168 |
+
if self.validation_file is not None:
|
169 |
+
extension = self.validation_file.split(".")[-1]
|
170 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
|
171 |
+
|
172 |
+
|
173 |
+
@flax.struct.dataclass
|
174 |
+
class FlaxDataCollatorForLanguageModeling:
|
175 |
+
"""
|
176 |
+
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
|
177 |
+
are not all of the same length.
|
178 |
+
|
179 |
+
Args:
|
180 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
181 |
+
The tokenizer used for encoding the data.
|
182 |
+
mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
|
183 |
+
The probability with which to (randomly) mask tokens in the input.
|
184 |
+
|
185 |
+
.. note::
|
186 |
+
|
187 |
+
For best performance, this data collator should be used with a dataset having items that are dictionaries or
|
188 |
+
BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
|
189 |
+
:class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
|
190 |
+
argument :obj:`return_special_tokens_mask=True`.
|
191 |
+
"""
|
192 |
+
|
193 |
+
tokenizer: PreTrainedTokenizerBase
|
194 |
+
mlm_probability: float = 0.15
|
195 |
+
|
196 |
+
def __post_init__(self):
|
197 |
+
if self.tokenizer.mask_token is None:
|
198 |
+
raise ValueError(
|
199 |
+
"This tokenizer does not have a mask token which is necessary for masked language modeling. "
|
200 |
+
"You should pass `mlm=False` to train on causal language modeling instead."
|
201 |
+
)
|
202 |
+
|
203 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
|
204 |
+
# Handle dict or lists with proper padding and conversion to tensor.
|
205 |
+
batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
|
206 |
+
|
207 |
+
# If special token mask has been preprocessed, pop it from the dict.
|
208 |
+
special_tokens_mask = batch.pop("special_tokens_mask", None)
|
209 |
+
|
210 |
+
batch["input_ids"], batch["labels"] = self.mask_tokens(
|
211 |
+
batch["input_ids"], special_tokens_mask=special_tokens_mask
|
212 |
+
)
|
213 |
+
return batch
|
214 |
+
|
215 |
+
def mask_tokens(
|
216 |
+
self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
|
217 |
+
) -> Tuple[jnp.ndarray, jnp.ndarray]:
|
218 |
+
"""
|
219 |
+
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
|
220 |
+
"""
|
221 |
+
labels = inputs.copy()
|
222 |
+
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
|
223 |
+
probability_matrix = np.full(labels.shape, self.mlm_probability)
|
224 |
+
special_tokens_mask = special_tokens_mask.astype("bool")
|
225 |
+
|
226 |
+
probability_matrix[special_tokens_mask] = 0.0
|
227 |
+
masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
|
228 |
+
labels[~masked_indices] = -100 # We only compute loss on masked tokens
|
229 |
+
|
230 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
231 |
+
indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
|
232 |
+
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
|
233 |
+
|
234 |
+
# 10% of the time, we replace masked input tokens with random word
|
235 |
+
indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
|
236 |
+
indices_random &= masked_indices & ~indices_replaced
|
237 |
+
|
238 |
+
random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
|
239 |
+
inputs[indices_random] = random_words[indices_random]
|
240 |
+
|
241 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
242 |
+
return inputs, labels
|
243 |
+
|
244 |
+
|
245 |
+
def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
|
246 |
+
num_samples = len(samples_idx)
|
247 |
+
samples_to_remove = num_samples % batch_size
|
248 |
+
|
249 |
+
if samples_to_remove != 0:
|
250 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
251 |
+
sections_split = num_samples // batch_size
|
252 |
+
batch_idx = np.split(samples_idx, sections_split)
|
253 |
+
return batch_idx
|
254 |
+
|
255 |
+
|
256 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
257 |
+
summary_writer.scalar("train_time", train_time, step)
|
258 |
+
|
259 |
+
train_metrics = get_metrics(train_metrics)
|
260 |
+
for key, vals in train_metrics.items():
|
261 |
+
tag = f"train_{key}"
|
262 |
+
for i, val in enumerate(vals):
|
263 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
264 |
+
|
265 |
+
|
266 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
267 |
+
for metric_name, value in eval_metrics.items():
|
268 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
269 |
+
|
270 |
+
|
271 |
+
if __name__ == "__main__":
|
272 |
+
# See all possible arguments in src/transformers/training_args.py
|
273 |
+
# or by passing the --help flag to this script.
|
274 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
275 |
+
|
276 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
277 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
278 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
279 |
+
# let's parse it to get our arguments.
|
280 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
281 |
+
else:
|
282 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
283 |
+
|
284 |
+
if (
|
285 |
+
os.path.exists(training_args.output_dir)
|
286 |
+
and os.listdir(training_args.output_dir)
|
287 |
+
and training_args.do_train
|
288 |
+
and not training_args.overwrite_output_dir
|
289 |
+
):
|
290 |
+
raise ValueError(
|
291 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
292 |
+
"Use --overwrite_output_dir to overcome."
|
293 |
+
)
|
294 |
+
|
295 |
+
# Setup logging
|
296 |
+
logging.basicConfig(
|
297 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
298 |
+
level="NOTSET",
|
299 |
+
datefmt="[%X]",
|
300 |
+
)
|
301 |
+
|
302 |
+
# Log on each process the small summary:
|
303 |
+
logger = logging.getLogger(__name__)
|
304 |
+
|
305 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
306 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
307 |
+
|
308 |
+
# Set seed before initializing model.
|
309 |
+
set_seed(training_args.seed)
|
310 |
+
|
311 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
312 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
313 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
314 |
+
#
|
315 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
316 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
317 |
+
#
|
318 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
319 |
+
# download the dataset.
|
320 |
+
chunksize = 10<<20
|
321 |
+
if data_args.dataset_name is not None:
|
322 |
+
# Downloading and loading a dataset from the hub.
|
323 |
+
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, chunksize=chunksize)
|
324 |
+
|
325 |
+
if "validation" not in datasets.keys():
|
326 |
+
datasets["validation"] = load_dataset(
|
327 |
+
data_args.dataset_name,
|
328 |
+
data_args.dataset_config_name,
|
329 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
330 |
+
cache_dir=model_args.cache_dir,
|
331 |
+
chunksize=chunksize
|
332 |
+
)
|
333 |
+
datasets["train"] = load_dataset(
|
334 |
+
data_args.dataset_name,
|
335 |
+
data_args.dataset_config_name,
|
336 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
337 |
+
cache_dir=model_args.cache_dir,
|
338 |
+
chunksize=chunksize
|
339 |
+
)
|
340 |
+
else:
|
341 |
+
data_files = {}
|
342 |
+
if data_args.train_file is not None:
|
343 |
+
data_files["train"] = data_args.train_file
|
344 |
+
if data_args.validation_file is not None:
|
345 |
+
data_files["validation"] = data_args.validation_file
|
346 |
+
extension = data_args.train_file.split(".")[-1]
|
347 |
+
if extension == "txt":
|
348 |
+
extension = "text"
|
349 |
+
datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir, chunksize=chunksize)
|
350 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
351 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
352 |
+
|
353 |
+
# Load pretrained model and tokenizer
|
354 |
+
|
355 |
+
# Distributed training:
|
356 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
357 |
+
# download model & vocab.
|
358 |
+
if model_args.config_name:
|
359 |
+
config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
|
360 |
+
elif model_args.model_name_or_path:
|
361 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
|
362 |
+
else:
|
363 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
364 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
365 |
+
|
366 |
+
if model_args.tokenizer_name:
|
367 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
368 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
369 |
+
)
|
370 |
+
elif model_args.model_name_or_path:
|
371 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
372 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
373 |
+
)
|
374 |
+
else:
|
375 |
+
raise ValueError(
|
376 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
377 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
378 |
+
)
|
379 |
+
|
380 |
+
# Preprocessing the datasets.
|
381 |
+
# First we tokenize all the texts.
|
382 |
+
if training_args.do_train:
|
383 |
+
column_names = datasets["train"].column_names
|
384 |
+
else:
|
385 |
+
column_names = datasets["validation"].column_names
|
386 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
387 |
+
|
388 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
389 |
+
|
390 |
+
if data_args.line_by_line:
|
391 |
+
# When using line_by_line, we just tokenize each nonempty line.
|
392 |
+
padding = "max_length" if data_args.pad_to_max_length else False
|
393 |
+
|
394 |
+
def tokenize_function(examples):
|
395 |
+
# Remove empty lines
|
396 |
+
examples = [line for line in examples if len(line) > 0 and not line.isspace()]
|
397 |
+
return tokenizer(
|
398 |
+
examples,
|
399 |
+
return_special_tokens_mask=True,
|
400 |
+
padding=padding,
|
401 |
+
truncation=True,
|
402 |
+
max_length=max_seq_length,
|
403 |
+
)
|
404 |
+
|
405 |
+
tokenized_datasets = datasets.map(
|
406 |
+
tokenize_function,
|
407 |
+
input_columns=[text_column_name],
|
408 |
+
batched=True,
|
409 |
+
num_proc=data_args.preprocessing_num_workers,
|
410 |
+
remove_columns=column_names,
|
411 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
412 |
+
)
|
413 |
+
|
414 |
+
else:
|
415 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
416 |
+
# We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
|
417 |
+
# efficient when it receives the `special_tokens_mask`.
|
418 |
+
def tokenize_function(examples):
|
419 |
+
return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
|
420 |
+
|
421 |
+
tokenized_datasets = datasets.map(
|
422 |
+
tokenize_function,
|
423 |
+
batched=True,
|
424 |
+
num_proc=data_args.preprocessing_num_workers,
|
425 |
+
remove_columns=column_names,
|
426 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
427 |
+
)
|
428 |
+
|
429 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of
|
430 |
+
# max_seq_length.
|
431 |
+
def group_texts(examples):
|
432 |
+
# Concatenate all texts.
|
433 |
+
concatenated_examples = {k: sum(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 >= max_seq_length:
|
438 |
+
total_length = (total_length // max_seq_length) * max_seq_length
|
439 |
+
# Split by chunks of max_len.
|
440 |
+
result = {
|
441 |
+
k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
|
442 |
+
for k, t in concatenated_examples.items()
|
443 |
+
}
|
444 |
+
return result
|
445 |
+
|
446 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
|
447 |
+
# remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
|
448 |
+
# might be slower to preprocess.
|
449 |
+
#
|
450 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
451 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
|
452 |
+
tokenized_datasets = tokenized_datasets.map(
|
453 |
+
group_texts,
|
454 |
+
batched=True,
|
455 |
+
num_proc=data_args.preprocessing_num_workers,
|
456 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
457 |
+
)
|
458 |
+
|
459 |
+
# Enable tensorboard only on the master node
|
460 |
+
has_tensorboard = is_tensorboard_available()
|
461 |
+
if has_tensorboard and jax.process_index() == 0:
|
462 |
+
try:
|
463 |
+
from flax.metrics.tensorboard import SummaryWriter
|
464 |
+
|
465 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
466 |
+
except ImportError as ie:
|
467 |
+
has_tensorboard = False
|
468 |
+
logger.warning(
|
469 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
470 |
+
)
|
471 |
+
else:
|
472 |
+
logger.warning(
|
473 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
474 |
+
"Please run pip install tensorboard to enable."
|
475 |
+
)
|
476 |
+
|
477 |
+
# Data collator
|
478 |
+
# This one will take care of randomly masking the tokens.
|
479 |
+
data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
|
480 |
+
|
481 |
+
# Initialize our training
|
482 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
483 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
484 |
+
|
485 |
+
if model_args.model_name_or_path:
|
486 |
+
model = FlaxAutoModelForMaskedLM.from_pretrained(
|
487 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
488 |
+
)
|
489 |
+
else:
|
490 |
+
model = FlaxAutoModelForMaskedLM.from_config(
|
491 |
+
config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
492 |
+
)
|
493 |
+
|
494 |
+
# Store some constant
|
495 |
+
num_epochs = int(training_args.num_train_epochs)
|
496 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
497 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
498 |
+
|
499 |
+
num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
|
500 |
+
|
501 |
+
# Create learning rate schedule
|
502 |
+
warmup_fn = optax.linear_schedule(
|
503 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
504 |
+
)
|
505 |
+
decay_fn = optax.linear_schedule(
|
506 |
+
init_value=training_args.learning_rate,
|
507 |
+
end_value=0,
|
508 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
509 |
+
)
|
510 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
511 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
512 |
+
)
|
513 |
+
|
514 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
515 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
516 |
+
# mask boolean with the same structure as the parameters.
|
517 |
+
# The mask is True for parameters that should be decayed.
|
518 |
+
# Note that this mask is specifically adapted for FlaxBERT-like models.
|
519 |
+
# For other models, one should correct the layer norm parameter naming
|
520 |
+
# accordingly.
|
521 |
+
def decay_mask_fn(params):
|
522 |
+
flat_params = traverse_util.flatten_dict(params)
|
523 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
|
524 |
+
return traverse_util.unflatten_dict(flat_mask)
|
525 |
+
|
526 |
+
# create adam optimizer
|
527 |
+
if training_args.adafactor:
|
528 |
+
# We use the default parameters here to initialize adafactor,
|
529 |
+
# For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
|
530 |
+
optimizer = optax.adafactor(
|
531 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
532 |
+
)
|
533 |
+
else:
|
534 |
+
optimizer = optax.adamw(
|
535 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
536 |
+
b1=training_args.adam_beta1,
|
537 |
+
b2=training_args.adam_beta2,
|
538 |
+
eps=training_args.adam_epsilon,
|
539 |
+
weight_decay=training_args.weight_decay,
|
540 |
+
mask=decay_mask_fn,
|
541 |
+
)
|
542 |
+
|
543 |
+
# Setup train state
|
544 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
|
545 |
+
|
546 |
+
# Define gradient update step fn
|
547 |
+
def train_step(state, batch, dropout_rng):
|
548 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
549 |
+
|
550 |
+
def loss_fn(params):
|
551 |
+
labels = batch.pop("labels")
|
552 |
+
|
553 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
554 |
+
|
555 |
+
# compute loss, ignore padded input tokens
|
556 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
557 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
558 |
+
|
559 |
+
# take average
|
560 |
+
loss = loss.sum() / label_mask.sum()
|
561 |
+
|
562 |
+
return loss
|
563 |
+
|
564 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
565 |
+
loss, grad = grad_fn(state.params)
|
566 |
+
grad = jax.lax.pmean(grad, "batch")
|
567 |
+
new_state = state.apply_gradients(grads=grad)
|
568 |
+
|
569 |
+
metrics = jax.lax.pmean(
|
570 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
571 |
+
)
|
572 |
+
|
573 |
+
return new_state, metrics, new_dropout_rng
|
574 |
+
|
575 |
+
# Create parallel version of the train step
|
576 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
577 |
+
|
578 |
+
# Define eval fn
|
579 |
+
def eval_step(params, batch):
|
580 |
+
labels = batch.pop("labels")
|
581 |
+
|
582 |
+
logits = model(**batch, params=params, train=False)[0]
|
583 |
+
|
584 |
+
# compute loss, ignore padded input tokens
|
585 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
586 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
587 |
+
|
588 |
+
# compute accuracy
|
589 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
|
590 |
+
|
591 |
+
# summarize metrics
|
592 |
+
metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
|
593 |
+
metrics = jax.lax.psum(metrics, axis_name="batch")
|
594 |
+
|
595 |
+
return metrics
|
596 |
+
|
597 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
598 |
+
|
599 |
+
# Replicate the train state on each device
|
600 |
+
state = jax_utils.replicate(state)
|
601 |
+
|
602 |
+
train_time = 0
|
603 |
+
epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
|
604 |
+
for epoch in epochs:
|
605 |
+
# ======================== Training ================================
|
606 |
+
train_start = time.time()
|
607 |
+
train_metrics = []
|
608 |
+
|
609 |
+
# Create sampling rng
|
610 |
+
rng, input_rng = jax.random.split(rng)
|
611 |
+
|
612 |
+
# Generate an epoch by shuffling sampling indices from the train dataset
|
613 |
+
num_train_samples = len(tokenized_datasets["train"])
|
614 |
+
train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
|
615 |
+
train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
|
616 |
+
|
617 |
+
# Gather the indexes for creating the batch and do a training step
|
618 |
+
for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
|
619 |
+
samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
|
620 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
621 |
+
|
622 |
+
# Model forward
|
623 |
+
model_inputs = shard(model_inputs.data)
|
624 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
625 |
+
train_metrics.append(train_metric)
|
626 |
+
|
627 |
+
cur_step = epoch * (num_train_samples // train_batch_size) + step
|
628 |
+
|
629 |
+
if cur_step % training_args.logging_steps == 0 and cur_step > 0:
|
630 |
+
# Save metrics
|
631 |
+
train_metric = jax_utils.unreplicate(train_metric)
|
632 |
+
train_time += time.time() - train_start
|
633 |
+
if has_tensorboard and jax.process_index() == 0:
|
634 |
+
write_train_metric(summary_writer, train_metrics, train_time, cur_step)
|
635 |
+
|
636 |
+
epochs.write(
|
637 |
+
f"Step... ({cur_step} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
|
638 |
+
)
|
639 |
+
|
640 |
+
train_metrics = []
|
641 |
+
|
642 |
+
if cur_step % training_args.eval_steps == 0 and cur_step > 0:
|
643 |
+
# ======================== Evaluating ==============================
|
644 |
+
num_eval_samples = len(tokenized_datasets["validation"])
|
645 |
+
eval_samples_idx = jnp.arange(num_eval_samples)
|
646 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
647 |
+
|
648 |
+
eval_metrics = []
|
649 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
|
650 |
+
samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
|
651 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
652 |
+
|
653 |
+
# Model forward
|
654 |
+
model_inputs = shard(model_inputs.data)
|
655 |
+
metrics = p_eval_step(state.params, model_inputs)
|
656 |
+
eval_metrics.append(metrics)
|
657 |
+
|
658 |
+
# normalize eval metrics
|
659 |
+
eval_metrics = get_metrics(eval_metrics)
|
660 |
+
eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
|
661 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
662 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
663 |
+
|
664 |
+
# Update progress bar
|
665 |
+
epochs.desc = f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
|
666 |
+
|
667 |
+
# Save metrics
|
668 |
+
if has_tensorboard and jax.process_index() == 0:
|
669 |
+
write_eval_metric(summary_writer, eval_metrics, cur_step)
|
670 |
+
|
671 |
+
if cur_step % training_args.save_steps == 0 and cur_step > 0:
|
672 |
+
# save checkpoint after each epoch and push checkpoint to the hub
|
673 |
+
if jax.process_index() == 0:
|
674 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
675 |
+
model.save_pretrained(
|
676 |
+
training_args.output_dir,
|
677 |
+
params=params,
|
678 |
+
push_to_hub=training_args.push_to_hub,
|
679 |
+
commit_message=f"Saving weights and logs of step {cur_step}",
|
680 |
+
)
|
run_mlm_flax_stream.py
ADDED
@@ -0,0 +1,638 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2021 The HuggingFace Team All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""
|
17 |
+
Fine-tuning the library models for masked language modeling (BERT, ALBERT, RoBERTa...) with whole word masking on a
|
18 |
+
text file or a dataset.
|
19 |
+
|
20 |
+
Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
|
21 |
+
https://huggingface.co/models?filter=masked-lm
|
22 |
+
"""
|
23 |
+
import logging
|
24 |
+
import os
|
25 |
+
import sys
|
26 |
+
import time
|
27 |
+
from collections import defaultdict
|
28 |
+
from dataclasses import dataclass, field
|
29 |
+
|
30 |
+
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
|
31 |
+
from pathlib import Path
|
32 |
+
from typing import Dict, List, Optional, Tuple
|
33 |
+
|
34 |
+
import datasets
|
35 |
+
import numpy as np
|
36 |
+
from datasets import load_dataset
|
37 |
+
from tqdm import tqdm
|
38 |
+
|
39 |
+
import flax
|
40 |
+
import jax
|
41 |
+
import jax.numpy as jnp
|
42 |
+
import optax
|
43 |
+
from flax import jax_utils, traverse_util
|
44 |
+
from flax.training import train_state
|
45 |
+
from flax.training.common_utils import get_metrics, onehot, shard
|
46 |
+
from transformers import (
|
47 |
+
CONFIG_MAPPING,
|
48 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING,
|
49 |
+
AutoConfig,
|
50 |
+
AutoTokenizer,
|
51 |
+
FlaxAutoModelForMaskedLM,
|
52 |
+
HfArgumentParser,
|
53 |
+
PreTrainedTokenizerBase,
|
54 |
+
TensorType,
|
55 |
+
TrainingArguments,
|
56 |
+
is_tensorboard_available,
|
57 |
+
set_seed,
|
58 |
+
)
|
59 |
+
|
60 |
+
|
61 |
+
#if datasets.__version__ <= "1.8.0":
|
62 |
+
# raise ValueError("Make sure to upgrade `datasets` to a version >= 1.9.0 to use dataset streaming")
|
63 |
+
|
64 |
+
|
65 |
+
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
|
66 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
67 |
+
|
68 |
+
|
69 |
+
@dataclass
|
70 |
+
class ModelArguments:
|
71 |
+
"""
|
72 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
73 |
+
"""
|
74 |
+
|
75 |
+
model_name_or_path: Optional[str] = field(
|
76 |
+
default=None,
|
77 |
+
metadata={
|
78 |
+
"help": "The model checkpoint for weights initialization."
|
79 |
+
"Don't set if you want to train a model from scratch."
|
80 |
+
},
|
81 |
+
)
|
82 |
+
model_type: Optional[str] = field(
|
83 |
+
default=None,
|
84 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
85 |
+
)
|
86 |
+
config_name: Optional[str] = field(
|
87 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
88 |
+
)
|
89 |
+
tokenizer_name: Optional[str] = field(
|
90 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
91 |
+
)
|
92 |
+
cache_dir: Optional[str] = field(
|
93 |
+
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
94 |
+
)
|
95 |
+
use_fast_tokenizer: bool = field(
|
96 |
+
default=True,
|
97 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
98 |
+
)
|
99 |
+
dtype: Optional[str] = field(
|
100 |
+
default="float32",
|
101 |
+
metadata={
|
102 |
+
"help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
|
103 |
+
},
|
104 |
+
)
|
105 |
+
|
106 |
+
|
107 |
+
@dataclass
|
108 |
+
class DataTrainingArguments:
|
109 |
+
"""
|
110 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
111 |
+
"""
|
112 |
+
|
113 |
+
dataset_name: Optional[str] = field(
|
114 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
115 |
+
)
|
116 |
+
dataset_config_name: Optional[str] = field(
|
117 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
118 |
+
)
|
119 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
120 |
+
validation_file: Optional[str] = field(
|
121 |
+
default=None,
|
122 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
123 |
+
)
|
124 |
+
train_ref_file: Optional[str] = field(
|
125 |
+
default=None,
|
126 |
+
metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
|
127 |
+
)
|
128 |
+
validation_ref_file: Optional[str] = field(
|
129 |
+
default=None,
|
130 |
+
metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
|
131 |
+
)
|
132 |
+
auth_token: bool = field(
|
133 |
+
default=False, metadata={"help": "Use authorisation token"}
|
134 |
+
)
|
135 |
+
overwrite_cache: bool = field(
|
136 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
137 |
+
)
|
138 |
+
validation_split_percentage: Optional[int] = field(
|
139 |
+
default=5,
|
140 |
+
metadata={
|
141 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
142 |
+
},
|
143 |
+
)
|
144 |
+
max_seq_length: Optional[int] = field(
|
145 |
+
default=None,
|
146 |
+
metadata={
|
147 |
+
"help": "The maximum total input sequence length after tokenization. Sequences longer "
|
148 |
+
"than this will be truncated. Default to the max input length of the model."
|
149 |
+
},
|
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 |
+
mlm_probability: float = field(
|
156 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
|
157 |
+
)
|
158 |
+
pad_to_max_length: bool = field(
|
159 |
+
default=False,
|
160 |
+
metadata={
|
161 |
+
"help": "Whether to pad all samples to `max_seq_length`. "
|
162 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
163 |
+
},
|
164 |
+
)
|
165 |
+
line_by_line: bool = field(
|
166 |
+
default=False,
|
167 |
+
metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
|
168 |
+
)
|
169 |
+
text_column_name: str = field(
|
170 |
+
default="text", metadata={"help": "The name of the column to retrieve the training text."}
|
171 |
+
)
|
172 |
+
shuffle_buffer_size: int = field(
|
173 |
+
default=10000, metadata={"help": "The number of examples to pre-load for shuffling."}
|
174 |
+
)
|
175 |
+
num_train_steps: int = field(default=50000, metadata={"help": "The number of training steps."})
|
176 |
+
num_eval_samples: int = field(default=50000, metadata={"help": "The number of samples to be used for evaluation"})
|
177 |
+
|
178 |
+
def __post_init__(self):
|
179 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
180 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
181 |
+
else:
|
182 |
+
if self.train_file is not None:
|
183 |
+
extension = self.train_file.split(".")[-1]
|
184 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
|
185 |
+
if self.validation_file is not None:
|
186 |
+
extension = self.validation_file.split(".")[-1]
|
187 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
|
188 |
+
|
189 |
+
|
190 |
+
@flax.struct.dataclass
|
191 |
+
class FlaxDataCollatorForLanguageModeling:
|
192 |
+
"""
|
193 |
+
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
|
194 |
+
are not all of the same length.
|
195 |
+
|
196 |
+
Args:
|
197 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
198 |
+
The tokenizer used for encoding the data.
|
199 |
+
mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
|
200 |
+
The probability with which to (randomly) mask tokens in the input.
|
201 |
+
|
202 |
+
.. note::
|
203 |
+
|
204 |
+
For best performance, this data collator should be used with a dataset having items that are dictionaries or
|
205 |
+
BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
|
206 |
+
:class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
|
207 |
+
argument :obj:`return_special_tokens_mask=True`.
|
208 |
+
"""
|
209 |
+
|
210 |
+
tokenizer: PreTrainedTokenizerBase
|
211 |
+
mlm_probability: float = 0.15
|
212 |
+
|
213 |
+
def __post_init__(self):
|
214 |
+
if self.tokenizer.mask_token is None:
|
215 |
+
raise ValueError(
|
216 |
+
"This tokenizer does not have a mask token which is necessary for masked language modeling. "
|
217 |
+
"You should pass `mlm=False` to train on causal language modeling instead."
|
218 |
+
)
|
219 |
+
|
220 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]]) -> Dict[str, np.ndarray]:
|
221 |
+
# Handle dict or lists with proper padding and conversion to tensor.
|
222 |
+
batch = self.tokenizer.pad(examples, return_tensors=TensorType.NUMPY)
|
223 |
+
|
224 |
+
# If special token mask has been preprocessed, pop it from the dict.
|
225 |
+
special_tokens_mask = batch.pop("special_tokens_mask", None)
|
226 |
+
|
227 |
+
batch["input_ids"], batch["labels"] = self.mask_tokens(
|
228 |
+
batch["input_ids"], special_tokens_mask=special_tokens_mask
|
229 |
+
)
|
230 |
+
return batch
|
231 |
+
|
232 |
+
def mask_tokens(
|
233 |
+
self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
|
234 |
+
) -> Tuple[jnp.ndarray, jnp.ndarray]:
|
235 |
+
"""
|
236 |
+
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
|
237 |
+
"""
|
238 |
+
labels = inputs.copy()
|
239 |
+
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
|
240 |
+
probability_matrix = np.full(labels.shape, self.mlm_probability)
|
241 |
+
special_tokens_mask = special_tokens_mask.astype("bool")
|
242 |
+
|
243 |
+
probability_matrix[special_tokens_mask] = 0.0
|
244 |
+
masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
|
245 |
+
labels[~masked_indices] = -100 # We only compute loss on masked tokens
|
246 |
+
|
247 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
248 |
+
indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
|
249 |
+
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
|
250 |
+
|
251 |
+
# 10% of the time, we replace masked input tokens with random word
|
252 |
+
indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
|
253 |
+
indices_random &= masked_indices & ~indices_replaced
|
254 |
+
|
255 |
+
random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
|
256 |
+
inputs[indices_random] = random_words[indices_random]
|
257 |
+
|
258 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
259 |
+
return inputs, labels
|
260 |
+
|
261 |
+
|
262 |
+
def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
|
263 |
+
num_samples = len(samples_idx)
|
264 |
+
samples_to_remove = num_samples % batch_size
|
265 |
+
|
266 |
+
if samples_to_remove != 0:
|
267 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
268 |
+
sections_split = num_samples // batch_size
|
269 |
+
batch_idx = np.split(samples_idx, sections_split)
|
270 |
+
return batch_idx
|
271 |
+
|
272 |
+
|
273 |
+
def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
|
274 |
+
"""
|
275 |
+
The training iterator is advanced so that after groupifying the samples,
|
276 |
+
`num_samples` of length `max_seq_length` are returned.
|
277 |
+
"""
|
278 |
+
num_total_tokens = max_seq_length * num_samples
|
279 |
+
samples = defaultdict(list)
|
280 |
+
|
281 |
+
i = 0
|
282 |
+
while i < num_total_tokens:
|
283 |
+
tokenized_samples = next(train_iterator)
|
284 |
+
i += len(tokenized_samples["input_ids"])
|
285 |
+
|
286 |
+
# concatenate tokenized samples to list
|
287 |
+
samples = {k: samples[k] + tokenized_samples[k] for k in tokenized_samples.keys()}
|
288 |
+
|
289 |
+
# Concatenated tokens are split to lists of length `max_seq_length`.
|
290 |
+
# Note that remainedr of % max_seq_length are thrown away.
|
291 |
+
def group_texts(examples):
|
292 |
+
result = {
|
293 |
+
k: [t[i : i + max_seq_length] for i in range(0, num_total_tokens, max_seq_length)]
|
294 |
+
for k, t in examples.items()
|
295 |
+
}
|
296 |
+
return result
|
297 |
+
|
298 |
+
grouped_samples = group_texts(samples)
|
299 |
+
return grouped_samples
|
300 |
+
|
301 |
+
|
302 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
303 |
+
summary_writer.scalar("train_time", train_time, step)
|
304 |
+
|
305 |
+
train_metrics = get_metrics(train_metrics)
|
306 |
+
for key, vals in train_metrics.items():
|
307 |
+
tag = f"train_{key}"
|
308 |
+
for i, val in enumerate(vals):
|
309 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
310 |
+
|
311 |
+
|
312 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
313 |
+
for metric_name, value in eval_metrics.items():
|
314 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
315 |
+
|
316 |
+
|
317 |
+
if __name__ == "__main__":
|
318 |
+
# See all possible arguments in src/transformers/training_args.py
|
319 |
+
# or by passing the --help flag to this script.
|
320 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
321 |
+
|
322 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
323 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
324 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
325 |
+
# let's parse it to get our arguments.
|
326 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
327 |
+
else:
|
328 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
329 |
+
|
330 |
+
if (
|
331 |
+
os.path.exists(training_args.output_dir)
|
332 |
+
and os.listdir(training_args.output_dir)
|
333 |
+
and training_args.do_train
|
334 |
+
and not training_args.overwrite_output_dir
|
335 |
+
):
|
336 |
+
raise ValueError(
|
337 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
338 |
+
"Use --overwrite_output_dir to overcome."
|
339 |
+
)
|
340 |
+
|
341 |
+
# Setup logging
|
342 |
+
logging.basicConfig(
|
343 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
344 |
+
level="INFO",
|
345 |
+
datefmt="[%X]",
|
346 |
+
)
|
347 |
+
|
348 |
+
# Log on each process the small summary:
|
349 |
+
logger = logging.getLogger(__name__)
|
350 |
+
#logger.warning(
|
351 |
+
# f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
352 |
+
# + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
353 |
+
#)
|
354 |
+
|
355 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
356 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
357 |
+
|
358 |
+
# Set seed before initializing model.
|
359 |
+
set_seed(training_args.seed)
|
360 |
+
|
361 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
362 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
363 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
364 |
+
#
|
365 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
366 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
367 |
+
|
368 |
+
if data_args.dataset_name is not None:
|
369 |
+
# Downloading and loading a dataset from the hub.
|
370 |
+
dataset = load_dataset(
|
371 |
+
data_args.dataset_name,
|
372 |
+
data_args.dataset_config_name,
|
373 |
+
cache_dir=model_args.cache_dir,
|
374 |
+
streaming=True,
|
375 |
+
use_auth_token=data_args.auth_token,
|
376 |
+
split="train",
|
377 |
+
)
|
378 |
+
|
379 |
+
if model_args.config_name:
|
380 |
+
config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
|
381 |
+
elif model_args.model_name_or_path:
|
382 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
|
383 |
+
else:
|
384 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
385 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
386 |
+
|
387 |
+
if model_args.tokenizer_name:
|
388 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
389 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
390 |
+
)
|
391 |
+
elif model_args.model_name_or_path:
|
392 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
393 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
394 |
+
)
|
395 |
+
else:
|
396 |
+
raise ValueError(
|
397 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
398 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
399 |
+
)
|
400 |
+
|
401 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
402 |
+
# We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
|
403 |
+
# efficient when it receives the `special_tokens_mask`.
|
404 |
+
def tokenize_function(examples):
|
405 |
+
return tokenizer(examples[data_args.text_column_name], return_special_tokens_mask=True)
|
406 |
+
|
407 |
+
tokenized_datasets = dataset.map(
|
408 |
+
tokenize_function,
|
409 |
+
batched=True,
|
410 |
+
)
|
411 |
+
|
412 |
+
shuffle_seed = training_args.seed
|
413 |
+
tokenized_datasets = tokenized_datasets.shuffle(buffer_size=data_args.shuffle_buffer_size, seed=shuffle_seed)
|
414 |
+
|
415 |
+
has_tensorboard = is_tensorboard_available()
|
416 |
+
if has_tensorboard and jax.process_index() == 0:
|
417 |
+
try:
|
418 |
+
from flax.metrics.tensorboard import SummaryWriter
|
419 |
+
except ImportError as ie:
|
420 |
+
has_tensorboard = False
|
421 |
+
logger.warning(
|
422 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
423 |
+
)
|
424 |
+
|
425 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
426 |
+
|
427 |
+
# Data collator
|
428 |
+
# This one will take care of randomly masking the tokens.
|
429 |
+
data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
|
430 |
+
|
431 |
+
# Initialize our training
|
432 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
433 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
434 |
+
|
435 |
+
if model_args.model_name_or_path:
|
436 |
+
model = FlaxAutoModelForMaskedLM.from_pretrained(
|
437 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
438 |
+
)
|
439 |
+
else:
|
440 |
+
model = FlaxAutoModelForMaskedLM.from_config(
|
441 |
+
config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
442 |
+
)
|
443 |
+
|
444 |
+
# Store some constant
|
445 |
+
num_epochs = int(training_args.num_train_epochs)
|
446 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
447 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
448 |
+
|
449 |
+
# define number steps per stream epoch
|
450 |
+
num_train_steps = data_args.num_train_steps
|
451 |
+
|
452 |
+
# Create learning rate schedule
|
453 |
+
warmup_fn = optax.linear_schedule(
|
454 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
455 |
+
)
|
456 |
+
decay_fn = optax.linear_schedule(
|
457 |
+
init_value=training_args.learning_rate,
|
458 |
+
end_value=0,
|
459 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
460 |
+
)
|
461 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
462 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
463 |
+
)
|
464 |
+
|
465 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
466 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
467 |
+
# mask boolean with the same structure as the parameters.
|
468 |
+
# The mask is True for parameters that should be decayed.
|
469 |
+
# Note that this mask is specifically adapted for FlaxBERT-like models.
|
470 |
+
# For other models, one should correct the layer norm parameter naming
|
471 |
+
# accordingly.
|
472 |
+
def decay_mask_fn(params):
|
473 |
+
flat_params = traverse_util.flatten_dict(params)
|
474 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
|
475 |
+
return traverse_util.unflatten_dict(flat_mask)
|
476 |
+
|
477 |
+
|
478 |
+
|
479 |
+
#te adam optimizer
|
480 |
+
if training_args.adafactor:
|
481 |
+
# We use the default parameters here to initialize adafactor,
|
482 |
+
# For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
|
483 |
+
optimizer = optax.adafactor(
|
484 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
485 |
+
)
|
486 |
+
else:
|
487 |
+
optimizer = optax.adamw(
|
488 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
489 |
+
b1=training_args.adam_beta1,
|
490 |
+
b2=training_args.adam_beta2,
|
491 |
+
eps=training_args.adam_epsilon,
|
492 |
+
weight_decay=training_args.weight_decay,
|
493 |
+
mask=decay_mask_fn,
|
494 |
+
)
|
495 |
+
|
496 |
+
# Setup train state
|
497 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
|
498 |
+
|
499 |
+
# Define gradient update step fn
|
500 |
+
def train_step(state, batch, dropout_rng):
|
501 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
502 |
+
|
503 |
+
def loss_fn(params):
|
504 |
+
labels = batch.pop("labels")
|
505 |
+
|
506 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
507 |
+
|
508 |
+
# compute loss, ignore padded input tokens
|
509 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
510 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
511 |
+
|
512 |
+
# take average
|
513 |
+
loss = loss.sum() / label_mask.sum()
|
514 |
+
|
515 |
+
return loss
|
516 |
+
|
517 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
518 |
+
loss, grad = grad_fn(state.params)
|
519 |
+
grad = jax.lax.pmean(grad, "batch")
|
520 |
+
new_state = state.apply_gradients(grads=grad)
|
521 |
+
|
522 |
+
metrics = jax.lax.pmean(
|
523 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
524 |
+
)
|
525 |
+
|
526 |
+
return new_state, metrics, new_dropout_rng
|
527 |
+
|
528 |
+
# Create parallel version of the train step
|
529 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
530 |
+
|
531 |
+
# Define eval fn
|
532 |
+
def eval_step(params, batch):
|
533 |
+
labels = batch.pop("labels")
|
534 |
+
|
535 |
+
logits = model(**batch, params=params, train=False)[0]
|
536 |
+
|
537 |
+
# compute loss, ignore padded input tokens
|
538 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
539 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
540 |
+
|
541 |
+
# compute accuracy
|
542 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
|
543 |
+
|
544 |
+
# summarize metrics
|
545 |
+
metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
|
546 |
+
metrics = jax.lax.psum(metrics, axis_name="batch")
|
547 |
+
|
548 |
+
return metrics
|
549 |
+
|
550 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
551 |
+
|
552 |
+
# Replicate the train state on each device
|
553 |
+
state = jax_utils.replicate(state)
|
554 |
+
|
555 |
+
train_time = 0
|
556 |
+
train_start = time.time()
|
557 |
+
train_metrics = []
|
558 |
+
eval_metrics = []
|
559 |
+
|
560 |
+
training_iter = iter(tokenized_datasets)
|
561 |
+
|
562 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
563 |
+
eval_samples = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, max_seq_length)
|
564 |
+
|
565 |
+
steps = tqdm(range(num_train_steps), desc="Training...", position=0)
|
566 |
+
for step in range(num_train_steps):
|
567 |
+
# ======================== Training ================================
|
568 |
+
try:
|
569 |
+
samples = advance_iter_and_group_samples(training_iter, train_batch_size, max_seq_length)
|
570 |
+
except StopIteration:
|
571 |
+
# Once the end of the dataset stream is reached, the training iterator
|
572 |
+
# is reinitialized and reshuffled and a new eval dataset is randomely chosen.
|
573 |
+
shuffle_seed += 1
|
574 |
+
tokenized_datasets.set_epoch(shuffle_seed)
|
575 |
+
|
576 |
+
training_iter = iter(tokenized_datasets)
|
577 |
+
|
578 |
+
eval_dataset = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, max_seq_length)
|
579 |
+
samples = advance_iter_and_group_samples(training_iter, train_batch_size, max_seq_length)
|
580 |
+
|
581 |
+
# process input samples
|
582 |
+
model_inputs = data_collator(samples)
|
583 |
+
|
584 |
+
# Model forward
|
585 |
+
model_inputs = shard(model_inputs.data)
|
586 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
587 |
+
|
588 |
+
train_metrics.append(train_metric)
|
589 |
+
|
590 |
+
if step % training_args.logging_steps == 0 and step > 0:
|
591 |
+
steps.write(
|
592 |
+
f"Step... ({step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
|
593 |
+
)
|
594 |
+
train_time += time.time() - train_start
|
595 |
+
if has_tensorboard and jax.process_index() == 0:
|
596 |
+
write_train_metric(summary_writer, train_metrics, train_time, step)
|
597 |
+
train_metrics = []
|
598 |
+
|
599 |
+
# ======================== Evaluating ==============================
|
600 |
+
if step % training_args.eval_steps == 0 and step > 0:
|
601 |
+
eval_samples_idx = jnp.arange(data_args.num_eval_samples)
|
602 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
603 |
+
|
604 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=1)):
|
605 |
+
# process input samples
|
606 |
+
batch_eval_samples = {k: [v[idx] for idx in batch_idx] for k, v in eval_samples.items()}
|
607 |
+
model_inputs = data_collator(batch_eval_samples)
|
608 |
+
|
609 |
+
# Model forward
|
610 |
+
model_inputs = shard(model_inputs.data)
|
611 |
+
metrics = p_eval_step(state.params, model_inputs)
|
612 |
+
eval_metrics.append(metrics)
|
613 |
+
|
614 |
+
# normalize eval metrics
|
615 |
+
eval_metrics = get_metrics(eval_metrics)
|
616 |
+
eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
|
617 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
618 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
619 |
+
|
620 |
+
# Update progress bar
|
621 |
+
steps.desc = f"Step... ({step + 1}/{num_train_steps} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
|
622 |
+
|
623 |
+
if has_tensorboard and jax.process_index() == 0:
|
624 |
+
write_eval_metric(summary_writer, eval_metrics, step)
|
625 |
+
eval_metrics = []
|
626 |
+
|
627 |
+
# save checkpoint after each epoch and push checkpoint to the hub
|
628 |
+
if jax.process_index() == 0:
|
629 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
630 |
+
model.save_pretrained(
|
631 |
+
training_args.output_dir,
|
632 |
+
params=params,
|
633 |
+
push_to_hub=training_args.push_to_hub,
|
634 |
+
commit_message=f"Saving weights and logs of step {step+1}",
|
635 |
+
)
|
636 |
+
|
637 |
+
# update tqdm bar
|
638 |
+
steps.update(1)
|
run_stream_128.sh
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
./run_mlm_flax_stream.py \
|
2 |
+
--output_dir="./" \
|
3 |
+
--model_type="roberta" \
|
4 |
+
--config_name="./" \
|
5 |
+
--tokenizer_name="./" \
|
6 |
+
--model_name_or_path="./" \
|
7 |
+
--dataset_name="NbAiLab/scandinavian" \
|
8 |
+
--max_seq_length="128" \
|
9 |
+
--weight_decay="0.01" \
|
10 |
+
--per_device_train_batch_size="128" \
|
11 |
+
--per_device_eval_batch_size="128" \
|
12 |
+
--learning_rate="6e-5" \
|
13 |
+
--warmup_steps="5000" \
|
14 |
+
--overwrite_output_dir \
|
15 |
+
--cache_dir /mnt/disks/flaxdisk/cache/ \
|
16 |
+
--num_train_steps="720000" \
|
17 |
+
--adam_beta1="0.9" \
|
18 |
+
--adam_beta2="0.98" \
|
19 |
+
--logging_steps="10000" \
|
20 |
+
--save_steps="10000" \
|
21 |
+
--eval_steps="10000" \
|
22 |
+
--preprocessing_num_workers 96 \
|
23 |
+
--auth_token True \
|
24 |
+
--adafactor \
|
25 |
+
--push_to_hub
|
run_stream_512.sh
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
./run_mlm_flax_stream.py \
|
2 |
+
--output_dir="./" \
|
3 |
+
--model_type="roberta" \
|
4 |
+
--config_name="./" \
|
5 |
+
--tokenizer_name="./" \
|
6 |
+
--model_name_or_path="./" \
|
7 |
+
--dataset_name="NbAiLab/scandinavian" \
|
8 |
+
--max_seq_length="512" \
|
9 |
+
--weight_decay="0.01" \
|
10 |
+
--per_device_train_batch_size="48" \
|
11 |
+
--per_device_eval_batch_size="48" \
|
12 |
+
--learning_rate="3e-5" \
|
13 |
+
--warmup_steps="2000" \
|
14 |
+
--overwrite_output_dir \
|
15 |
+
--cache_dir /mnt/disks/flaxdisk/cache/ \
|
16 |
+
--num_train_steps="70000" \
|
17 |
+
--adam_beta1="0.9" \
|
18 |
+
--adam_beta2="0.98" \
|
19 |
+
--logging_steps="20000" \
|
20 |
+
--save_steps="10000" \
|
21 |
+
--eval_steps="10000" \
|
22 |
+
--preprocessing_num_workers 96 \
|
23 |
+
--auth_token True \
|
24 |
+
--adafactor \
|
25 |
+
--push_to_hub
|
special_tokens_map.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": false}}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>", "add_prefix_space": false, "errors": "replace", "sep_token": "</s>", "cls_token": "<s>", "pad_token": "<pad>", "mask_token": "<mask>", "special_tokens_map_file": null, "name_or_path": ".", "tokenizer_class": "RobertaTokenizer"}
|
train_tokenizer.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datasets import load_dataset, concatenate_datasets
|
2 |
+
from tokenizers import trainers, Tokenizer, normalizers, ByteLevelBPETokenizer
|
3 |
+
|
4 |
+
model_dir = "./" # ${MODEL_DIR}
|
5 |
+
|
6 |
+
# load dataset
|
7 |
+
dataset = load_dataset("json", data_files=["/mnt/disks/flaxdisk/corpus/norwegian_colossal_corpus_validation.json","/mnt/disks/flaxdisk/corpus/special_chars.json"], split='train')
|
8 |
+
|
9 |
+
|
10 |
+
# Instantiate tokenizer
|
11 |
+
tokenizer = ByteLevelBPETokenizer()
|
12 |
+
|
13 |
+
def batch_iterator(batch_size=1000):
|
14 |
+
for i in range(0, len(dataset), batch_size):
|
15 |
+
yield dataset[i: i + batch_size]["text"]
|
16 |
+
|
17 |
+
# Customized training
|
18 |
+
tokenizer.train_from_iterator(batch_iterator(), vocab_size=50265, min_frequency=2, special_tokens=[
|
19 |
+
"<s>",
|
20 |
+
"<pad>",
|
21 |
+
"</s>",
|
22 |
+
"<unk>",
|
23 |
+
"<mask>",
|
24 |
+
])
|
25 |
+
|
26 |
+
|
27 |
+
# Save files to disk
|
28 |
+
tokenizer.save(f"{model_dir}/tokenizer.json")
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|