Saving weights and logs of step 10000
Browse files- README.md +1 -0
- config.json +28 -0
- create_config.py +6 -0
- events.out.tfevents.1640261667.t1v-n-358ff5d1-w-0.1667932.3.v2 +3 -0
- events.out.tfevents.1640263998.t1v-n-358ff5d1-w-0.1676696.3.v2 +3 -0
- events.out.tfevents.1640264276.t1v-n-358ff5d1-w-0.1678479.3.v2 +3 -0
- events.out.tfevents.1640779990.t1v-n-358ff5d1-w-0.2119930.3.v2 +3 -0
- events.out.tfevents.1640956682.t1v-n-358ff5d1-w-0.11974.3.v2 +3 -0
- events.out.tfevents.1641299828.t1v-n-358ff5d1-w-0.355877.3.v2 +3 -0
- events.out.tfevents.1641311061.t1v-n-358ff5d1-w-0.367642.3.v2 +3 -0
- flax_model.msgpack +3 -0
- flax_model_backup_final.msgpack +3 -0
- generate_pytorch_model.py +5 -0
- merges.txt +0 -0
- pytorch_model.bin +3 -0
- run_mlm_flax.py +691 -0
- run_step1.sh +26 -0
- run_step2.sh +26 -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 @@
|
|
|
|
|
1 |
+
Just for performing some experiments. Do not use.
|
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": "bfloat16",
|
24 |
+
"transformers_version": "4.15.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.1640261667.t1v-n-358ff5d1-w-0.1667932.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c6a8477d21766f937975208be48441ba54cdff6eb0cc792e7d1c0bca7734ffe4
|
3 |
+
size 40
|
events.out.tfevents.1640263998.t1v-n-358ff5d1-w-0.1676696.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d99dcbe152245c74123b25a17b0ecdba0a2d3c1e67121479130e1db38a20f5a8
|
3 |
+
size 40
|
events.out.tfevents.1640264276.t1v-n-358ff5d1-w-0.1678479.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:aebdb37cfb768737ea6ccc7cdc32a0403ccbbc0e155821325afdfb2821163f78
|
3 |
+
size 7418218
|
events.out.tfevents.1640779990.t1v-n-358ff5d1-w-0.2119930.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5bb5bcd8ee2fb1b04f69ce197874a6f296e9a5d2de7ffe87bddc4b523bd5f35e
|
3 |
+
size 41912932
|
events.out.tfevents.1640956682.t1v-n-358ff5d1-w-0.11974.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:64ab393a0478af5f4ff04d8e25833a4e0c94add58ef90fb29842fdc0e147e5f8
|
3 |
+
size 60256092
|
events.out.tfevents.1641299828.t1v-n-358ff5d1-w-0.355877.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c479c58a311b3c3bef4df1082214c3f83ba33424f1553351cf618d2d7d2c4ad1
|
3 |
+
size 40
|
events.out.tfevents.1641311061.t1v-n-358ff5d1-w-0.367642.3.v2
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:21a15f51d6a3318a60f721a0dc5cac6d706ce9707d4a1c175a30ef8af0b7192a
|
3 |
+
size 1470136
|
flax_model.msgpack
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0aeca2d7590874929548e47b9e3bb48e09ae5cfa42d6471deaeba007ecde1052
|
3 |
+
size 498796983
|
flax_model_backup_final.msgpack
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5255008970a84f6e4d55177ca133107efb4c186c01834c6dac31da4bc0e34e91
|
3 |
+
size 498796983
|
generate_pytorch_model.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
3 |
+
model = RobertaForMaskedLM.from_pretrained(".",from_flax=True)
|
4 |
+
model.save_pretrained(".")
|
5 |
+
|
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:48f88c91ae784c3e4820cd1fbecd154c0f6ac8eab3062d26da6a831ed3c621a7
|
3 |
+
size 498872555
|
run_mlm_flax.py
ADDED
@@ -0,0 +1,691 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
static_learning_rate: bool = field(
|
130 |
+
default=False, metadata={"help": "Use a non decaying learning rate"}
|
131 |
+
)
|
132 |
+
auth_token: bool = field(
|
133 |
+
default=False, metadata={"help": "Use authorisation token"}
|
134 |
+
)
|
135 |
+
validation_split_percentage: Optional[int] = field(
|
136 |
+
default=5,
|
137 |
+
metadata={
|
138 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
139 |
+
},
|
140 |
+
)
|
141 |
+
max_seq_length: Optional[int] = field(
|
142 |
+
default=None,
|
143 |
+
metadata={
|
144 |
+
"help": "The maximum total input sequence length after tokenization. Sequences longer "
|
145 |
+
"than this will be truncated. Default to the max input length of the model."
|
146 |
+
},
|
147 |
+
)
|
148 |
+
preprocessing_num_workers: Optional[int] = field(
|
149 |
+
default=None,
|
150 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
151 |
+
)
|
152 |
+
mlm_probability: float = field(
|
153 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
|
154 |
+
)
|
155 |
+
pad_to_max_length: bool = field(
|
156 |
+
default=False,
|
157 |
+
metadata={
|
158 |
+
"help": "Whether to pad all samples to `max_seq_length`. "
|
159 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
160 |
+
},
|
161 |
+
)
|
162 |
+
line_by_line: bool = field(
|
163 |
+
default=False,
|
164 |
+
metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
|
165 |
+
)
|
166 |
+
|
167 |
+
def __post_init__(self):
|
168 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
169 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
170 |
+
else:
|
171 |
+
if self.train_file is not None:
|
172 |
+
extension = self.train_file.split(".")[-1]
|
173 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
|
174 |
+
if self.validation_file is not None:
|
175 |
+
extension = self.validation_file.split(".")[-1]
|
176 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
|
177 |
+
|
178 |
+
|
179 |
+
@flax.struct.dataclass
|
180 |
+
class FlaxDataCollatorForLanguageModeling:
|
181 |
+
"""
|
182 |
+
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
|
183 |
+
are not all of the same length.
|
184 |
+
|
185 |
+
Args:
|
186 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
187 |
+
The tokenizer used for encoding the data.
|
188 |
+
mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
|
189 |
+
The probability with which to (randomly) mask tokens in the input.
|
190 |
+
|
191 |
+
.. note::
|
192 |
+
|
193 |
+
For best performance, this data collator should be used with a dataset having items that are dictionaries or
|
194 |
+
BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
|
195 |
+
:class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
|
196 |
+
argument :obj:`return_special_tokens_mask=True`.
|
197 |
+
"""
|
198 |
+
|
199 |
+
tokenizer: PreTrainedTokenizerBase
|
200 |
+
mlm_probability: float = 0.15
|
201 |
+
|
202 |
+
def __post_init__(self):
|
203 |
+
if self.tokenizer.mask_token is None:
|
204 |
+
raise ValueError(
|
205 |
+
"This tokenizer does not have a mask token which is necessary for masked language modeling. "
|
206 |
+
"You should pass `mlm=False` to train on causal language modeling instead."
|
207 |
+
)
|
208 |
+
|
209 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
|
210 |
+
# Handle dict or lists with proper padding and conversion to tensor.
|
211 |
+
batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
|
212 |
+
|
213 |
+
# If special token mask has been preprocessed, pop it from the dict.
|
214 |
+
special_tokens_mask = batch.pop("special_tokens_mask", None)
|
215 |
+
|
216 |
+
batch["input_ids"], batch["labels"] = self.mask_tokens(
|
217 |
+
batch["input_ids"], special_tokens_mask=special_tokens_mask
|
218 |
+
)
|
219 |
+
return batch
|
220 |
+
|
221 |
+
def mask_tokens(
|
222 |
+
self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
|
223 |
+
) -> Tuple[jnp.ndarray, jnp.ndarray]:
|
224 |
+
"""
|
225 |
+
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
|
226 |
+
"""
|
227 |
+
labels = inputs.copy()
|
228 |
+
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
|
229 |
+
probability_matrix = np.full(labels.shape, self.mlm_probability)
|
230 |
+
special_tokens_mask = special_tokens_mask.astype("bool")
|
231 |
+
|
232 |
+
probability_matrix[special_tokens_mask] = 0.0
|
233 |
+
masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
|
234 |
+
labels[~masked_indices] = -100 # We only compute loss on masked tokens
|
235 |
+
|
236 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
237 |
+
indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
|
238 |
+
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
|
239 |
+
|
240 |
+
# 10% of the time, we replace masked input tokens with random word
|
241 |
+
indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
|
242 |
+
indices_random &= masked_indices & ~indices_replaced
|
243 |
+
|
244 |
+
random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
|
245 |
+
inputs[indices_random] = random_words[indices_random]
|
246 |
+
|
247 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
248 |
+
return inputs, labels
|
249 |
+
|
250 |
+
|
251 |
+
def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
|
252 |
+
num_samples = len(samples_idx)
|
253 |
+
samples_to_remove = num_samples % batch_size
|
254 |
+
|
255 |
+
if samples_to_remove != 0:
|
256 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
257 |
+
sections_split = num_samples // batch_size
|
258 |
+
batch_idx = np.split(samples_idx, sections_split)
|
259 |
+
return batch_idx
|
260 |
+
|
261 |
+
|
262 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
263 |
+
summary_writer.scalar("train_time", train_time, step)
|
264 |
+
|
265 |
+
train_metrics = get_metrics(train_metrics)
|
266 |
+
for key, vals in train_metrics.items():
|
267 |
+
tag = f"train_{key}"
|
268 |
+
for i, val in enumerate(vals):
|
269 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
270 |
+
|
271 |
+
|
272 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
273 |
+
for metric_name, value in eval_metrics.items():
|
274 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
275 |
+
|
276 |
+
|
277 |
+
if __name__ == "__main__":
|
278 |
+
# See all possible arguments in src/transformers/training_args.py
|
279 |
+
# or by passing the --help flag to this script.
|
280 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
281 |
+
|
282 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
283 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
284 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
285 |
+
# let's parse it to get our arguments.
|
286 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
287 |
+
else:
|
288 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
289 |
+
|
290 |
+
if (
|
291 |
+
os.path.exists(training_args.output_dir)
|
292 |
+
and os.listdir(training_args.output_dir)
|
293 |
+
and training_args.do_train
|
294 |
+
and not training_args.overwrite_output_dir
|
295 |
+
):
|
296 |
+
raise ValueError(
|
297 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
298 |
+
"Use --overwrite_output_dir to overcome."
|
299 |
+
)
|
300 |
+
|
301 |
+
# Setup logging
|
302 |
+
logging.basicConfig(
|
303 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
304 |
+
level="NOTSET",
|
305 |
+
datefmt="[%X]",
|
306 |
+
)
|
307 |
+
|
308 |
+
# Log on each process the small summary:
|
309 |
+
logger = logging.getLogger(__name__)
|
310 |
+
|
311 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
312 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
313 |
+
|
314 |
+
# Set seed before initializing model.
|
315 |
+
set_seed(training_args.seed)
|
316 |
+
|
317 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
318 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
319 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
320 |
+
#
|
321 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
322 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
323 |
+
#
|
324 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
325 |
+
# download the dataset.
|
326 |
+
if data_args.dataset_name is not None:
|
327 |
+
# Downloading and loading a dataset from the hub.
|
328 |
+
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, use_auth_token=data_args.auth_token, cache_dir=model_args.cache_dir)
|
329 |
+
|
330 |
+
if "validation" not in datasets.keys():
|
331 |
+
datasets["validation"] = load_dataset(
|
332 |
+
data_args.dataset_name,
|
333 |
+
data_args.dataset_config_name,
|
334 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
335 |
+
cache_dir=model_args.cache_dir,
|
336 |
+
use_auth_token=data_args.auth_token,
|
337 |
+
)
|
338 |
+
datasets["train"] = load_dataset(
|
339 |
+
data_args.dataset_name,
|
340 |
+
data_args.dataset_config_name,
|
341 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
342 |
+
cache_dir=model_args.cache_dir,
|
343 |
+
use_auth_token=data_args.auth_token,
|
344 |
+
)
|
345 |
+
else:
|
346 |
+
data_files = {}
|
347 |
+
if data_args.train_file is not None:
|
348 |
+
data_files["train"] = data_args.train_file
|
349 |
+
if data_args.validation_file is not None:
|
350 |
+
data_files["validation"] = data_args.validation_file
|
351 |
+
extension = data_args.train_file.split(".")[-1]
|
352 |
+
if extension == "txt":
|
353 |
+
extension = "text"
|
354 |
+
datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
|
355 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
356 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
357 |
+
|
358 |
+
# Load pretrained model and tokenizer
|
359 |
+
|
360 |
+
# Distributed training:
|
361 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
362 |
+
# download model & vocab.
|
363 |
+
if model_args.config_name:
|
364 |
+
config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
|
365 |
+
elif model_args.model_name_or_path:
|
366 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
|
367 |
+
else:
|
368 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
369 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
370 |
+
|
371 |
+
if model_args.tokenizer_name:
|
372 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
373 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
374 |
+
)
|
375 |
+
elif model_args.model_name_or_path:
|
376 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
377 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
378 |
+
)
|
379 |
+
else:
|
380 |
+
raise ValueError(
|
381 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
382 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
383 |
+
)
|
384 |
+
|
385 |
+
# Preprocessing the datasets.
|
386 |
+
# First we tokenize all the texts.
|
387 |
+
if training_args.do_train:
|
388 |
+
column_names = datasets["train"].column_names
|
389 |
+
else:
|
390 |
+
column_names = datasets["validation"].column_names
|
391 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
392 |
+
|
393 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
394 |
+
|
395 |
+
if data_args.line_by_line:
|
396 |
+
# When using line_by_line, we just tokenize each nonempty line.
|
397 |
+
padding = "max_length" if data_args.pad_to_max_length else False
|
398 |
+
|
399 |
+
def tokenize_function(examples):
|
400 |
+
# Remove empty lines
|
401 |
+
examples = [line for line in examples if len(line) > 0 and not line.isspace()]
|
402 |
+
return tokenizer(
|
403 |
+
examples,
|
404 |
+
return_special_tokens_mask=True,
|
405 |
+
padding=padding,
|
406 |
+
truncation=True,
|
407 |
+
max_length=max_seq_length,
|
408 |
+
)
|
409 |
+
|
410 |
+
tokenized_datasets = datasets.map(
|
411 |
+
tokenize_function,
|
412 |
+
input_columns=[text_column_name],
|
413 |
+
batched=True,
|
414 |
+
num_proc=data_args.preprocessing_num_workers,
|
415 |
+
remove_columns=column_names,
|
416 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
417 |
+
)
|
418 |
+
|
419 |
+
else:
|
420 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
421 |
+
# We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
|
422 |
+
# efficient when it receives the `special_tokens_mask`.
|
423 |
+
def tokenize_function(examples):
|
424 |
+
return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
|
425 |
+
|
426 |
+
tokenized_datasets = datasets.map(
|
427 |
+
tokenize_function,
|
428 |
+
batched=True,
|
429 |
+
num_proc=data_args.preprocessing_num_workers,
|
430 |
+
remove_columns=column_names,
|
431 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
432 |
+
)
|
433 |
+
|
434 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of
|
435 |
+
# max_seq_length.
|
436 |
+
def group_texts(examples):
|
437 |
+
# Concatenate all texts.
|
438 |
+
concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
|
439 |
+
total_length = len(concatenated_examples[list(examples.keys())[0]])
|
440 |
+
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
|
441 |
+
# customize this part to your needs.
|
442 |
+
if total_length >= max_seq_length:
|
443 |
+
total_length = (total_length // max_seq_length) * max_seq_length
|
444 |
+
# Split by chunks of max_len.
|
445 |
+
result = {
|
446 |
+
k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
|
447 |
+
for k, t in concatenated_examples.items()
|
448 |
+
}
|
449 |
+
return result
|
450 |
+
|
451 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
|
452 |
+
# remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
|
453 |
+
# might be slower to preprocess.
|
454 |
+
#
|
455 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
456 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
|
457 |
+
tokenized_datasets = tokenized_datasets.map(
|
458 |
+
group_texts,
|
459 |
+
batched=True,
|
460 |
+
num_proc=data_args.preprocessing_num_workers,
|
461 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
462 |
+
)
|
463 |
+
|
464 |
+
# Enable tensorboard only on the master node
|
465 |
+
has_tensorboard = is_tensorboard_available()
|
466 |
+
if has_tensorboard and jax.process_index() == 0:
|
467 |
+
try:
|
468 |
+
from flax.metrics.tensorboard import SummaryWriter
|
469 |
+
|
470 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
471 |
+
except ImportError as ie:
|
472 |
+
has_tensorboard = False
|
473 |
+
logger.warning(
|
474 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
475 |
+
)
|
476 |
+
else:
|
477 |
+
logger.warning(
|
478 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
479 |
+
"Please run pip install tensorboard to enable."
|
480 |
+
)
|
481 |
+
|
482 |
+
# Data collator
|
483 |
+
# This one will take care of randomly masking the tokens.
|
484 |
+
data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
|
485 |
+
|
486 |
+
# Initialize our training
|
487 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
488 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
489 |
+
|
490 |
+
if model_args.model_name_or_path:
|
491 |
+
model = FlaxAutoModelForMaskedLM.from_pretrained(
|
492 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
493 |
+
)
|
494 |
+
else:
|
495 |
+
model = FlaxAutoModelForMaskedLM.from_config(
|
496 |
+
config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
497 |
+
)
|
498 |
+
|
499 |
+
# Store some constant
|
500 |
+
num_epochs = int(training_args.num_train_epochs)
|
501 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
502 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
503 |
+
|
504 |
+
num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
|
505 |
+
|
506 |
+
# Create learning rate schedule
|
507 |
+
warmup_fn = optax.linear_schedule(
|
508 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
509 |
+
)
|
510 |
+
|
511 |
+
if data_args.static_learning_rate:
|
512 |
+
end_lr_value = training_args.learning_rate
|
513 |
+
else:
|
514 |
+
end_lr_value = 0
|
515 |
+
|
516 |
+
decay_fn = optax.linear_schedule(
|
517 |
+
init_value=training_args.learning_rate,
|
518 |
+
end_value=end_lr_value,
|
519 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
520 |
+
)
|
521 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
522 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
523 |
+
)
|
524 |
+
|
525 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
526 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
527 |
+
# mask boolean with the same structure as the parameters.
|
528 |
+
# The mask is True for parameters that should be decayed.
|
529 |
+
# Note that this mask is specifically adapted for FlaxBERT-like models.
|
530 |
+
# For other models, one should correct the layer norm parameter naming
|
531 |
+
# accordingly.
|
532 |
+
def decay_mask_fn(params):
|
533 |
+
flat_params = traverse_util.flatten_dict(params)
|
534 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
|
535 |
+
return traverse_util.unflatten_dict(flat_mask)
|
536 |
+
|
537 |
+
# create adam optimizer
|
538 |
+
if training_args.adafactor:
|
539 |
+
# We use the default parameters here to initialize adafactor,
|
540 |
+
# For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
|
541 |
+
optimizer = optax.adafactor(
|
542 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
543 |
+
)
|
544 |
+
else:
|
545 |
+
optimizer = optax.adamw(
|
546 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
547 |
+
b1=training_args.adam_beta1,
|
548 |
+
b2=training_args.adam_beta2,
|
549 |
+
eps=training_args.adam_epsilon,
|
550 |
+
weight_decay=training_args.weight_decay,
|
551 |
+
mask=decay_mask_fn,
|
552 |
+
)
|
553 |
+
|
554 |
+
# Setup train state
|
555 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
|
556 |
+
|
557 |
+
# Define gradient update step fn
|
558 |
+
def train_step(state, batch, dropout_rng):
|
559 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
560 |
+
|
561 |
+
def loss_fn(params):
|
562 |
+
labels = batch.pop("labels")
|
563 |
+
|
564 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
565 |
+
|
566 |
+
# compute loss, ignore padded input tokens
|
567 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
568 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
569 |
+
|
570 |
+
# take average
|
571 |
+
loss = loss.sum() / label_mask.sum()
|
572 |
+
|
573 |
+
return loss
|
574 |
+
|
575 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
576 |
+
loss, grad = grad_fn(state.params)
|
577 |
+
grad = jax.lax.pmean(grad, "batch")
|
578 |
+
new_state = state.apply_gradients(grads=grad)
|
579 |
+
|
580 |
+
metrics = jax.lax.pmean(
|
581 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
582 |
+
)
|
583 |
+
|
584 |
+
return new_state, metrics, new_dropout_rng
|
585 |
+
|
586 |
+
# Create parallel version of the train step
|
587 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
588 |
+
|
589 |
+
# Define eval fn
|
590 |
+
def eval_step(params, batch):
|
591 |
+
labels = batch.pop("labels")
|
592 |
+
|
593 |
+
logits = model(**batch, params=params, train=False)[0]
|
594 |
+
|
595 |
+
# compute loss, ignore padded input tokens
|
596 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
597 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
598 |
+
|
599 |
+
# compute accuracy
|
600 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
|
601 |
+
|
602 |
+
# summarize metrics
|
603 |
+
metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
|
604 |
+
metrics = jax.lax.psum(metrics, axis_name="batch")
|
605 |
+
|
606 |
+
return metrics
|
607 |
+
|
608 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
609 |
+
|
610 |
+
# Replicate the train state on each device
|
611 |
+
state = jax_utils.replicate(state)
|
612 |
+
|
613 |
+
train_time = 0
|
614 |
+
epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
|
615 |
+
for epoch in epochs:
|
616 |
+
# ======================== Training ================================
|
617 |
+
train_start = time.time()
|
618 |
+
train_metrics = []
|
619 |
+
|
620 |
+
# Create sampling rng
|
621 |
+
rng, input_rng = jax.random.split(rng)
|
622 |
+
|
623 |
+
# Generate an epoch by shuffling sampling indices from the train dataset
|
624 |
+
num_train_samples = len(tokenized_datasets["train"])
|
625 |
+
train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
|
626 |
+
train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
|
627 |
+
|
628 |
+
# Gather the indexes for creating the batch and do a training step
|
629 |
+
for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
|
630 |
+
samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
|
631 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
632 |
+
|
633 |
+
# Model forward
|
634 |
+
model_inputs = shard(model_inputs.data)
|
635 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
636 |
+
train_metrics.append(train_metric)
|
637 |
+
|
638 |
+
cur_step = epoch * (num_train_samples // train_batch_size) + step
|
639 |
+
|
640 |
+
if cur_step % training_args.logging_steps == 0 and cur_step > 0:
|
641 |
+
# Save metrics
|
642 |
+
train_metric = jax_utils.unreplicate(train_metric)
|
643 |
+
train_time += time.time() - train_start
|
644 |
+
if has_tensorboard and jax.process_index() == 0:
|
645 |
+
write_train_metric(summary_writer, train_metrics, train_time, cur_step)
|
646 |
+
|
647 |
+
epochs.write(
|
648 |
+
f"Step... ({cur_step} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
|
649 |
+
)
|
650 |
+
|
651 |
+
train_metrics = []
|
652 |
+
|
653 |
+
if cur_step % training_args.eval_steps == 0 and cur_step > 0:
|
654 |
+
# ======================== Evaluating ==============================
|
655 |
+
num_eval_samples = len(tokenized_datasets["validation"])
|
656 |
+
eval_samples_idx = jnp.arange(num_eval_samples)
|
657 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
658 |
+
|
659 |
+
eval_metrics = []
|
660 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
|
661 |
+
samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
|
662 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
663 |
+
|
664 |
+
# Model forward
|
665 |
+
model_inputs = shard(model_inputs.data)
|
666 |
+
metrics = p_eval_step(state.params, model_inputs)
|
667 |
+
eval_metrics.append(metrics)
|
668 |
+
|
669 |
+
# normalize eval metrics
|
670 |
+
eval_metrics = get_metrics(eval_metrics)
|
671 |
+
eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
|
672 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
673 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
674 |
+
|
675 |
+
# Update progress bar
|
676 |
+
epochs.desc = f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
|
677 |
+
|
678 |
+
# Save metrics
|
679 |
+
if has_tensorboard and jax.process_index() == 0:
|
680 |
+
write_eval_metric(summary_writer, eval_metrics, cur_step)
|
681 |
+
|
682 |
+
if cur_step % training_args.save_steps == 0 and cur_step > 0:
|
683 |
+
# save checkpoint after each epoch and push checkpoint to the hub
|
684 |
+
if jax.process_index() == 0:
|
685 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
686 |
+
model.save_pretrained(
|
687 |
+
training_args.output_dir,
|
688 |
+
params=params,
|
689 |
+
push_to_hub=training_args.push_to_hub,
|
690 |
+
commit_message=f"Saving weights and logs of step {cur_step}",
|
691 |
+
)
|
run_step1.sh
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
./run_mlm_flax.py \
|
2 |
+
--output_dir="./" \
|
3 |
+
--model_type="roberta" \
|
4 |
+
--config_name="./" \
|
5 |
+
--tokenizer_name="./" \
|
6 |
+
--dataset_name="NbAiLab/NCC" \
|
7 |
+
--cache_dir="/mnt/disks/flaxdisk/cache/" \
|
8 |
+
--max_seq_length="128" \
|
9 |
+
--weight_decay="0.01" \
|
10 |
+
--per_device_train_batch_size="200" \
|
11 |
+
--per_device_eval_batch_size="200" \
|
12 |
+
--learning_rate="4e-4" \
|
13 |
+
--warmup_steps="10000" \
|
14 |
+
--overwrite_output_dir \
|
15 |
+
--num_train_epochs="10" \
|
16 |
+
--adam_beta1="0.9" \
|
17 |
+
--adam_beta2="0.98" \
|
18 |
+
--adam_epsilon="1e-6" \
|
19 |
+
--logging_steps="10000" \
|
20 |
+
--save_steps="10000" \
|
21 |
+
--eval_steps="10000" \
|
22 |
+
--preprocessing_num_workers="64" \
|
23 |
+
--auth_token="True" \
|
24 |
+
--static_learning_rate="True" \
|
25 |
+
--dtype="bfloat16" \
|
26 |
+
--push_to_hub
|
run_step2.sh
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
./run_mlm_flax.py \
|
2 |
+
--output_dir="./" \
|
3 |
+
--model_type="roberta" \
|
4 |
+
--model_name_or_path="./" \
|
5 |
+
--config_name="./" \
|
6 |
+
--tokenizer_name="./" \
|
7 |
+
--dataset_name="NbAiLab/NCC" \
|
8 |
+
--cache_dir="/mnt/disks/flaxdisk/cache/" \
|
9 |
+
--max_seq_length="128" \
|
10 |
+
--weight_decay="0.01" \
|
11 |
+
--per_device_train_batch_size="200" \
|
12 |
+
--per_device_eval_batch_size="200" \
|
13 |
+
--learning_rate="4e-4" \
|
14 |
+
--warmup_steps="10000" \
|
15 |
+
--overwrite_output_dir \
|
16 |
+
--num_train_epochs="10" \
|
17 |
+
--adam_beta1="0.9" \
|
18 |
+
--adam_beta2="0.98" \
|
19 |
+
--adam_epsilon="1e-6" \
|
20 |
+
--logging_steps="10000" \
|
21 |
+
--save_steps="10000" \
|
22 |
+
--eval_steps="10000" \
|
23 |
+
--preprocessing_num_workers="64" \
|
24 |
+
--auth_token="True" \
|
25 |
+
--dtype="bfloat16" \
|
26 |
+
--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
|
|