Prepping the run
Browse files- .gitattributes +2 -0
- .gitignore +4 -0
- config.json +25 -0
- configs/base/config.json +25 -0
- configs/base/tokenizer.json +0 -0
- configs/large/config.json +25 -0
- configs/large/tokenizer.json +0 -0
- convert.py +29 -0
- merges.txt +0 -0
- run_mlm_flax_stream.py +780 -0
- run_stream.128.sh +27 -0
- run_stream.512.sh +27 -0
- special_tokens_map.json +1 -0
- tokenizer.json +0 -0
- tokenizer_config.json +1 -0
- vocab.json +0 -0
.gitattributes
CHANGED
@@ -15,3 +15,5 @@
|
|
15 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
16 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
17 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
15 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
16 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
17 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.log filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.wandb filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#run*.log
|
2 |
+
debug*.log
|
3 |
+
run*.wandb
|
4 |
+
wandb/
|
config.json
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"RobertaForMaskedLM"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"bos_token_id": 0,
|
7 |
+
"eos_token_id": 2,
|
8 |
+
"gradient_checkpointing": false,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 768,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 3072,
|
14 |
+
"layer_norm_eps": 1e-05,
|
15 |
+
"max_position_embeddings": 514,
|
16 |
+
"model_type": "roberta",
|
17 |
+
"num_attention_heads": 12,
|
18 |
+
"num_hidden_layers": 12,
|
19 |
+
"pad_token_id": 1,
|
20 |
+
"position_embedding_type": "absolute",
|
21 |
+
"transformers_version": "4.9.0.dev0",
|
22 |
+
"type_vocab_size": 1,
|
23 |
+
"use_cache": true,
|
24 |
+
"vocab_size": 50265
|
25 |
+
}
|
configs/base/config.json
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"RobertaForMaskedLM"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"bos_token_id": 0,
|
7 |
+
"eos_token_id": 2,
|
8 |
+
"gradient_checkpointing": false,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 768,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 3072,
|
14 |
+
"layer_norm_eps": 1e-05,
|
15 |
+
"max_position_embeddings": 514,
|
16 |
+
"model_type": "roberta",
|
17 |
+
"num_attention_heads": 12,
|
18 |
+
"num_hidden_layers": 12,
|
19 |
+
"pad_token_id": 1,
|
20 |
+
"position_embedding_type": "absolute",
|
21 |
+
"transformers_version": "4.9.0.dev0",
|
22 |
+
"type_vocab_size": 1,
|
23 |
+
"use_cache": true,
|
24 |
+
"vocab_size": 50265
|
25 |
+
}
|
configs/base/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
configs/large/config.json
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"RobertaForMaskedLM"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"bos_token_id": 0,
|
7 |
+
"eos_token_id": 2,
|
8 |
+
"gradient_checkpointing": false,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 1024,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 4096,
|
14 |
+
"layer_norm_eps": 1e-05,
|
15 |
+
"max_position_embeddings": 514,
|
16 |
+
"model_type": "roberta",
|
17 |
+
"num_attention_heads": 16,
|
18 |
+
"num_hidden_layers": 24,
|
19 |
+
"pad_token_id": 1,
|
20 |
+
"position_embedding_type": "absolute",
|
21 |
+
"transformers_version": "4.9.0.dev0",
|
22 |
+
"type_vocab_size": 1,
|
23 |
+
"use_cache": true,
|
24 |
+
"vocab_size": 50265
|
25 |
+
}
|
configs/large/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
convert.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
import tempfile
|
3 |
+
|
4 |
+
import jax
|
5 |
+
from jax import numpy as jnp
|
6 |
+
from transformers import AutoTokenizer, FlaxRobertaForMaskedLM, RobertaForMaskedLM
|
7 |
+
|
8 |
+
|
9 |
+
def to_f32(t):
|
10 |
+
return jax.tree_map(lambda x: x.astype(jnp.float32) if x.dtype == jnp.bfloat16 else x, t)
|
11 |
+
|
12 |
+
|
13 |
+
def main():
|
14 |
+
# Saving extra files from config.json and tokenizer.json files
|
15 |
+
tokenizer = AutoTokenizer.from_pretrained("./")
|
16 |
+
tokenizer.save_pretrained("./")
|
17 |
+
|
18 |
+
# Temporary saving bfloat16 Flax model into float32
|
19 |
+
tmp = tempfile.mkdtemp()
|
20 |
+
flax_model = FlaxRobertaForMaskedLM.from_pretrained("./")
|
21 |
+
flax_model.params = to_f32(flax_model.params)
|
22 |
+
flax_model.save_pretrained(tmp)
|
23 |
+
# Converting float32 Flax to PyTorch
|
24 |
+
model = RobertaForMaskedLM.from_pretrained(tmp, from_flax=True)
|
25 |
+
model.save_pretrained("./", save_config=False)
|
26 |
+
|
27 |
+
|
28 |
+
if __name__ == "__main__":
|
29 |
+
main()
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
run_mlm_flax_stream.py
ADDED
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 json
|
25 |
+
import os
|
26 |
+
import shutil
|
27 |
+
import sys
|
28 |
+
import time
|
29 |
+
from collections import defaultdict
|
30 |
+
from dataclasses import dataclass, field
|
31 |
+
|
32 |
+
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
|
33 |
+
import joblib
|
34 |
+
from pathlib import Path
|
35 |
+
from typing import Dict, List, Optional, Tuple
|
36 |
+
|
37 |
+
import datasets
|
38 |
+
import numpy as np
|
39 |
+
from datasets import load_dataset
|
40 |
+
from tqdm import tqdm
|
41 |
+
|
42 |
+
import flax
|
43 |
+
import jax
|
44 |
+
import jax.numpy as jnp
|
45 |
+
import kenlm # pip install https://github.com/kpu/kenlm/archive/master.zip
|
46 |
+
import optax
|
47 |
+
from flax import jax_utils, traverse_util
|
48 |
+
from flax.serialization import from_bytes, to_bytes
|
49 |
+
from flax.training import train_state
|
50 |
+
from flax.training.common_utils import get_metrics, onehot, shard
|
51 |
+
from transformers import (
|
52 |
+
CONFIG_MAPPING,
|
53 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING,
|
54 |
+
AutoConfig,
|
55 |
+
AutoTokenizer,
|
56 |
+
FlaxAutoModelForMaskedLM,
|
57 |
+
HfArgumentParser,
|
58 |
+
PreTrainedTokenizerBase,
|
59 |
+
TensorType,
|
60 |
+
TrainingArguments,
|
61 |
+
is_tensorboard_available,
|
62 |
+
set_seed,
|
63 |
+
)
|
64 |
+
|
65 |
+
|
66 |
+
if datasets.__version__ <= "1.8.0":
|
67 |
+
raise ValueError("Make sure to upgrade `datasets` to a version >= 1.9.0 to use dataset streaming")
|
68 |
+
|
69 |
+
|
70 |
+
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
|
71 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
72 |
+
|
73 |
+
|
74 |
+
@dataclass
|
75 |
+
class ModelArguments:
|
76 |
+
"""
|
77 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
78 |
+
"""
|
79 |
+
|
80 |
+
model_name_or_path: Optional[str] = field(
|
81 |
+
default=None,
|
82 |
+
metadata={
|
83 |
+
"help": "The model checkpoint for weights initialization."
|
84 |
+
"Don't set if you want to train a model from scratch."
|
85 |
+
},
|
86 |
+
)
|
87 |
+
model_type: Optional[str] = field(
|
88 |
+
default=None,
|
89 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
90 |
+
)
|
91 |
+
config_name: Optional[str] = field(
|
92 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
93 |
+
)
|
94 |
+
tokenizer_name: Optional[str] = field(
|
95 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
96 |
+
)
|
97 |
+
cache_dir: Optional[str] = field(
|
98 |
+
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
99 |
+
)
|
100 |
+
use_fast_tokenizer: bool = field(
|
101 |
+
default=True,
|
102 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
103 |
+
)
|
104 |
+
dtype: Optional[str] = field(
|
105 |
+
default="float32",
|
106 |
+
metadata={
|
107 |
+
"help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
|
108 |
+
},
|
109 |
+
)
|
110 |
+
|
111 |
+
@dataclass
|
112 |
+
class DataTrainingArguments:
|
113 |
+
"""
|
114 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
115 |
+
"""
|
116 |
+
|
117 |
+
dataset_name: Optional[str] = field(
|
118 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
119 |
+
)
|
120 |
+
dataset_config_name: Optional[str] = field(
|
121 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
122 |
+
)
|
123 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
124 |
+
validation_file: Optional[str] = field(
|
125 |
+
default=None,
|
126 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
127 |
+
)
|
128 |
+
train_ref_file: Optional[str] = field(
|
129 |
+
default=None,
|
130 |
+
metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
|
131 |
+
)
|
132 |
+
validation_ref_file: Optional[str] = field(
|
133 |
+
default=None,
|
134 |
+
metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
|
135 |
+
)
|
136 |
+
overwrite_cache: bool = field(
|
137 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
138 |
+
)
|
139 |
+
validation_split_percentage: Optional[int] = field(
|
140 |
+
default=5,
|
141 |
+
metadata={
|
142 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
143 |
+
},
|
144 |
+
)
|
145 |
+
max_seq_length: Optional[int] = field(
|
146 |
+
default=None,
|
147 |
+
metadata={
|
148 |
+
"help": "The maximum total input sequence length after tokenization. Sequences longer "
|
149 |
+
"than this will be truncated. Default to the max input length of the model."
|
150 |
+
},
|
151 |
+
)
|
152 |
+
preprocessing_num_workers: Optional[int] = field(
|
153 |
+
default=None,
|
154 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
155 |
+
)
|
156 |
+
mlm_probability: float = field(
|
157 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
|
158 |
+
)
|
159 |
+
pad_to_max_length: bool = field(
|
160 |
+
default=False,
|
161 |
+
metadata={
|
162 |
+
"help": "Whether to pad all samples to `max_seq_length`. "
|
163 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
164 |
+
},
|
165 |
+
)
|
166 |
+
line_by_line: bool = field(
|
167 |
+
default=False,
|
168 |
+
metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
|
169 |
+
)
|
170 |
+
text_column_name: str = field(
|
171 |
+
default="text", metadata={"help": "The name of the column to retrieve the training text."}
|
172 |
+
)
|
173 |
+
shuffle_buffer_size: int = field(
|
174 |
+
default=10000, metadata={"help": "The number of examples to pre-load for shuffling."}
|
175 |
+
)
|
176 |
+
num_train_steps: int = field(default=50000, metadata={"help": "The number of training steps."})
|
177 |
+
num_eval_samples: int = field(default=50000, metadata={"help": "The number of samples to be used for evaluation"})
|
178 |
+
|
179 |
+
def __post_init__(self):
|
180 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
181 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
182 |
+
else:
|
183 |
+
if self.train_file is not None:
|
184 |
+
extension = self.train_file.split(".")[-1]
|
185 |
+
assert extension in ["csv", "json", "jsonl", "txt", "gz"], "`train_file` should be a csv, a json (lines) or a txt file."
|
186 |
+
if self.validation_file is not None:
|
187 |
+
extension = self.validation_file.split(".")[-1]
|
188 |
+
assert extension in ["csv", "json", "jsonl", "txt", "gz"], "`validation_file` should be a csv, a json (lines) or a txt file."
|
189 |
+
|
190 |
+
|
191 |
+
@flax.struct.dataclass
|
192 |
+
class FlaxDataCollatorForLanguageModeling:
|
193 |
+
"""
|
194 |
+
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
|
195 |
+
are not all of the same length.
|
196 |
+
|
197 |
+
Args:
|
198 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
199 |
+
The tokenizer used for encoding the data.
|
200 |
+
mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
|
201 |
+
The probability with which to (randomly) mask tokens in the input.
|
202 |
+
|
203 |
+
.. note::
|
204 |
+
|
205 |
+
For best performance, this data collator should be used with a dataset having items that are dictionaries or
|
206 |
+
BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
|
207 |
+
:class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
|
208 |
+
argument :obj:`return_special_tokens_mask=True`.
|
209 |
+
"""
|
210 |
+
|
211 |
+
tokenizer: PreTrainedTokenizerBase
|
212 |
+
mlm_probability: float = 0.15
|
213 |
+
|
214 |
+
def __post_init__(self):
|
215 |
+
if self.tokenizer.mask_token is None:
|
216 |
+
raise ValueError(
|
217 |
+
"This tokenizer does not have a mask token which is necessary for masked language modeling. "
|
218 |
+
"You should pass `mlm=False` to train on causal language modeling instead."
|
219 |
+
)
|
220 |
+
|
221 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
|
222 |
+
# Handle dict or lists with proper padding and conversion to tensor.
|
223 |
+
batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
|
224 |
+
|
225 |
+
# If special token mask has been preprocessed, pop it from the dict.
|
226 |
+
special_tokens_mask = batch.pop("special_tokens_mask", None)
|
227 |
+
|
228 |
+
batch["input_ids"], batch["labels"] = self.mask_tokens(
|
229 |
+
batch["input_ids"], special_tokens_mask=special_tokens_mask
|
230 |
+
)
|
231 |
+
return batch
|
232 |
+
|
233 |
+
def mask_tokens(
|
234 |
+
self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
|
235 |
+
) -> Tuple[jnp.ndarray, jnp.ndarray]:
|
236 |
+
"""
|
237 |
+
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
|
238 |
+
"""
|
239 |
+
labels = inputs.copy()
|
240 |
+
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
|
241 |
+
probability_matrix = np.full(labels.shape, self.mlm_probability)
|
242 |
+
special_tokens_mask = special_tokens_mask.astype("bool")
|
243 |
+
|
244 |
+
probability_matrix[special_tokens_mask] = 0.0
|
245 |
+
masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
|
246 |
+
labels[~masked_indices] = -100 # We only compute loss on masked tokens
|
247 |
+
|
248 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
249 |
+
indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
|
250 |
+
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
|
251 |
+
|
252 |
+
# 10% of the time, we replace masked input tokens with random word
|
253 |
+
indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
|
254 |
+
indices_random &= masked_indices & ~indices_replaced
|
255 |
+
|
256 |
+
random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
|
257 |
+
inputs[indices_random] = random_words[indices_random]
|
258 |
+
|
259 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
260 |
+
return inputs, labels
|
261 |
+
|
262 |
+
|
263 |
+
@dataclass
|
264 |
+
class SamplingArguments:
|
265 |
+
"""
|
266 |
+
Arguments pertaining to how to perform sampling of the dataset.
|
267 |
+
"""
|
268 |
+
|
269 |
+
perplexity_model: Optional[str] = field(
|
270 |
+
default="./es.arpa.bin", metadata={"help": "Path to KenLM model to use to get perplexity values."}
|
271 |
+
)
|
272 |
+
sampling_method: Optional[str] = field(
|
273 |
+
default=None, metadata={"help": "Sample using a 'step' or 'gaussian' perplexity function per document, or 'random'."}
|
274 |
+
)
|
275 |
+
sampling_factor: Optional[float] = field(
|
276 |
+
default=None, metadata={"help": "Sampling factor. Integers for step function, decimals for gaussian."}
|
277 |
+
)
|
278 |
+
boundaries: Optional[str] = field(
|
279 |
+
default="536394.99320948,662247.50212365,919250.87225178", metadata={"help": "Quartile boundaries"}
|
280 |
+
)
|
281 |
+
|
282 |
+
def __post_init__(self):
|
283 |
+
self.boundaries = [float(q.strip()) for q in self.boundaries.split(",")]
|
284 |
+
|
285 |
+
|
286 |
+
def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
|
287 |
+
num_samples = len(samples_idx)
|
288 |
+
samples_to_remove = num_samples % batch_size
|
289 |
+
|
290 |
+
if samples_to_remove != 0:
|
291 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
292 |
+
sections_split = num_samples // batch_size
|
293 |
+
batch_idx = np.split(samples_idx, sections_split)
|
294 |
+
return batch_idx
|
295 |
+
|
296 |
+
|
297 |
+
def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
|
298 |
+
"""
|
299 |
+
The training iterator is advanced so that after groupifying the samples,
|
300 |
+
`num_samples` of length `max_seq_length` are returned.
|
301 |
+
"""
|
302 |
+
num_total_tokens = max_seq_length * num_samples
|
303 |
+
samples = defaultdict(list)
|
304 |
+
|
305 |
+
i = 0
|
306 |
+
while i < num_total_tokens:
|
307 |
+
tokenized_samples = next(train_iterator)
|
308 |
+
i += len(tokenized_samples["input_ids"])
|
309 |
+
|
310 |
+
# concatenate tokenized samples to list
|
311 |
+
samples = {k: samples[k] + tokenized_samples[k] for k in tokenized_samples.keys()}
|
312 |
+
|
313 |
+
# Concatenated tokens are split to lists of length `max_seq_length`.
|
314 |
+
# Note that remainedr of % max_seq_length are thrown away.
|
315 |
+
def group_texts(examples):
|
316 |
+
result = {
|
317 |
+
k: [t[i : i + max_seq_length] for i in range(0, num_total_tokens, max_seq_length)]
|
318 |
+
for k, t in examples.items()
|
319 |
+
}
|
320 |
+
return result
|
321 |
+
|
322 |
+
grouped_samples = group_texts(samples)
|
323 |
+
return grouped_samples
|
324 |
+
|
325 |
+
|
326 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
327 |
+
summary_writer.scalar("train_time", train_time, step)
|
328 |
+
|
329 |
+
train_metrics = get_metrics(train_metrics)
|
330 |
+
for key, vals in train_metrics.items():
|
331 |
+
tag = f"train_{key}"
|
332 |
+
for i, val in enumerate(vals):
|
333 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
334 |
+
|
335 |
+
|
336 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
337 |
+
for metric_name, value in eval_metrics.items():
|
338 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
339 |
+
|
340 |
+
|
341 |
+
def save_checkpoint_files(state, data_collator, training_args, save_dir):
|
342 |
+
unreplicated_state = jax_utils.unreplicate(state)
|
343 |
+
with open(os.path.join(save_dir, "optimizer_state.msgpack"), "wb") as f:
|
344 |
+
f.write(to_bytes(unreplicated_state.opt_state))
|
345 |
+
joblib.dump(training_args, os.path.join(save_dir, "training_args.joblib"))
|
346 |
+
joblib.dump(data_collator, os.path.join(save_dir, "data_collator.joblib"))
|
347 |
+
with open(os.path.join(save_dir, "training_state.json"), "w") as f:
|
348 |
+
json.dump({"step": unreplicated_state.step.item()}, f)
|
349 |
+
|
350 |
+
|
351 |
+
def restore_checkpoint(save_dir, state):
|
352 |
+
logger.info(f"Restoring checkpoint from {save_dir}")
|
353 |
+
with open(os.path.join(save_dir, "flax_model.msgpack"), "rb") as f:
|
354 |
+
params = from_bytes(state.params, f.read())
|
355 |
+
|
356 |
+
with open(os.path.join(save_dir, "optimizer_state.msgpack"), "rb") as f:
|
357 |
+
opt_state = from_bytes(state.opt_state, f.read())
|
358 |
+
|
359 |
+
args = joblib.load(os.path.join(save_dir, "training_args.joblib"))
|
360 |
+
data_collator = joblib.load(os.path.join(save_dir, "data_collator.joblib"))
|
361 |
+
|
362 |
+
with open(os.path.join(save_dir, "training_state.json"), "r") as f:
|
363 |
+
training_state = json.load(f)
|
364 |
+
step = training_state["step"]
|
365 |
+
|
366 |
+
return params, opt_state, step, args, data_collator
|
367 |
+
|
368 |
+
|
369 |
+
def rotate_checkpoints(path, max_checkpoints=5):
|
370 |
+
paths = sorted(Path(path).iterdir(), key=os.path.getmtime)[::-1]
|
371 |
+
if len(paths) > max_checkpoints:
|
372 |
+
for path_to_delete in paths[max_checkpoints:]:
|
373 |
+
try:
|
374 |
+
shutil.rmtree(path_to_delete)
|
375 |
+
except OSError:
|
376 |
+
os.remove(path_to_delete)
|
377 |
+
|
378 |
+
|
379 |
+
if __name__ == "__main__":
|
380 |
+
# See all possible arguments in src/transformers/training_args.py
|
381 |
+
# or by passing the --help flag to this script.
|
382 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
383 |
+
|
384 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, SamplingArguments))
|
385 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
386 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
387 |
+
# let's parse it to get our arguments.
|
388 |
+
model_args, data_args, training_args, sampling_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
389 |
+
else:
|
390 |
+
model_args, data_args, training_args, sampling_args = parser.parse_args_into_dataclasses()
|
391 |
+
|
392 |
+
if (
|
393 |
+
os.path.exists(training_args.output_dir)
|
394 |
+
and os.listdir(training_args.output_dir)
|
395 |
+
and training_args.do_train
|
396 |
+
and not training_args.overwrite_output_dir
|
397 |
+
):
|
398 |
+
raise ValueError(
|
399 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
400 |
+
"Use --overwrite_output_dir to overcome."
|
401 |
+
)
|
402 |
+
|
403 |
+
# Setup logging
|
404 |
+
logging.basicConfig(
|
405 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
406 |
+
level="INFO",
|
407 |
+
datefmt="[%X]",
|
408 |
+
)
|
409 |
+
|
410 |
+
# Log on each process the small summary:
|
411 |
+
logger = logging.getLogger(__name__)
|
412 |
+
logger.warning(
|
413 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
414 |
+
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
415 |
+
)
|
416 |
+
|
417 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
418 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
419 |
+
|
420 |
+
# Set seed before initializing model.
|
421 |
+
set_seed(training_args.seed)
|
422 |
+
|
423 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
424 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
425 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
426 |
+
#
|
427 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
428 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
429 |
+
if data_args.dataset_name is not None:
|
430 |
+
# Downloading and loading a dataset from the hub.
|
431 |
+
filepaths = {}
|
432 |
+
if data_args.train_file:
|
433 |
+
filepaths["train"] = data_args.train_file
|
434 |
+
if data_args.validation_file:
|
435 |
+
filepaths["validation"] = data_args.validation_file
|
436 |
+
try:
|
437 |
+
dataset = load_dataset(
|
438 |
+
data_args.dataset_name,
|
439 |
+
data_args.dataset_config_name,
|
440 |
+
cache_dir=model_args.cache_dir,
|
441 |
+
streaming=True,
|
442 |
+
split="train",
|
443 |
+
sampling_method=sampling_args.sampling_method,
|
444 |
+
sampling_factor=sampling_args.sampling_factor,
|
445 |
+
boundaries=sampling_args.boundaries,
|
446 |
+
perplexity_model=sampling_args.perplexity_model,
|
447 |
+
seed=training_args.seed,
|
448 |
+
data_files=filepaths,
|
449 |
+
)
|
450 |
+
except Exception as exc:
|
451 |
+
logger.warning(
|
452 |
+
f"Unable to load local dataset with perplexity sampling support. Using huggingface.co/datasets/{data_args.dataset_name}: {exc}"
|
453 |
+
)
|
454 |
+
dataset = load_dataset(
|
455 |
+
data_args.dataset_name,
|
456 |
+
data_args.dataset_config_name,
|
457 |
+
cache_dir=model_args.cache_dir,
|
458 |
+
streaming=True,
|
459 |
+
split="train",
|
460 |
+
)
|
461 |
+
|
462 |
+
if model_args.config_name:
|
463 |
+
config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
|
464 |
+
elif model_args.model_name_or_path:
|
465 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
|
466 |
+
else:
|
467 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
468 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
469 |
+
|
470 |
+
if model_args.tokenizer_name:
|
471 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
472 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
473 |
+
)
|
474 |
+
elif model_args.model_name_or_path:
|
475 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
476 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
477 |
+
)
|
478 |
+
else:
|
479 |
+
raise ValueError(
|
480 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
481 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
482 |
+
)
|
483 |
+
|
484 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
485 |
+
# We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
|
486 |
+
# efficient when it receives the `special_tokens_mask`.
|
487 |
+
def tokenize_function(examples):
|
488 |
+
return tokenizer(
|
489 |
+
examples[data_args.text_column_name],
|
490 |
+
return_special_tokens_mask=True
|
491 |
+
)
|
492 |
+
|
493 |
+
tokenized_datasets = dataset.map(
|
494 |
+
tokenize_function,
|
495 |
+
batched=True,
|
496 |
+
)
|
497 |
+
|
498 |
+
shuffle_seed = training_args.seed
|
499 |
+
tokenized_datasets = tokenized_datasets.shuffle(buffer_size=data_args.shuffle_buffer_size, seed=shuffle_seed)
|
500 |
+
|
501 |
+
# Enable tensorboard only on the master node
|
502 |
+
has_tensorboard = is_tensorboard_available()
|
503 |
+
if has_tensorboard and jax.process_index() == 0:
|
504 |
+
try:
|
505 |
+
# Enable Weight&Biases
|
506 |
+
import wandb
|
507 |
+
wandb.init(
|
508 |
+
entity='wandb',
|
509 |
+
project='hf-flax-bertin-roberta-es',
|
510 |
+
sync_tensorboard=True,
|
511 |
+
)
|
512 |
+
wandb.config.update(training_args)
|
513 |
+
wandb.config.update(model_args)
|
514 |
+
wandb.config.update(data_args)
|
515 |
+
from flax.metrics.tensorboard import SummaryWriter
|
516 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
517 |
+
except ImportError as ie:
|
518 |
+
has_tensorboard = False
|
519 |
+
logger.warning(
|
520 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
521 |
+
)
|
522 |
+
else:
|
523 |
+
logger.warning(
|
524 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
525 |
+
"Please run pip install tensorboard to enable."
|
526 |
+
)
|
527 |
+
|
528 |
+
# Data collator
|
529 |
+
# This one will take care of randomly masking the tokens.
|
530 |
+
data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
|
531 |
+
|
532 |
+
# Initialize our training
|
533 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
534 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
535 |
+
|
536 |
+
if model_args.model_name_or_path:
|
537 |
+
model = FlaxAutoModelForMaskedLM.from_pretrained(
|
538 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
539 |
+
)
|
540 |
+
else:
|
541 |
+
model = FlaxAutoModelForMaskedLM.from_config(
|
542 |
+
config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
543 |
+
)
|
544 |
+
|
545 |
+
# Store some constant
|
546 |
+
num_epochs = int(training_args.num_train_epochs)
|
547 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
548 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
549 |
+
|
550 |
+
# define number steps per stream epoch
|
551 |
+
num_train_steps = data_args.num_train_steps
|
552 |
+
|
553 |
+
# Create learning rate schedule
|
554 |
+
warmup_fn = optax.linear_schedule(
|
555 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
556 |
+
)
|
557 |
+
decay_fn = optax.linear_schedule(
|
558 |
+
init_value=training_args.learning_rate,
|
559 |
+
end_value=0,
|
560 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
561 |
+
)
|
562 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
563 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
564 |
+
)
|
565 |
+
|
566 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
567 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
568 |
+
# mask boolean with the same structure as the parameters.
|
569 |
+
# The mask is True for parameters that should be decayed.
|
570 |
+
# Note that this mask is specifically adapted for FlaxBERT-like models.
|
571 |
+
# For other models, one should correct the layer norm parameter naming
|
572 |
+
# accordingly.
|
573 |
+
def decay_mask_fn(params):
|
574 |
+
flat_params = traverse_util.flatten_dict(params)
|
575 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
|
576 |
+
return traverse_util.unflatten_dict(flat_mask)
|
577 |
+
|
578 |
+
# create adam optimizer
|
579 |
+
adamw = optax.adamw(
|
580 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
581 |
+
b1=training_args.adam_beta1,
|
582 |
+
b2=training_args.adam_beta2,
|
583 |
+
eps=training_args.adam_epsilon,
|
584 |
+
weight_decay=training_args.weight_decay,
|
585 |
+
mask=decay_mask_fn,
|
586 |
+
)
|
587 |
+
|
588 |
+
# Setup train state
|
589 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=adamw)
|
590 |
+
saved_step = -1
|
591 |
+
if model_args.model_name_or_path and "checkpoint" in model_args.model_name_or_path:
|
592 |
+
params, opt_state, saved_step, args, data_collator = restore_checkpoint(model_args.model_name_or_path, state)
|
593 |
+
# Create learning rate schedule
|
594 |
+
warmup_fn = optax.linear_schedule(
|
595 |
+
init_value=0.0, end_value=args.learning_rate, transition_steps=args.warmup_steps
|
596 |
+
)
|
597 |
+
decay_fn = optax.linear_schedule(
|
598 |
+
init_value=args.learning_rate,
|
599 |
+
end_value=0,
|
600 |
+
transition_steps=data_args.num_train_steps - args.warmup_steps,
|
601 |
+
)
|
602 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
603 |
+
schedules=[warmup_fn, decay_fn], boundaries=[args.warmup_steps]
|
604 |
+
)
|
605 |
+
# create adam optimizer
|
606 |
+
adamw = optax.adamw(
|
607 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
608 |
+
b1=training_args.adam_beta1,
|
609 |
+
b2=training_args.adam_beta2,
|
610 |
+
eps=training_args.adam_epsilon,
|
611 |
+
weight_decay=args.weight_decay,
|
612 |
+
mask=decay_mask_fn,
|
613 |
+
)
|
614 |
+
state = train_state.TrainState(
|
615 |
+
step=saved_step,
|
616 |
+
apply_fn=model.__call__,
|
617 |
+
params=params,
|
618 |
+
tx=adamw,
|
619 |
+
opt_state=opt_state,
|
620 |
+
)
|
621 |
+
# self.args = args
|
622 |
+
# data_collator = data_collator
|
623 |
+
# scheduler_fn = args.learning_rate
|
624 |
+
model.params = params
|
625 |
+
|
626 |
+
|
627 |
+
# Define gradient update step fn
|
628 |
+
def train_step(state, batch, dropout_rng):
|
629 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
630 |
+
|
631 |
+
def loss_fn(params):
|
632 |
+
labels = batch.pop("labels")
|
633 |
+
|
634 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
635 |
+
|
636 |
+
# compute loss, ignore padded input tokens
|
637 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
638 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
639 |
+
|
640 |
+
# take average
|
641 |
+
loss = loss.sum() / label_mask.sum()
|
642 |
+
|
643 |
+
return loss
|
644 |
+
|
645 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
646 |
+
loss, grad = grad_fn(state.params)
|
647 |
+
grad = jax.lax.pmean(grad, "batch")
|
648 |
+
new_state = state.apply_gradients(grads=grad)
|
649 |
+
|
650 |
+
metrics = jax.lax.pmean(
|
651 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
652 |
+
)
|
653 |
+
|
654 |
+
return new_state, metrics, new_dropout_rng
|
655 |
+
|
656 |
+
# Create parallel version of the train step
|
657 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
658 |
+
|
659 |
+
# Define eval fn
|
660 |
+
def eval_step(params, batch):
|
661 |
+
labels = batch.pop("labels")
|
662 |
+
|
663 |
+
logits = model(**batch, params=params, train=False)[0]
|
664 |
+
|
665 |
+
# compute loss, ignore padded input tokens
|
666 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
667 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
668 |
+
|
669 |
+
# compute accuracy
|
670 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
|
671 |
+
|
672 |
+
# summarize metrics
|
673 |
+
metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
|
674 |
+
metrics = jax.lax.psum(metrics, axis_name="batch")
|
675 |
+
|
676 |
+
return metrics
|
677 |
+
|
678 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
679 |
+
|
680 |
+
# Replicate the train state on each device
|
681 |
+
state = jax_utils.replicate(state)
|
682 |
+
|
683 |
+
train_time = 0
|
684 |
+
train_start = time.time()
|
685 |
+
train_metrics = []
|
686 |
+
eval_metrics = []
|
687 |
+
|
688 |
+
training_iter = iter(tokenized_datasets)
|
689 |
+
|
690 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
691 |
+
eval_samples = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, max_seq_length)
|
692 |
+
|
693 |
+
steps = tqdm(range(num_train_steps), desc="Training...", position=0)
|
694 |
+
for step in range(0, num_train_steps):
|
695 |
+
if step < saved_step:
|
696 |
+
steps.update(1)
|
697 |
+
continue
|
698 |
+
# ======================== Training ================================
|
699 |
+
try:
|
700 |
+
samples = advance_iter_and_group_samples(training_iter, train_batch_size, max_seq_length)
|
701 |
+
except StopIteration:
|
702 |
+
# Once the end of the dataset stream is reached, the training iterator
|
703 |
+
# is reinitialized and reshuffled and a new eval dataset is randomely chosen.
|
704 |
+
shuffle_seed += 1
|
705 |
+
tokenized_datasets.set_epoch(shuffle_seed)
|
706 |
+
|
707 |
+
training_iter = iter(tokenized_datasets)
|
708 |
+
|
709 |
+
eval_dataset = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, max_seq_length)
|
710 |
+
samples = advance_iter_and_group_samples(training_iter, train_batch_size, max_seq_length)
|
711 |
+
|
712 |
+
# process input samples
|
713 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
714 |
+
|
715 |
+
# Model forward
|
716 |
+
model_inputs = shard(model_inputs.data)
|
717 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
718 |
+
|
719 |
+
train_metrics.append(train_metric)
|
720 |
+
|
721 |
+
if step % training_args.logging_steps == 0 and step > 0:
|
722 |
+
steps.write(
|
723 |
+
f"Step... ({step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
|
724 |
+
)
|
725 |
+
train_time += time.time() - train_start
|
726 |
+
if has_tensorboard and jax.process_index() == 0:
|
727 |
+
write_train_metric(summary_writer, train_metrics, train_time, step)
|
728 |
+
train_metrics = []
|
729 |
+
|
730 |
+
# ======================== Evaluating ==============================
|
731 |
+
if step % training_args.eval_steps == 0 and step > 0:
|
732 |
+
eval_samples_idx = jnp.arange(data_args.num_eval_samples)
|
733 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
734 |
+
|
735 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=1)):
|
736 |
+
# process input samples
|
737 |
+
batch_eval_samples = {k: [v[idx] for idx in batch_idx] for k, v in eval_samples.items()}
|
738 |
+
model_inputs = data_collator(batch_eval_samples, pad_to_multiple_of=16)
|
739 |
+
|
740 |
+
# Model forward
|
741 |
+
model_inputs = shard(model_inputs.data)
|
742 |
+
metrics = p_eval_step(state.params, model_inputs)
|
743 |
+
eval_metrics.append(metrics)
|
744 |
+
|
745 |
+
# normalize eval metrics
|
746 |
+
eval_metrics = get_metrics(eval_metrics)
|
747 |
+
eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
|
748 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
749 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
750 |
+
|
751 |
+
# Update progress bar
|
752 |
+
steps.desc = f"Step... ({step + 1}/{num_train_steps} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
|
753 |
+
|
754 |
+
if has_tensorboard and jax.process_index() == 0:
|
755 |
+
write_eval_metric(summary_writer, eval_metrics, step)
|
756 |
+
eval_metrics = []
|
757 |
+
|
758 |
+
# save checkpoint after eval_steps
|
759 |
+
if step % training_args.save_steps == 0 and step > 0 and jax.process_index() == 0:
|
760 |
+
logger.info(f"Saving checkpoint at {step} steps")
|
761 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
762 |
+
model.save_pretrained(
|
763 |
+
training_args.output_dir,
|
764 |
+
params=params,
|
765 |
+
push_to_hub=training_args.push_to_hub,
|
766 |
+
commit_message=f"Saving weights and logs of step {step + 1}",
|
767 |
+
)
|
768 |
+
save_checkpoint_files(state, data_collator, training_args, training_args.output_dir)
|
769 |
+
checkpoints_dir = Path(training_args.output_dir) / "checkpoints" / f"checkpoint-{step}"
|
770 |
+
checkpoints_dir.mkdir(parents=True, exist_ok=True)
|
771 |
+
model.save_pretrained(checkpoints_dir, params=params)
|
772 |
+
save_checkpoint_files(state, data_collator, training_args, checkpoints_dir)
|
773 |
+
rotate_checkpoints(
|
774 |
+
Path(training_args.output_dir) / "checkpoints",
|
775 |
+
max_checkpoints=training_args.save_total_limit
|
776 |
+
)
|
777 |
+
|
778 |
+
# update tqdm bar
|
779 |
+
steps.update(1)
|
780 |
+
|
run_stream.128.sh
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# From https://arxiv.org/pdf/1907.11692.pdf for base model
|
2 |
+
python -c "import jax; print('TPUs', jax.device_count())"
|
3 |
+
python ./run_mlm_flax_stream.py \
|
4 |
+
--output_dir="./outputs" \
|
5 |
+
--model_type="roberta" \
|
6 |
+
--config_name="./configs/base" \
|
7 |
+
--tokenizer_name="./configs/base" \
|
8 |
+
--dataset_name="./mc4" \
|
9 |
+
--dataset_config_name="es" \
|
10 |
+
--train_file="../mc4-es-train-50M-random.jsonl" \
|
11 |
+
--max_seq_length="128" \
|
12 |
+
--pad_to_max_length \
|
13 |
+
--per_device_train_batch_size="256" \
|
14 |
+
--per_device_eval_batch_size="256" \
|
15 |
+
--adam_beta1="0.9" \
|
16 |
+
--adam_beta2="0.98" \
|
17 |
+
--adam_epsilon="1e-6" \
|
18 |
+
--learning_rate="6e-4" \
|
19 |
+
--weight_decay="0.01" \
|
20 |
+
--save_steps="10000" \
|
21 |
+
--save_total_limit="5" \
|
22 |
+
--warmup_steps="24000" \
|
23 |
+
--overwrite_output_dir \
|
24 |
+
--num_train_steps="250000" \
|
25 |
+
--eval_steps="10000" \
|
26 |
+
--dtype="bfloat16" \
|
27 |
+
--logging_steps="500" 2>&1 | tee run_stream.log
|
run_stream.512.sh
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# From https://arxiv.org/pdf/1907.11692.pdf for base model
|
2 |
+
python -c "import jax; print('TPUs', jax.device_count())"
|
3 |
+
python ./run_mlm_flax_stream.py \
|
4 |
+
--model_name_or_path="bertin-project/bertin-base-gaussian" \
|
5 |
+
--output_dir="./outputs" \
|
6 |
+
--model_type="roberta" \
|
7 |
+
--config_name="./configs/base" \
|
8 |
+
--tokenizer_name="./configs/base" \
|
9 |
+
--dataset_name="versae/mc4-es-sampled" \
|
10 |
+
--dataset_config_name="gaussian" \
|
11 |
+
--max_seq_length="512" \
|
12 |
+
--pad_to_max_length \
|
13 |
+
--per_device_train_batch_size="48" \
|
14 |
+
--per_device_eval_batch_size="48" \
|
15 |
+
--adam_beta1="0.9" \
|
16 |
+
--adam_beta2="0.98" \
|
17 |
+
--adam_epsilon="1e-6" \
|
18 |
+
--learning_rate="6e-4" \
|
19 |
+
--weight_decay="0.01" \
|
20 |
+
--save_steps="1000" \
|
21 |
+
--save_total_limit="5" \
|
22 |
+
--warmup_steps="500" \
|
23 |
+
--overwrite_output_dir \
|
24 |
+
--num_train_steps="50000" \
|
25 |
+
--eval_steps="1000" \
|
26 |
+
--dtype="bfloat16" \
|
27 |
+
--logging_steps="500" 2>&1 | tee run_stream.log
|
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"}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|