init files
Browse files- config.json +27 -0
- config.py +7 -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
- run.sh +29 -0
- run_mlm_flax.py +1003 -0
- run_mlm_flax_stream.py +825 -0
- run_stream.sh +26 -0
- special_tokens_map.json +1 -0
- tokenizer.json +0 -0
- tokenizer_config.json +1 -0
- tokens.py +25 -0
- training_state.json +1 -0
config.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "./configs/base",
|
| 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 |
+
"transformers_version": "4.22.0.dev0",
|
| 24 |
+
"type_vocab_size": 1,
|
| 25 |
+
"use_cache": true,
|
| 26 |
+
"vocab_size": 50265
|
| 27 |
+
}
|
config.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
from transformers import RobertaConfig
|
| 3 |
+
config = RobertaConfig.from_pretrained("roberta-large")
|
| 4 |
+
config.save_pretrained("./configs/large")
|
| 5 |
+
|
| 6 |
+
config = RobertaConfig.from_pretrained("roberta-base")
|
| 7 |
+
config.save_pretrained("./configs/base")
|
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()
|
run.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From https://arxiv.org/pdf/1907.11692.pdf
|
| 2 |
+
python3 -c "import jax; print('TPUs', jax.device_count())"
|
| 3 |
+
python3 run_mlm_flax.py \
|
| 4 |
+
--output_dir="./outputs" \
|
| 5 |
+
--model_type="roberta" \
|
| 6 |
+
--config_name="./configs/base" \
|
| 7 |
+
--tokenizer_name="./" \
|
| 8 |
+
--dataset_name="munggok/KoPI" \
|
| 9 |
+
--cache_dir="/data/cache" \
|
| 10 |
+
--dataset_config_name="full" \
|
| 11 |
+
--max_seq_length="512" \
|
| 12 |
+
--pad_to_max_length \
|
| 13 |
+
--per_device_train_batch_size="64" \
|
| 14 |
+
--per_device_eval_batch_size="64" \
|
| 15 |
+
--preprocessing_num_workers="96" \
|
| 16 |
+
--adam_beta1="0.9" \
|
| 17 |
+
--adam_beta2="0.98" \
|
| 18 |
+
--adam_epsilon="1e-6" \
|
| 19 |
+
--learning_rate="8e-5" \
|
| 20 |
+
--num_train_epochs="15" \
|
| 21 |
+
--weight_decay="0.01" \
|
| 22 |
+
--save_strategy="steps" \
|
| 23 |
+
--save_steps="10000" \
|
| 24 |
+
--save_total_limit='5' \
|
| 25 |
+
--warmup_steps="5000" \
|
| 26 |
+
--overwrite_output_dir \
|
| 27 |
+
--eval_steps="10000" \
|
| 28 |
+
--logging_steps="500" \
|
| 29 |
+
--dtype="bfloat16" 2>&1 | tee run.log
|
run_mlm_flax.py
ADDED
|
@@ -0,0 +1,1003 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
|
| 20 |
+
https://huggingface.co/models?filter=fill-mask
|
| 21 |
+
"""
|
| 22 |
+
import json
|
| 23 |
+
import logging
|
| 24 |
+
import math
|
| 25 |
+
import os
|
| 26 |
+
import sys
|
| 27 |
+
import time
|
| 28 |
+
from dataclasses import asdict, dataclass, field
|
| 29 |
+
from enum import Enum
|
| 30 |
+
from itertools import chain
|
| 31 |
+
from flax.serialization import from_bytes, to_bytes
|
| 32 |
+
import shutil
|
| 33 |
+
|
| 34 |
+
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from typing import Dict, List, Optional, Tuple,Union
|
| 37 |
+
|
| 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 optax
|
| 46 |
+
from flax import jax_utils, traverse_util
|
| 47 |
+
from flax.jax_utils import pad_shard_unpad
|
| 48 |
+
from flax.training import train_state
|
| 49 |
+
from flax.training.common_utils import get_metrics, onehot, shard
|
| 50 |
+
from huggingface_hub import Repository
|
| 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 |
+
is_tensorboard_available,
|
| 61 |
+
set_seed,
|
| 62 |
+
)
|
| 63 |
+
from transformers.utils import get_full_repo_name, send_example_telemetry
|
| 64 |
+
from transformers.trainer_utils import (
|
| 65 |
+
IntervalStrategy,
|
| 66 |
+
|
| 67 |
+
)
|
| 68 |
+
from transformers.file_utils import PushToHubMixin
|
| 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 TrainingArguments:
|
| 76 |
+
output_dir: str = field(
|
| 77 |
+
metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
|
| 78 |
+
)
|
| 79 |
+
overwrite_output_dir: bool = field(
|
| 80 |
+
default=False,
|
| 81 |
+
metadata={
|
| 82 |
+
"help": (
|
| 83 |
+
"Overwrite the content of the output directory. "
|
| 84 |
+
"Use this to continue training if output_dir points to a checkpoint directory."
|
| 85 |
+
)
|
| 86 |
+
},
|
| 87 |
+
)
|
| 88 |
+
do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
|
| 89 |
+
do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
|
| 90 |
+
per_device_train_batch_size: int = field(
|
| 91 |
+
default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."}
|
| 92 |
+
)
|
| 93 |
+
per_device_eval_batch_size: int = field(
|
| 94 |
+
default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}
|
| 95 |
+
)
|
| 96 |
+
learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
|
| 97 |
+
weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
|
| 98 |
+
adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
|
| 99 |
+
adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
|
| 100 |
+
adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
|
| 101 |
+
adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
|
| 102 |
+
num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
|
| 103 |
+
warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})
|
| 104 |
+
logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."})
|
| 105 |
+
save_steps: int = field(default=10000, metadata={"help": "Save checkpoint every X updates steps."})
|
| 106 |
+
eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."})
|
| 107 |
+
seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
|
| 108 |
+
save_strategy: Union[IntervalStrategy, str] = field(
|
| 109 |
+
default="steps",
|
| 110 |
+
metadata={"help": "The checkpoint save strategy to use."},
|
| 111 |
+
)
|
| 112 |
+
save_total_limit: Optional[int] = field(
|
| 113 |
+
default=None,
|
| 114 |
+
metadata={
|
| 115 |
+
"help": (
|
| 116 |
+
"Limit the total amount of checkpoints. "
|
| 117 |
+
"Deletes the older checkpoints in the output_dir. Default is unlimited checkpoints"
|
| 118 |
+
)
|
| 119 |
+
},
|
| 120 |
+
)
|
| 121 |
+
push_to_hub: bool = field(
|
| 122 |
+
default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."}
|
| 123 |
+
)
|
| 124 |
+
hub_model_id: str = field(
|
| 125 |
+
default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."}
|
| 126 |
+
)
|
| 127 |
+
hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."})
|
| 128 |
+
gradient_checkpointing: bool = field(
|
| 129 |
+
default=False,
|
| 130 |
+
metadata={
|
| 131 |
+
"help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass."
|
| 132 |
+
},
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def __post_init__(self):
|
| 136 |
+
if self.output_dir is not None:
|
| 137 |
+
self.output_dir = os.path.expanduser(self.output_dir)
|
| 138 |
+
|
| 139 |
+
def to_dict(self):
|
| 140 |
+
"""
|
| 141 |
+
Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
|
| 142 |
+
the token values by removing their value.
|
| 143 |
+
"""
|
| 144 |
+
d = asdict(self)
|
| 145 |
+
for k, v in d.items():
|
| 146 |
+
if isinstance(v, Enum):
|
| 147 |
+
d[k] = v.value
|
| 148 |
+
if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):
|
| 149 |
+
d[k] = [x.value for x in v]
|
| 150 |
+
if k.endswith("_token"):
|
| 151 |
+
d[k] = f"<{k.upper()}>"
|
| 152 |
+
return d
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@dataclass
|
| 156 |
+
class ModelArguments:
|
| 157 |
+
"""
|
| 158 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
model_name_or_path: Optional[str] = field(
|
| 162 |
+
default=None,
|
| 163 |
+
metadata={
|
| 164 |
+
"help": (
|
| 165 |
+
"The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."
|
| 166 |
+
)
|
| 167 |
+
},
|
| 168 |
+
)
|
| 169 |
+
model_type: Optional[str] = field(
|
| 170 |
+
default=None,
|
| 171 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
| 172 |
+
)
|
| 173 |
+
config_name: Optional[str] = field(
|
| 174 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
| 175 |
+
)
|
| 176 |
+
tokenizer_name: Optional[str] = field(
|
| 177 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
| 178 |
+
)
|
| 179 |
+
cache_dir: Optional[str] = field(
|
| 180 |
+
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
| 181 |
+
)
|
| 182 |
+
use_fast_tokenizer: bool = field(
|
| 183 |
+
default=True,
|
| 184 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
| 185 |
+
)
|
| 186 |
+
dtype: Optional[str] = field(
|
| 187 |
+
default="float32",
|
| 188 |
+
metadata={
|
| 189 |
+
"help": (
|
| 190 |
+
"Floating-point format in which the model weights should be initialized and trained. Choose one of"
|
| 191 |
+
" `[float32, float16, bfloat16]`."
|
| 192 |
+
)
|
| 193 |
+
},
|
| 194 |
+
)
|
| 195 |
+
use_auth_token: bool = field(
|
| 196 |
+
default=False,
|
| 197 |
+
metadata={
|
| 198 |
+
"help": (
|
| 199 |
+
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
|
| 200 |
+
"with private models)."
|
| 201 |
+
)
|
| 202 |
+
},
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@dataclass
|
| 207 |
+
class DataTrainingArguments:
|
| 208 |
+
"""
|
| 209 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
dataset_name: Optional[str] = field(
|
| 213 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
| 214 |
+
)
|
| 215 |
+
dataset_config_name: Optional[str] = field(
|
| 216 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
| 217 |
+
)
|
| 218 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
| 219 |
+
validation_file: Optional[str] = field(
|
| 220 |
+
default=None,
|
| 221 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
| 222 |
+
)
|
| 223 |
+
train_ref_file: Optional[str] = field(
|
| 224 |
+
default=None,
|
| 225 |
+
metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
|
| 226 |
+
)
|
| 227 |
+
validation_ref_file: Optional[str] = field(
|
| 228 |
+
default=None,
|
| 229 |
+
metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
|
| 230 |
+
)
|
| 231 |
+
overwrite_cache: bool = field(
|
| 232 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
| 233 |
+
)
|
| 234 |
+
validation_split_percentage: Optional[int] = field(
|
| 235 |
+
default=2,
|
| 236 |
+
metadata={
|
| 237 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
| 238 |
+
},
|
| 239 |
+
)
|
| 240 |
+
max_seq_length: Optional[int] = field(
|
| 241 |
+
default=None,
|
| 242 |
+
metadata={
|
| 243 |
+
"help": (
|
| 244 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 245 |
+
"than this will be truncated. Default to the max input length of the model."
|
| 246 |
+
)
|
| 247 |
+
},
|
| 248 |
+
)
|
| 249 |
+
preprocessing_num_workers: Optional[int] = field(
|
| 250 |
+
default=None,
|
| 251 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
| 252 |
+
)
|
| 253 |
+
mlm_probability: float = field(
|
| 254 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
|
| 255 |
+
)
|
| 256 |
+
pad_to_max_length: bool = field(
|
| 257 |
+
default=False,
|
| 258 |
+
metadata={
|
| 259 |
+
"help": (
|
| 260 |
+
"Whether to pad all samples to `max_seq_length`. "
|
| 261 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
| 262 |
+
)
|
| 263 |
+
},
|
| 264 |
+
)
|
| 265 |
+
line_by_line: bool = field(
|
| 266 |
+
default=False,
|
| 267 |
+
metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
def __post_init__(self):
|
| 271 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
| 272 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
| 273 |
+
else:
|
| 274 |
+
if self.train_file is not None:
|
| 275 |
+
extension = self.train_file.split(".")[-1]
|
| 276 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
|
| 277 |
+
if self.validation_file is not None:
|
| 278 |
+
extension = self.validation_file.split(".")[-1]
|
| 279 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@flax.struct.dataclass
|
| 283 |
+
class FlaxDataCollatorForLanguageModeling:
|
| 284 |
+
"""
|
| 285 |
+
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
|
| 286 |
+
are not all of the same length.
|
| 287 |
+
Args:
|
| 288 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
| 289 |
+
The tokenizer used for encoding the data.
|
| 290 |
+
mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
|
| 291 |
+
The probability with which to (randomly) mask tokens in the input.
|
| 292 |
+
.. note::
|
| 293 |
+
For best performance, this data collator should be used with a dataset having items that are dictionaries or
|
| 294 |
+
BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
|
| 295 |
+
:class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
|
| 296 |
+
argument :obj:`return_special_tokens_mask=True`.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
tokenizer: PreTrainedTokenizerBase
|
| 300 |
+
mlm_probability: float = 0.15
|
| 301 |
+
|
| 302 |
+
def __post_init__(self):
|
| 303 |
+
if self.tokenizer.mask_token is None:
|
| 304 |
+
raise ValueError(
|
| 305 |
+
"This tokenizer does not have a mask token which is necessary for masked language modeling. "
|
| 306 |
+
"You should pass `mlm=False` to train on causal language modeling instead."
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
|
| 310 |
+
# Handle dict or lists with proper padding and conversion to tensor.
|
| 311 |
+
batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
|
| 312 |
+
|
| 313 |
+
# If special token mask has been preprocessed, pop it from the dict.
|
| 314 |
+
special_tokens_mask = batch.pop("special_tokens_mask", None)
|
| 315 |
+
|
| 316 |
+
batch["input_ids"], batch["labels"] = self.mask_tokens(
|
| 317 |
+
batch["input_ids"], special_tokens_mask=special_tokens_mask
|
| 318 |
+
)
|
| 319 |
+
return batch
|
| 320 |
+
|
| 321 |
+
def mask_tokens(
|
| 322 |
+
self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
|
| 323 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 324 |
+
"""
|
| 325 |
+
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
|
| 326 |
+
"""
|
| 327 |
+
labels = inputs.copy()
|
| 328 |
+
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
|
| 329 |
+
probability_matrix = np.full(labels.shape, self.mlm_probability)
|
| 330 |
+
special_tokens_mask = special_tokens_mask.astype("bool")
|
| 331 |
+
|
| 332 |
+
probability_matrix[special_tokens_mask] = 0.0
|
| 333 |
+
masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
|
| 334 |
+
labels[~masked_indices] = -100 # We only compute loss on masked tokens
|
| 335 |
+
|
| 336 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
| 337 |
+
indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
|
| 338 |
+
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
|
| 339 |
+
|
| 340 |
+
# 10% of the time, we replace masked input tokens with random word
|
| 341 |
+
indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
|
| 342 |
+
indices_random &= masked_indices & ~indices_replaced
|
| 343 |
+
|
| 344 |
+
random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
|
| 345 |
+
inputs[indices_random] = random_words[indices_random]
|
| 346 |
+
|
| 347 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
| 348 |
+
return inputs, labels
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def generate_batch_splits(samples_idx: np.ndarray, batch_size: int, drop_last=True) -> np.ndarray:
|
| 352 |
+
"""Generate batches of data for a specified batch size from sample indices. If the dataset size is not divisible by
|
| 353 |
+
the batch size and `drop_last` is `True`, the last incomplete batch is dropped. Else, it is returned."""
|
| 354 |
+
num_samples = len(samples_idx)
|
| 355 |
+
if drop_last:
|
| 356 |
+
samples_to_remove = num_samples % batch_size
|
| 357 |
+
if samples_to_remove != 0:
|
| 358 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
| 359 |
+
sections_split = num_samples // batch_size
|
| 360 |
+
samples_idx = samples_idx.reshape((sections_split, batch_size))
|
| 361 |
+
else:
|
| 362 |
+
sections_split = math.ceil(num_samples / batch_size)
|
| 363 |
+
samples_idx = np.array_split(samples_idx, sections_split)
|
| 364 |
+
return samples_idx
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
| 368 |
+
summary_writer.scalar("train_time", train_time, step)
|
| 369 |
+
|
| 370 |
+
train_metrics = get_metrics(train_metrics)
|
| 371 |
+
for key, vals in train_metrics.items():
|
| 372 |
+
tag = f"train_{key}"
|
| 373 |
+
for i, val in enumerate(vals):
|
| 374 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
| 378 |
+
for metric_name, value in eval_metrics.items():
|
| 379 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
| 380 |
+
|
| 381 |
+
def mb_item(x):
|
| 382 |
+
return x.item() if hasattr(x, "item") else x
|
| 383 |
+
|
| 384 |
+
def save_model_checkpoint(
|
| 385 |
+
model,
|
| 386 |
+
save_dir,
|
| 387 |
+
state,
|
| 388 |
+
logger,
|
| 389 |
+
organization,
|
| 390 |
+
with_opt: bool = False,
|
| 391 |
+
push_to_hub: bool = False,
|
| 392 |
+
overwrite=False,
|
| 393 |
+
**kwargs,
|
| 394 |
+
):
|
| 395 |
+
state = jax_utils.unreplicate(state)
|
| 396 |
+
logger.info(f"Saving Checkpoint in {save_dir}")
|
| 397 |
+
ckpt_save_dir = f"{save_dir}/ckpt-{mb_item(state.step)-1}"
|
| 398 |
+
if os.path.exists(ckpt_save_dir) and not overwrite:
|
| 399 |
+
logger.info("checkpoint exists, skipping overwrite")
|
| 400 |
+
else:
|
| 401 |
+
model.save_pretrained(
|
| 402 |
+
ckpt_save_dir, params=state.params, push_to_hub=False, **kwargs
|
| 403 |
+
)
|
| 404 |
+
if with_opt:
|
| 405 |
+
with open(os.path.join(ckpt_save_dir, "opt_state.msgpack"), "wb") as f:
|
| 406 |
+
f.write(to_bytes(state.opt_state))
|
| 407 |
+
with open(os.path.join(ckpt_save_dir, "training_state.json"), "w") as f:
|
| 408 |
+
json.dump({"step": state.step.item()}, f)
|
| 409 |
+
|
| 410 |
+
logger.info("checkpoint saved")
|
| 411 |
+
|
| 412 |
+
if push_to_hub:
|
| 413 |
+
repo_name = Path(save_dir).name
|
| 414 |
+
repo_url = PushToHubMixin._get_repo_url_from_name(
|
| 415 |
+
repo_name, organization=organization, private=False, use_auth_token=True
|
| 416 |
+
)
|
| 417 |
+
repo = PushToHubMixin._create_or_get_repo(
|
| 418 |
+
save_dir,
|
| 419 |
+
repo_url=repo_url,
|
| 420 |
+
organization=organization,
|
| 421 |
+
use_auth_token=True,
|
| 422 |
+
)
|
| 423 |
+
commit_message = f"Saving weights and logs at step {mb_item(state.step)-1}"
|
| 424 |
+
url = PushToHubMixin._push_to_hub(repo=repo, commit_message=commit_message)
|
| 425 |
+
logger.info(f"Model pushed to the hub in this commit: {url}")
|
| 426 |
+
|
| 427 |
+
def restore_model_checkpoint(save_dir, state, logger):
|
| 428 |
+
logger.info(f"Restoring checkpoint from {save_dir}.")
|
| 429 |
+
with open(os.path.join(save_dir, "flax_model.msgpack"), "rb") as f:
|
| 430 |
+
params = from_bytes(state.params, f.read())
|
| 431 |
+
|
| 432 |
+
with open(os.path.join(save_dir, "opt_state.msgpack"), "rb") as f:
|
| 433 |
+
opt_state = from_bytes(state.opt_state, f.read())
|
| 434 |
+
|
| 435 |
+
with open(os.path.join(save_dir, "training_state.json"), "r") as f:
|
| 436 |
+
training_state = json.load(f)
|
| 437 |
+
step = training_state["step"]
|
| 438 |
+
|
| 439 |
+
logger.info("checkpoint restored")
|
| 440 |
+
# return state.replace(step=step, params=params, opt_state=opt_state), step
|
| 441 |
+
return params, opt_state, step
|
| 442 |
+
|
| 443 |
+
def rotate_checkpoints(ckpt_dir: str, save_total_limit: int, logger):
|
| 444 |
+
"Removes older checkpoints so that `save_total_limit` checkpoints are kept"
|
| 445 |
+
# TODO: what to remove is decided using step number only, we might want to improve that
|
| 446 |
+
ckpts = [str(x) for x in Path(ckpt_dir).glob("ckpt-*")]
|
| 447 |
+
# sort checkpoints by step
|
| 448 |
+
ckpts_sorted = sorted(ckpts, key=lambda x: int(x.split("-")[-1]))
|
| 449 |
+
ckpts_to_delete = ckpts_sorted[:-save_total_limit]
|
| 450 |
+
for ckpt in ckpts_to_delete:
|
| 451 |
+
logger.info(
|
| 452 |
+
f"Deleting older checkpoint [{ckpt}] due to save_total_limit ({save_total_limit})"
|
| 453 |
+
)
|
| 454 |
+
shutil.rmtree(ckpt)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def main():
|
| 458 |
+
# See all possible arguments in src/transformers/training_args.py
|
| 459 |
+
# or by passing the --help flag to this script.
|
| 460 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
| 461 |
+
|
| 462 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
| 463 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
| 464 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
| 465 |
+
# let's parse it to get our arguments.
|
| 466 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
| 467 |
+
else:
|
| 468 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
| 469 |
+
|
| 470 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
| 471 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
| 472 |
+
send_example_telemetry("run_mlm", model_args, data_args, framework="flax")
|
| 473 |
+
|
| 474 |
+
if (
|
| 475 |
+
os.path.exists(training_args.output_dir)
|
| 476 |
+
and os.listdir(training_args.output_dir)
|
| 477 |
+
and training_args.do_train
|
| 478 |
+
and not training_args.overwrite_output_dir
|
| 479 |
+
):
|
| 480 |
+
raise ValueError(
|
| 481 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
| 482 |
+
"Use --overwrite_output_dir to overcome."
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
# Setup logging
|
| 486 |
+
logging.basicConfig(
|
| 487 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 488 |
+
level=logging.INFO,
|
| 489 |
+
datefmt="[%X]",
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
# Log on each process the small summary:
|
| 493 |
+
logger = logging.getLogger(__name__)
|
| 494 |
+
|
| 495 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
| 496 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
| 497 |
+
|
| 498 |
+
# Set seed before initializing model.
|
| 499 |
+
set_seed(training_args.seed)
|
| 500 |
+
|
| 501 |
+
# Handle the repository creation
|
| 502 |
+
if training_args.push_to_hub:
|
| 503 |
+
if training_args.hub_model_id is None:
|
| 504 |
+
repo_name = get_full_repo_name(
|
| 505 |
+
Path(training_args.output_dir).absolute().name, token=training_args.hub_token
|
| 506 |
+
)
|
| 507 |
+
else:
|
| 508 |
+
repo_name = training_args.hub_model_id
|
| 509 |
+
repo = Repository(training_args.output_dir, clone_from=repo_name)
|
| 510 |
+
|
| 511 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
| 512 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
| 513 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
| 514 |
+
#
|
| 515 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
| 516 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
| 517 |
+
#
|
| 518 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
| 519 |
+
# download the dataset.
|
| 520 |
+
if data_args.dataset_name is not None:
|
| 521 |
+
# Downloading and loading a dataset from the hub.
|
| 522 |
+
datasets = load_dataset(
|
| 523 |
+
data_args.dataset_name,
|
| 524 |
+
data_args.dataset_config_name,
|
| 525 |
+
cache_dir=model_args.cache_dir,
|
| 526 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
if "validation" not in datasets.keys():
|
| 530 |
+
print('use validated percen')
|
| 531 |
+
datasets["validation"] = load_dataset(
|
| 532 |
+
data_args.dataset_name,
|
| 533 |
+
data_args.dataset_config_name,
|
| 534 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
| 535 |
+
cache_dir=model_args.cache_dir,
|
| 536 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 537 |
+
)
|
| 538 |
+
datasets["train"] = load_dataset(
|
| 539 |
+
data_args.dataset_name,
|
| 540 |
+
data_args.dataset_config_name,
|
| 541 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
| 542 |
+
cache_dir=model_args.cache_dir,
|
| 543 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 544 |
+
)
|
| 545 |
+
else:
|
| 546 |
+
data_files = {}
|
| 547 |
+
if data_args.train_file is not None:
|
| 548 |
+
data_files["train"] = data_args.train_file
|
| 549 |
+
if data_args.validation_file is not None:
|
| 550 |
+
data_files["validation"] = data_args.validation_file
|
| 551 |
+
extension = data_args.train_file.split(".")[-1]
|
| 552 |
+
if extension == "txt":
|
| 553 |
+
extension = "text"
|
| 554 |
+
datasets = load_dataset(
|
| 555 |
+
extension,
|
| 556 |
+
data_files=data_files,
|
| 557 |
+
cache_dir=model_args.cache_dir,
|
| 558 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
if "validation" not in datasets.keys():
|
| 562 |
+
datasets["validation"] = load_dataset(
|
| 563 |
+
extension,
|
| 564 |
+
data_files=data_files,
|
| 565 |
+
split=f"train[:{data_args.validation_split_percentage}%]",
|
| 566 |
+
cache_dir=model_args.cache_dir,
|
| 567 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 568 |
+
)
|
| 569 |
+
datasets["train"] = load_dataset(
|
| 570 |
+
extension,
|
| 571 |
+
data_files=data_files,
|
| 572 |
+
split=f"train[{data_args.validation_split_percentage}%:]",
|
| 573 |
+
cache_dir=model_args.cache_dir,
|
| 574 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 575 |
+
)
|
| 576 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
| 577 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
| 578 |
+
|
| 579 |
+
# Load pretrained model and tokenizer
|
| 580 |
+
|
| 581 |
+
# Distributed training:
|
| 582 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
| 583 |
+
# download model & vocab.
|
| 584 |
+
print("total len train",len(datasets["train"]))
|
| 585 |
+
print("total len valida",len(datasets["validation"]))
|
| 586 |
+
if model_args.config_name:
|
| 587 |
+
config = AutoConfig.from_pretrained(
|
| 588 |
+
model_args.config_name,
|
| 589 |
+
cache_dir=model_args.cache_dir,
|
| 590 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 591 |
+
)
|
| 592 |
+
elif model_args.model_name_or_path:
|
| 593 |
+
config = AutoConfig.from_pretrained(
|
| 594 |
+
model_args.model_name_or_path,
|
| 595 |
+
cache_dir=model_args.cache_dir,
|
| 596 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 597 |
+
)
|
| 598 |
+
else:
|
| 599 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
| 600 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
| 601 |
+
|
| 602 |
+
if model_args.tokenizer_name:
|
| 603 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 604 |
+
model_args.tokenizer_name,
|
| 605 |
+
cache_dir=model_args.cache_dir,
|
| 606 |
+
use_fast=model_args.use_fast_tokenizer,
|
| 607 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 608 |
+
)
|
| 609 |
+
elif model_args.model_name_or_path:
|
| 610 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 611 |
+
model_args.model_name_or_path,
|
| 612 |
+
cache_dir=model_args.cache_dir,
|
| 613 |
+
use_fast=model_args.use_fast_tokenizer,
|
| 614 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 615 |
+
)
|
| 616 |
+
else:
|
| 617 |
+
raise ValueError(
|
| 618 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
| 619 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
# Preprocessing the datasets.
|
| 623 |
+
# First we tokenize all the texts.
|
| 624 |
+
if training_args.do_train:
|
| 625 |
+
column_names = datasets["train"].column_names
|
| 626 |
+
else:
|
| 627 |
+
column_names = datasets["validation"].column_names
|
| 628 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
| 629 |
+
|
| 630 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
| 631 |
+
|
| 632 |
+
if data_args.line_by_line:
|
| 633 |
+
# When using line_by_line, we just tokenize each nonempty line.
|
| 634 |
+
padding = "max_length" if data_args.pad_to_max_length else False
|
| 635 |
+
|
| 636 |
+
def tokenize_function(examples):
|
| 637 |
+
# Remove empty lines
|
| 638 |
+
examples = [line for line in examples if len(line) > 0 and not line.isspace()]
|
| 639 |
+
return tokenizer(
|
| 640 |
+
examples,
|
| 641 |
+
return_special_tokens_mask=True,
|
| 642 |
+
padding=padding,
|
| 643 |
+
truncation=True,
|
| 644 |
+
max_length=max_seq_length,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
tokenized_datasets = datasets.map(
|
| 648 |
+
tokenize_function,
|
| 649 |
+
input_columns=[text_column_name],
|
| 650 |
+
batched=True,
|
| 651 |
+
num_proc=data_args.preprocessing_num_workers,
|
| 652 |
+
remove_columns=column_names,
|
| 653 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
else:
|
| 657 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
| 658 |
+
# We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
|
| 659 |
+
# efficient when it receives the `special_tokens_mask`.
|
| 660 |
+
def tokenize_function(examples):
|
| 661 |
+
return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
|
| 662 |
+
|
| 663 |
+
tokenized_datasets = datasets.map(
|
| 664 |
+
tokenize_function,
|
| 665 |
+
batched=True,
|
| 666 |
+
num_proc=data_args.preprocessing_num_workers,
|
| 667 |
+
remove_columns=column_names,
|
| 668 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of
|
| 672 |
+
# max_seq_length.
|
| 673 |
+
def group_texts(examples):
|
| 674 |
+
# Concatenate all texts.
|
| 675 |
+
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
|
| 676 |
+
total_length = len(concatenated_examples[list(examples.keys())[0]])
|
| 677 |
+
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
|
| 678 |
+
# customize this part to your needs.
|
| 679 |
+
if total_length >= max_seq_length:
|
| 680 |
+
total_length = (total_length // max_seq_length) * max_seq_length
|
| 681 |
+
# Split by chunks of max_len.
|
| 682 |
+
result = {
|
| 683 |
+
k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
|
| 684 |
+
for k, t in concatenated_examples.items()
|
| 685 |
+
}
|
| 686 |
+
return result
|
| 687 |
+
|
| 688 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
|
| 689 |
+
# remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
|
| 690 |
+
# might be slower to preprocess.
|
| 691 |
+
#
|
| 692 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
| 693 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
|
| 694 |
+
tokenized_datasets = tokenized_datasets.map(
|
| 695 |
+
group_texts,
|
| 696 |
+
batched=True,
|
| 697 |
+
num_proc=data_args.preprocessing_num_workers,
|
| 698 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
# Enable tensorboard only on the master node
|
| 702 |
+
has_tensorboard = is_tensorboard_available()
|
| 703 |
+
if has_tensorboard and jax.process_index() == 0:
|
| 704 |
+
try:
|
| 705 |
+
from flax.metrics.tensorboard import SummaryWriter
|
| 706 |
+
import wandb
|
| 707 |
+
wandb.init(
|
| 708 |
+
entity='munggok',
|
| 709 |
+
project='roberta-indo-base',
|
| 710 |
+
sync_tensorboard=True,
|
| 711 |
+
)
|
| 712 |
+
wandb.config.update(training_args)
|
| 713 |
+
wandb.config.update(model_args)
|
| 714 |
+
wandb.config.update(data_args)
|
| 715 |
+
|
| 716 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
| 717 |
+
except ImportError as ie:
|
| 718 |
+
has_tensorboard = False
|
| 719 |
+
logger.warning(
|
| 720 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
| 721 |
+
)
|
| 722 |
+
else:
|
| 723 |
+
logger.warning(
|
| 724 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
| 725 |
+
"Please run pip install tensorboard to enable."
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Data collator
|
| 729 |
+
# This one will take care of randomly masking the tokens.
|
| 730 |
+
data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
|
| 731 |
+
|
| 732 |
+
# Initialize our training
|
| 733 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
| 734 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
| 735 |
+
|
| 736 |
+
if model_args.model_name_or_path:
|
| 737 |
+
model = FlaxAutoModelForMaskedLM.from_pretrained(
|
| 738 |
+
model_args.model_name_or_path,
|
| 739 |
+
config=config,
|
| 740 |
+
seed=training_args.seed,
|
| 741 |
+
dtype=getattr(jnp, model_args.dtype),
|
| 742 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
| 743 |
+
)
|
| 744 |
+
else:
|
| 745 |
+
model = FlaxAutoModelForMaskedLM.from_config(
|
| 746 |
+
config,
|
| 747 |
+
seed=training_args.seed,
|
| 748 |
+
dtype=getattr(jnp, model_args.dtype),
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
if training_args.gradient_checkpointing:
|
| 752 |
+
model.enable_gradient_checkpointing()
|
| 753 |
+
|
| 754 |
+
# Store some constant
|
| 755 |
+
num_epochs = int(training_args.num_train_epochs)
|
| 756 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
| 757 |
+
per_device_eval_batch_size = int(training_args.per_device_eval_batch_size)
|
| 758 |
+
eval_batch_size = per_device_eval_batch_size * jax.device_count()
|
| 759 |
+
|
| 760 |
+
num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
|
| 761 |
+
|
| 762 |
+
# Create learning rate schedule
|
| 763 |
+
warmup_fn = optax.linear_schedule(
|
| 764 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
| 765 |
+
)
|
| 766 |
+
decay_fn = optax.linear_schedule(
|
| 767 |
+
init_value=training_args.learning_rate,
|
| 768 |
+
end_value=0,
|
| 769 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
| 770 |
+
)
|
| 771 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
| 772 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
| 776 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
| 777 |
+
# mask boolean with the same structure as the parameters.
|
| 778 |
+
# The mask is True for parameters that should be decayed.
|
| 779 |
+
def decay_mask_fn(params):
|
| 780 |
+
flat_params = traverse_util.flatten_dict(params)
|
| 781 |
+
# find out all LayerNorm parameters
|
| 782 |
+
layer_norm_candidates = ["layernorm", "layer_norm", "ln"]
|
| 783 |
+
layer_norm_named_params = set(
|
| 784 |
+
[
|
| 785 |
+
layer[-2:]
|
| 786 |
+
for layer_norm_name in layer_norm_candidates
|
| 787 |
+
for layer in flat_params.keys()
|
| 788 |
+
if layer_norm_name in "".join(layer).lower()
|
| 789 |
+
]
|
| 790 |
+
)
|
| 791 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] not in layer_norm_named_params) for path in flat_params}
|
| 792 |
+
return traverse_util.unflatten_dict(flat_mask)
|
| 793 |
+
|
| 794 |
+
# create adam optimizer
|
| 795 |
+
if training_args.adafactor:
|
| 796 |
+
# We use the default parameters here to initialize adafactor,
|
| 797 |
+
# For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
|
| 798 |
+
optimizer = optax.adafactor(
|
| 799 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
| 800 |
+
)
|
| 801 |
+
else:
|
| 802 |
+
optimizer = optax.adamw(
|
| 803 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
| 804 |
+
b1=training_args.adam_beta1,
|
| 805 |
+
b2=training_args.adam_beta2,
|
| 806 |
+
eps=training_args.adam_epsilon,
|
| 807 |
+
weight_decay=training_args.weight_decay,
|
| 808 |
+
mask=decay_mask_fn,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
# Setup train state
|
| 812 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
|
| 813 |
+
|
| 814 |
+
# Define gradient update step fn
|
| 815 |
+
def train_step(state, batch, dropout_rng):
|
| 816 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
| 817 |
+
|
| 818 |
+
def loss_fn(params):
|
| 819 |
+
labels = batch.pop("labels")
|
| 820 |
+
|
| 821 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
| 822 |
+
|
| 823 |
+
# compute loss, ignore padded input tokens
|
| 824 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
| 825 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
| 826 |
+
|
| 827 |
+
# take average
|
| 828 |
+
loss = loss.sum() / label_mask.sum()
|
| 829 |
+
|
| 830 |
+
return loss
|
| 831 |
+
|
| 832 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
| 833 |
+
loss, grad = grad_fn(state.params)
|
| 834 |
+
grad = jax.lax.pmean(grad, "batch")
|
| 835 |
+
new_state = state.apply_gradients(grads=grad)
|
| 836 |
+
|
| 837 |
+
metrics = jax.lax.pmean(
|
| 838 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
return new_state, metrics, new_dropout_rng
|
| 842 |
+
|
| 843 |
+
# Create parallel version of the train step
|
| 844 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
| 845 |
+
|
| 846 |
+
# Define eval fn
|
| 847 |
+
def eval_step(params, batch):
|
| 848 |
+
labels = batch.pop("labels")
|
| 849 |
+
|
| 850 |
+
logits = model(**batch, params=params, train=False)[0]
|
| 851 |
+
|
| 852 |
+
# compute loss, ignore padded input tokens
|
| 853 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
| 854 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
| 855 |
+
|
| 856 |
+
# compute accuracy
|
| 857 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
|
| 858 |
+
|
| 859 |
+
# summarize metrics
|
| 860 |
+
metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
|
| 861 |
+
metrics = jax.lax.psum(metrics, axis_name="batch")
|
| 862 |
+
|
| 863 |
+
return metrics
|
| 864 |
+
|
| 865 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
| 866 |
+
|
| 867 |
+
# Replicate the train state on each device
|
| 868 |
+
state = jax_utils.replicate(state)
|
| 869 |
+
|
| 870 |
+
train_time = 0
|
| 871 |
+
epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
|
| 872 |
+
for epoch in epochs:
|
| 873 |
+
# ======================== Training ================================
|
| 874 |
+
train_start = time.time()
|
| 875 |
+
train_metrics = []
|
| 876 |
+
|
| 877 |
+
# Create sampling rng
|
| 878 |
+
rng, input_rng = jax.random.split(rng)
|
| 879 |
+
|
| 880 |
+
# Generate an epoch by shuffling sampling indices from the train dataset
|
| 881 |
+
num_train_samples = len(tokenized_datasets["train"])
|
| 882 |
+
# Avoid using jax.numpy here in case of TPU training
|
| 883 |
+
train_samples_idx = np.random.permutation(np.arange(num_train_samples))
|
| 884 |
+
train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
|
| 885 |
+
|
| 886 |
+
# Gather the indexes for creating the batch and do a training step
|
| 887 |
+
for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
|
| 888 |
+
samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
|
| 889 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
| 890 |
+
|
| 891 |
+
# Model forward
|
| 892 |
+
model_inputs = shard(model_inputs.data)
|
| 893 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
| 894 |
+
train_metrics.append(train_metric)
|
| 895 |
+
|
| 896 |
+
cur_step = epoch * (num_train_samples // train_batch_size) + step
|
| 897 |
+
|
| 898 |
+
if cur_step % training_args.logging_steps == 0 and cur_step > 0:
|
| 899 |
+
# Save metrics
|
| 900 |
+
train_metric = jax_utils.unreplicate(train_metric)
|
| 901 |
+
train_time += time.time() - train_start
|
| 902 |
+
if has_tensorboard and jax.process_index() == 0:
|
| 903 |
+
write_train_metric(summary_writer, train_metrics, train_time, cur_step)
|
| 904 |
+
|
| 905 |
+
epochs.write(
|
| 906 |
+
f"Step... ({cur_step} | Loss: {train_metric['loss']}, Learning Rate:"
|
| 907 |
+
f" {train_metric['learning_rate']})"
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
train_metrics = []
|
| 911 |
+
|
| 912 |
+
if cur_step % training_args.eval_steps == 0 and cur_step > 0:
|
| 913 |
+
# ======================== Evaluating ==============================
|
| 914 |
+
num_eval_samples = len(tokenized_datasets["validation"])
|
| 915 |
+
# Avoid using jax.numpy here in case of TPU training
|
| 916 |
+
eval_samples_idx = np.arange(num_eval_samples)
|
| 917 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size, drop_last=False)
|
| 918 |
+
|
| 919 |
+
eval_metrics = []
|
| 920 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
|
| 921 |
+
samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
|
| 922 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
| 923 |
+
|
| 924 |
+
# Model forward
|
| 925 |
+
metrics = pad_shard_unpad(p_eval_step, static_return=True)(
|
| 926 |
+
state.params, model_inputs.data, min_device_batch=per_device_eval_batch_size
|
| 927 |
+
)
|
| 928 |
+
eval_metrics.append(metrics)
|
| 929 |
+
|
| 930 |
+
# normalize eval metrics
|
| 931 |
+
eval_metrics = get_metrics(eval_metrics)
|
| 932 |
+
eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
|
| 933 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
| 934 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
| 935 |
+
|
| 936 |
+
# Update progress bar
|
| 937 |
+
epochs.desc = f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
|
| 938 |
+
|
| 939 |
+
# Save metrics
|
| 940 |
+
if has_tensorboard and jax.process_index() == 0:
|
| 941 |
+
write_eval_metric(summary_writer, eval_metrics, cur_step)
|
| 942 |
+
|
| 943 |
+
if cur_step % training_args.save_steps == 0 and cur_step > 0:
|
| 944 |
+
# save checkpoint after each epoch and push checkpoint to the hub
|
| 945 |
+
if jax.process_index() == 0:
|
| 946 |
+
save_model_checkpoint(
|
| 947 |
+
model,
|
| 948 |
+
training_args.output_dir,
|
| 949 |
+
state,
|
| 950 |
+
logger,
|
| 951 |
+
False,
|
| 952 |
+
with_opt=True,
|
| 953 |
+
push_to_hub=training_args.push_to_hub,
|
| 954 |
+
overwrite=True,
|
| 955 |
+
)
|
| 956 |
+
if training_args.save_total_limit is not None:
|
| 957 |
+
rotate_checkpoints(
|
| 958 |
+
training_args.output_dir,
|
| 959 |
+
training_args.save_total_limit,
|
| 960 |
+
logger,
|
| 961 |
+
)
|
| 962 |
+
if training_args.push_to_hub:
|
| 963 |
+
repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False)
|
| 964 |
+
|
| 965 |
+
# Eval after training
|
| 966 |
+
if training_args.do_eval:
|
| 967 |
+
num_eval_samples = len(tokenized_datasets["validation"])
|
| 968 |
+
# Avoid using jax.numpy here in case of TPU training
|
| 969 |
+
eval_samples_idx = np.arange(num_eval_samples)
|
| 970 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size, drop_last=False)
|
| 971 |
+
|
| 972 |
+
eval_metrics = []
|
| 973 |
+
for _, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
|
| 974 |
+
samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
|
| 975 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
| 976 |
+
|
| 977 |
+
# Model forward
|
| 978 |
+
metrics = pad_shard_unpad(p_eval_step, static_return=True)(
|
| 979 |
+
state.params, model_inputs.data, min_device_batch=per_device_eval_batch_size
|
| 980 |
+
)
|
| 981 |
+
eval_metrics.append(metrics)
|
| 982 |
+
|
| 983 |
+
# normalize eval metrics
|
| 984 |
+
eval_metrics = get_metrics(eval_metrics)
|
| 985 |
+
eval_metrics = jax.tree_map(lambda metric: jnp.sum(metric).item(), eval_metrics)
|
| 986 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
| 987 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
| 988 |
+
|
| 989 |
+
try:
|
| 990 |
+
perplexity = math.exp(eval_metrics["loss"])
|
| 991 |
+
except OverflowError:
|
| 992 |
+
perplexity = float("inf")
|
| 993 |
+
eval_metrics["perplexity"] = perplexity
|
| 994 |
+
|
| 995 |
+
if jax.process_index() == 0:
|
| 996 |
+
eval_metrics = {f"eval_{metric_name}": value for metric_name, value in eval_metrics.items()}
|
| 997 |
+
path = os.path.join(training_args.output_dir, "eval_results.json")
|
| 998 |
+
with open(path, "w") as f:
|
| 999 |
+
json.dump(eval_metrics, f, indent=4, sort_keys=True)
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
if __name__ == "__main__":
|
| 1003 |
+
main()
|
run_mlm_flax_stream.py
ADDED
|
@@ -0,0 +1,825 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 tempfile
|
| 29 |
+
import time
|
| 30 |
+
from collections import defaultdict
|
| 31 |
+
from dataclasses import dataclass, field
|
| 32 |
+
|
| 33 |
+
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
|
| 34 |
+
import joblib
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from typing import Dict, List, Optional, Tuple
|
| 37 |
+
|
| 38 |
+
import datasets
|
| 39 |
+
import numpy as np
|
| 40 |
+
from datasets import load_dataset
|
| 41 |
+
from tqdm import tqdm
|
| 42 |
+
|
| 43 |
+
import flax
|
| 44 |
+
import jax
|
| 45 |
+
import jax.numpy as jnp
|
| 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 |
+
FlaxRobertaForMaskedLM,
|
| 64 |
+
RobertaForMaskedLM,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if datasets.__version__ <= "1.8.0":
|
| 69 |
+
raise ValueError("Make sure to upgrade `datasets` to a version >= 1.9.0 to use dataset streaming")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
|
| 73 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class ModelArguments:
|
| 78 |
+
"""
|
| 79 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
model_name_or_path: Optional[str] = field(
|
| 83 |
+
default=None,
|
| 84 |
+
metadata={
|
| 85 |
+
"help": "The model checkpoint for weights initialization."
|
| 86 |
+
"Don't set if you want to train a model from scratch."
|
| 87 |
+
},
|
| 88 |
+
)
|
| 89 |
+
model_type: Optional[str] = field(
|
| 90 |
+
default=None,
|
| 91 |
+
metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
|
| 92 |
+
)
|
| 93 |
+
config_name: Optional[str] = field(
|
| 94 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
| 95 |
+
)
|
| 96 |
+
tokenizer_name: Optional[str] = field(
|
| 97 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
| 98 |
+
)
|
| 99 |
+
cache_dir: Optional[str] = field(
|
| 100 |
+
default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
|
| 101 |
+
)
|
| 102 |
+
use_fast_tokenizer: bool = field(
|
| 103 |
+
default=True,
|
| 104 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
| 105 |
+
)
|
| 106 |
+
dtype: Optional[str] = field(
|
| 107 |
+
default="float32",
|
| 108 |
+
metadata={
|
| 109 |
+
"help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
|
| 110 |
+
},
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
@dataclass
|
| 114 |
+
class DataTrainingArguments:
|
| 115 |
+
"""
|
| 116 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
dataset_name: Optional[str] = field(
|
| 120 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
| 121 |
+
)
|
| 122 |
+
dataset_config_name: Optional[str] = field(
|
| 123 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
| 124 |
+
)
|
| 125 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
| 126 |
+
validation_file: Optional[str] = field(
|
| 127 |
+
default=None,
|
| 128 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
| 129 |
+
)
|
| 130 |
+
train_ref_file: Optional[str] = field(
|
| 131 |
+
default=None,
|
| 132 |
+
metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
|
| 133 |
+
)
|
| 134 |
+
validation_ref_file: Optional[str] = field(
|
| 135 |
+
default=None,
|
| 136 |
+
metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
|
| 137 |
+
)
|
| 138 |
+
overwrite_cache: bool = field(
|
| 139 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
| 140 |
+
)
|
| 141 |
+
validation_split_percentage: Optional[int] = field(
|
| 142 |
+
default=5,
|
| 143 |
+
metadata={
|
| 144 |
+
"help": "The percentage of the train set used as validation set in case there's no validation split"
|
| 145 |
+
},
|
| 146 |
+
)
|
| 147 |
+
max_seq_length: Optional[int] = field(
|
| 148 |
+
default=None,
|
| 149 |
+
metadata={
|
| 150 |
+
"help": "The maximum total input sequence length after tokenization. Sequences longer "
|
| 151 |
+
"than this will be truncated. Default to the max input length of the model."
|
| 152 |
+
},
|
| 153 |
+
)
|
| 154 |
+
preprocessing_num_workers: Optional[int] = field(
|
| 155 |
+
default=None,
|
| 156 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
| 157 |
+
)
|
| 158 |
+
mlm_probability: float = field(
|
| 159 |
+
default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
|
| 160 |
+
)
|
| 161 |
+
pad_to_max_length: bool = field(
|
| 162 |
+
default=False,
|
| 163 |
+
metadata={
|
| 164 |
+
"help": "Whether to pad all samples to `max_seq_length`. "
|
| 165 |
+
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
|
| 166 |
+
},
|
| 167 |
+
)
|
| 168 |
+
line_by_line: bool = field(
|
| 169 |
+
default=False,
|
| 170 |
+
metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
|
| 171 |
+
)
|
| 172 |
+
text_column_name: str = field(
|
| 173 |
+
default="text", metadata={"help": "The name of the column to retrieve the training text."}
|
| 174 |
+
)
|
| 175 |
+
shuffle_buffer_size: int = field(
|
| 176 |
+
default=10000, metadata={"help": "The number of examples to pre-load for shuffling."}
|
| 177 |
+
)
|
| 178 |
+
num_train_steps: int = field(default=50000, metadata={"help": "The number of training steps."})
|
| 179 |
+
num_eval_samples: int = field(default=50000, metadata={"help": "The number of samples to be used for evaluation"})
|
| 180 |
+
|
| 181 |
+
def __post_init__(self):
|
| 182 |
+
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
|
| 183 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
| 184 |
+
else:
|
| 185 |
+
if self.train_file is not None:
|
| 186 |
+
extension = self.train_file.split(".")[-1]
|
| 187 |
+
assert extension in ["csv", "json", "jsonl", "txt", "gz"], "`train_file` should be a csv, a json (lines) or a txt file."
|
| 188 |
+
if self.validation_file is not None:
|
| 189 |
+
extension = self.validation_file.split(".")[-1]
|
| 190 |
+
assert extension in ["csv", "json", "jsonl", "txt", "gz"], "`validation_file` should be a csv, a json (lines) or a txt file."
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@flax.struct.dataclass
|
| 194 |
+
class FlaxDataCollatorForLanguageModeling:
|
| 195 |
+
"""
|
| 196 |
+
Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
|
| 197 |
+
are not all of the same length.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
|
| 201 |
+
The tokenizer used for encoding the data.
|
| 202 |
+
mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
|
| 203 |
+
The probability with which to (randomly) mask tokens in the input.
|
| 204 |
+
|
| 205 |
+
.. note::
|
| 206 |
+
|
| 207 |
+
For best performance, this data collator should be used with a dataset having items that are dictionaries or
|
| 208 |
+
BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
|
| 209 |
+
:class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
|
| 210 |
+
argument :obj:`return_special_tokens_mask=True`.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
tokenizer: PreTrainedTokenizerBase
|
| 214 |
+
mlm_probability: float = 0.15
|
| 215 |
+
|
| 216 |
+
def __post_init__(self):
|
| 217 |
+
if self.tokenizer.mask_token is None:
|
| 218 |
+
raise ValueError(
|
| 219 |
+
"This tokenizer does not have a mask token which is necessary for masked language modeling. "
|
| 220 |
+
"You should pass `mlm=False` to train on causal language modeling instead."
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
|
| 224 |
+
# Handle dict or lists with proper padding and conversion to tensor.
|
| 225 |
+
batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
|
| 226 |
+
|
| 227 |
+
# If special token mask has been preprocessed, pop it from the dict.
|
| 228 |
+
special_tokens_mask = batch.pop("special_tokens_mask", None)
|
| 229 |
+
|
| 230 |
+
batch["input_ids"], batch["labels"] = self.mask_tokens(
|
| 231 |
+
batch["input_ids"], special_tokens_mask=special_tokens_mask
|
| 232 |
+
)
|
| 233 |
+
return batch
|
| 234 |
+
|
| 235 |
+
def mask_tokens(
|
| 236 |
+
self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
|
| 237 |
+
) -> Tuple[jnp.ndarray, jnp.ndarray]:
|
| 238 |
+
"""
|
| 239 |
+
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
|
| 240 |
+
"""
|
| 241 |
+
labels = inputs.copy()
|
| 242 |
+
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
|
| 243 |
+
probability_matrix = np.full(labels.shape, self.mlm_probability)
|
| 244 |
+
special_tokens_mask = special_tokens_mask.astype("bool")
|
| 245 |
+
|
| 246 |
+
probability_matrix[special_tokens_mask] = 0.0
|
| 247 |
+
masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
|
| 248 |
+
labels[~masked_indices] = -100 # We only compute loss on masked tokens
|
| 249 |
+
|
| 250 |
+
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
|
| 251 |
+
indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
|
| 252 |
+
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
|
| 253 |
+
|
| 254 |
+
# 10% of the time, we replace masked input tokens with random word
|
| 255 |
+
indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
|
| 256 |
+
indices_random &= masked_indices & ~indices_replaced
|
| 257 |
+
|
| 258 |
+
random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
|
| 259 |
+
inputs[indices_random] = random_words[indices_random]
|
| 260 |
+
|
| 261 |
+
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
|
| 262 |
+
return inputs, labels
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@dataclass
|
| 266 |
+
class SamplingArguments:
|
| 267 |
+
"""
|
| 268 |
+
Arguments pertaining to how to perform sampling of the dataset.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
perplexity_model: Optional[str] = field(
|
| 272 |
+
default="./es.arpa.bin", metadata={"help": "Path to KenLM model to use to get perplexity values."}
|
| 273 |
+
)
|
| 274 |
+
sampling_method: Optional[str] = field(
|
| 275 |
+
default=None, metadata={"help": "Sample using a 'step' or 'gaussian' perplexity function per document, or 'random'."}
|
| 276 |
+
)
|
| 277 |
+
sampling_factor: Optional[float] = field(
|
| 278 |
+
default=None, metadata={"help": "Sampling factor. Integers for step function, decimals for gaussian."}
|
| 279 |
+
)
|
| 280 |
+
boundaries: Optional[str] = field(
|
| 281 |
+
default="536394.99320948,662247.50212365,919250.87225178", metadata={"help": "Quartile boundaries"}
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def __post_init__(self):
|
| 285 |
+
self.boundaries = [float(q.strip()) for q in self.boundaries.split(",")]
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
|
| 289 |
+
num_samples = len(samples_idx)
|
| 290 |
+
samples_to_remove = num_samples % batch_size
|
| 291 |
+
|
| 292 |
+
if samples_to_remove != 0:
|
| 293 |
+
samples_idx = samples_idx[:-samples_to_remove]
|
| 294 |
+
sections_split = num_samples // batch_size
|
| 295 |
+
batch_idx = np.split(samples_idx, sections_split)
|
| 296 |
+
return batch_idx
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
|
| 300 |
+
"""
|
| 301 |
+
The training iterator is advanced so that after groupifying the samples,
|
| 302 |
+
`num_samples` of length `max_seq_length` are returned.
|
| 303 |
+
"""
|
| 304 |
+
num_total_tokens = max_seq_length * num_samples
|
| 305 |
+
samples = defaultdict(list)
|
| 306 |
+
|
| 307 |
+
i = 0
|
| 308 |
+
while i < num_total_tokens:
|
| 309 |
+
tokenized_samples = next(train_iterator)
|
| 310 |
+
i += len(tokenized_samples["input_ids"])
|
| 311 |
+
|
| 312 |
+
# concatenate tokenized samples to list
|
| 313 |
+
samples = {k: samples[k] + tokenized_samples[k] for k in tokenized_samples.keys()}
|
| 314 |
+
|
| 315 |
+
# Concatenated tokens are split to lists of length `max_seq_length`.
|
| 316 |
+
# Note that remainedr of % max_seq_length are thrown away.
|
| 317 |
+
def group_texts(examples):
|
| 318 |
+
result = {
|
| 319 |
+
k: [t[i : i + max_seq_length] for i in range(0, num_total_tokens, max_seq_length)]
|
| 320 |
+
for k, t in examples.items()
|
| 321 |
+
}
|
| 322 |
+
return result
|
| 323 |
+
|
| 324 |
+
grouped_samples = group_texts(samples)
|
| 325 |
+
return grouped_samples
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def write_train_metric(summary_writer, train_metrics, train_time, step):
|
| 329 |
+
summary_writer.scalar("train_time", train_time, step)
|
| 330 |
+
|
| 331 |
+
train_metrics = get_metrics(train_metrics)
|
| 332 |
+
for key, vals in train_metrics.items():
|
| 333 |
+
tag = f"train_{key}"
|
| 334 |
+
for i, val in enumerate(vals):
|
| 335 |
+
summary_writer.scalar(tag, val, step - len(vals) + i + 1)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def write_eval_metric(summary_writer, eval_metrics, step):
|
| 339 |
+
for metric_name, value in eval_metrics.items():
|
| 340 |
+
summary_writer.scalar(f"eval_{metric_name}", value, step)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def save_checkpoint_files(state, data_collator, training_args, save_dir):
|
| 344 |
+
unreplicated_state = jax_utils.unreplicate(state)
|
| 345 |
+
with open(os.path.join(save_dir, "optimizer_state.msgpack"), "wb") as f:
|
| 346 |
+
f.write(to_bytes(unreplicated_state.opt_state))
|
| 347 |
+
joblib.dump(training_args, os.path.join(save_dir, "training_args.joblib"))
|
| 348 |
+
joblib.dump(data_collator, os.path.join(save_dir, "data_collator.joblib"))
|
| 349 |
+
with open(os.path.join(save_dir, "training_state.json"), "w") as f:
|
| 350 |
+
json.dump({"step": unreplicated_state.step.item()}, f)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def restore_checkpoint(save_dir, state):
|
| 354 |
+
logger.info(f"Restoring checkpoint from {save_dir}")
|
| 355 |
+
with open(os.path.join(save_dir, "flax_model.msgpack"), "rb") as f:
|
| 356 |
+
params = from_bytes(state.params, f.read())
|
| 357 |
+
|
| 358 |
+
with open(os.path.join(save_dir, "optimizer_state.msgpack"), "rb") as f:
|
| 359 |
+
opt_state = from_bytes(state.opt_state, f.read())
|
| 360 |
+
|
| 361 |
+
args = joblib.load(os.path.join(save_dir, "training_args.joblib"))
|
| 362 |
+
data_collator = joblib.load(os.path.join(save_dir, "data_collator.joblib"))
|
| 363 |
+
|
| 364 |
+
with open(os.path.join(save_dir, "training_state.json"), "r") as f:
|
| 365 |
+
training_state = json.load(f)
|
| 366 |
+
step = training_state["step"]
|
| 367 |
+
|
| 368 |
+
return params, opt_state, step, args, data_collator
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def rotate_checkpoints(path, max_checkpoints=5):
|
| 372 |
+
paths = sorted(Path(path).iterdir(), key=os.path.getmtime)[::-1]
|
| 373 |
+
if len(paths) > max_checkpoints:
|
| 374 |
+
for path_to_delete in paths[max_checkpoints:]:
|
| 375 |
+
try:
|
| 376 |
+
shutil.rmtree(path_to_delete)
|
| 377 |
+
except OSError:
|
| 378 |
+
os.remove(path_to_delete)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def to_f32(t):
|
| 382 |
+
return jax.tree_map(lambda x: x.astype(jnp.float32) if x.dtype == jnp.bfloat16 else x, t)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def convert(output_dir, destination_dir="./"):
|
| 386 |
+
shutil.copyfile(Path(output_dir) / "flax_model.msgpack", Path(destination_dir) / "flax_model.msgpack")
|
| 387 |
+
shutil.copyfile(Path(output_dir) / "config.json", Path(destination_dir) / "config.json")
|
| 388 |
+
# Saving extra files from config.json and tokenizer.json files
|
| 389 |
+
tokenizer = AutoTokenizer.from_pretrained(destination_dir)
|
| 390 |
+
tokenizer.save_pretrained(destination_dir)
|
| 391 |
+
|
| 392 |
+
# Temporary saving bfloat16 Flax model into float32
|
| 393 |
+
tmp = tempfile.mkdtemp()
|
| 394 |
+
flax_model = FlaxRobertaForMaskedLM.from_pretrained(destination_dir)
|
| 395 |
+
flax_model.params = to_f32(flax_model.params)
|
| 396 |
+
flax_model.save_pretrained(tmp)
|
| 397 |
+
# Converting float32 Flax to PyTorch
|
| 398 |
+
model = RobertaForMaskedLM.from_pretrained(tmp, from_flax=True)
|
| 399 |
+
model.save_pretrained(destination_dir, save_config=False)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
if __name__ == "__main__":
|
| 403 |
+
# See all possible arguments in src/transformers/training_args.py
|
| 404 |
+
# or by passing the --help flag to this script.
|
| 405 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
| 406 |
+
|
| 407 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, SamplingArguments))
|
| 408 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
| 409 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
| 410 |
+
# let's parse it to get our arguments.
|
| 411 |
+
model_args, data_args, training_args, sampling_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
| 412 |
+
else:
|
| 413 |
+
model_args, data_args, training_args, sampling_args = parser.parse_args_into_dataclasses()
|
| 414 |
+
|
| 415 |
+
if (
|
| 416 |
+
os.path.exists(training_args.output_dir)
|
| 417 |
+
and os.listdir(training_args.output_dir)
|
| 418 |
+
and training_args.do_train
|
| 419 |
+
and not training_args.overwrite_output_dir
|
| 420 |
+
):
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty."
|
| 423 |
+
"Use --overwrite_output_dir to overcome."
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
# Setup logging
|
| 427 |
+
logging.basicConfig(
|
| 428 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 429 |
+
level="INFO",
|
| 430 |
+
datefmt="[%X]",
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# Log on each process the small summary:
|
| 434 |
+
logger = logging.getLogger(__name__)
|
| 435 |
+
logger.warning(
|
| 436 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
| 437 |
+
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
| 441 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
| 442 |
+
|
| 443 |
+
# Set seed before initializing model.
|
| 444 |
+
set_seed(training_args.seed)
|
| 445 |
+
|
| 446 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
| 447 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
| 448 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
| 449 |
+
#
|
| 450 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
| 451 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
| 452 |
+
if data_args.dataset_name is not None:
|
| 453 |
+
# Downloading and loading a dataset from the hub.
|
| 454 |
+
filepaths = {}
|
| 455 |
+
if data_args.train_file:
|
| 456 |
+
filepaths["train"] = data_args.train_file
|
| 457 |
+
if data_args.validation_file:
|
| 458 |
+
filepaths["validation"] = data_args.validation_file
|
| 459 |
+
try:
|
| 460 |
+
dataset = load_dataset(
|
| 461 |
+
data_args.dataset_name,
|
| 462 |
+
data_args.dataset_config_name,
|
| 463 |
+
cache_dir=model_args.cache_dir,
|
| 464 |
+
streaming=True,
|
| 465 |
+
split="train",
|
| 466 |
+
)
|
| 467 |
+
except Exception as exc:
|
| 468 |
+
logger.warning(
|
| 469 |
+
f"Unable to load local dataset with perplexity sampling support. Using huggingface.co/datasets/{data_args.dataset_name}: {exc}"
|
| 470 |
+
)
|
| 471 |
+
dataset = load_dataset(
|
| 472 |
+
data_args.dataset_name,
|
| 473 |
+
data_args.dataset_config_name,
|
| 474 |
+
cache_dir=model_args.cache_dir,
|
| 475 |
+
streaming=True,
|
| 476 |
+
split="train",
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
if model_args.config_name:
|
| 480 |
+
config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
|
| 481 |
+
elif model_args.model_name_or_path:
|
| 482 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
|
| 483 |
+
else:
|
| 484 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
| 485 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
| 486 |
+
|
| 487 |
+
if model_args.tokenizer_name:
|
| 488 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 489 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
| 490 |
+
)
|
| 491 |
+
elif model_args.model_name_or_path:
|
| 492 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 493 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
| 494 |
+
)
|
| 495 |
+
else:
|
| 496 |
+
raise ValueError(
|
| 497 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
| 498 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
| 502 |
+
# We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
|
| 503 |
+
# efficient when it receives the `special_tokens_mask`.
|
| 504 |
+
def tokenize_function(examples):
|
| 505 |
+
return tokenizer(
|
| 506 |
+
examples[data_args.text_column_name],
|
| 507 |
+
return_special_tokens_mask=True
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
tokenized_datasets = dataset.map(
|
| 511 |
+
tokenize_function,
|
| 512 |
+
batched=True,
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
shuffle_seed = training_args.seed
|
| 516 |
+
tokenized_datasets = tokenized_datasets.shuffle(buffer_size=data_args.shuffle_buffer_size, seed=shuffle_seed)
|
| 517 |
+
|
| 518 |
+
# Enable tensorboard only on the master node
|
| 519 |
+
has_tensorboard = is_tensorboard_available()
|
| 520 |
+
if has_tensorboard and jax.process_index() == 0:
|
| 521 |
+
try:
|
| 522 |
+
# Enable Weight&Biases
|
| 523 |
+
import wandb
|
| 524 |
+
wandb.init(
|
| 525 |
+
entity='wandb',
|
| 526 |
+
project='hf-flax-bertin-roberta-es',
|
| 527 |
+
sync_tensorboard=True,
|
| 528 |
+
)
|
| 529 |
+
wandb.config.update(training_args)
|
| 530 |
+
wandb.config.update(model_args)
|
| 531 |
+
wandb.config.update(data_args)
|
| 532 |
+
from flax.metrics.tensorboard import SummaryWriter
|
| 533 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
| 534 |
+
except ImportError as ie:
|
| 535 |
+
has_tensorboard = False
|
| 536 |
+
logger.warning(
|
| 537 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
| 538 |
+
)
|
| 539 |
+
else:
|
| 540 |
+
logger.warning(
|
| 541 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
| 542 |
+
"Please run pip install tensorboard to enable."
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
# Data collator
|
| 546 |
+
# This one will take care of randomly masking the tokens.
|
| 547 |
+
data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
|
| 548 |
+
|
| 549 |
+
# Initialize our training
|
| 550 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
| 551 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
| 552 |
+
|
| 553 |
+
if model_args.model_name_or_path:
|
| 554 |
+
model = FlaxAutoModelForMaskedLM.from_pretrained(
|
| 555 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
| 556 |
+
)
|
| 557 |
+
else:
|
| 558 |
+
model = FlaxAutoModelForMaskedLM.from_config(
|
| 559 |
+
config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
# Store some constant
|
| 563 |
+
num_epochs = int(training_args.num_train_epochs)
|
| 564 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
| 565 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
| 566 |
+
|
| 567 |
+
# define number steps per stream epoch
|
| 568 |
+
num_train_steps = data_args.num_train_steps
|
| 569 |
+
|
| 570 |
+
# Create learning rate schedule
|
| 571 |
+
warmup_fn = optax.linear_schedule(
|
| 572 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
| 573 |
+
)
|
| 574 |
+
decay_fn = optax.linear_schedule(
|
| 575 |
+
init_value=training_args.learning_rate,
|
| 576 |
+
end_value=0,
|
| 577 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
| 578 |
+
)
|
| 579 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
| 580 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
| 584 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
| 585 |
+
# mask boolean with the same structure as the parameters.
|
| 586 |
+
# The mask is True for parameters that should be decayed.
|
| 587 |
+
# Note that this mask is specifically adapted for FlaxBERT-like models.
|
| 588 |
+
# For other models, one should correct the layer norm parameter naming
|
| 589 |
+
# accordingly.
|
| 590 |
+
def decay_mask_fn(params):
|
| 591 |
+
flat_params = traverse_util.flatten_dict(params)
|
| 592 |
+
flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
|
| 593 |
+
return traverse_util.unflatten_dict(flat_mask)
|
| 594 |
+
|
| 595 |
+
# create adam optimizer
|
| 596 |
+
adamw = optax.adamw(
|
| 597 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
| 598 |
+
b1=training_args.adam_beta1,
|
| 599 |
+
b2=training_args.adam_beta2,
|
| 600 |
+
eps=training_args.adam_epsilon,
|
| 601 |
+
weight_decay=training_args.weight_decay,
|
| 602 |
+
mask=decay_mask_fn,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
# Setup train state
|
| 606 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=adamw)
|
| 607 |
+
saved_step = -1
|
| 608 |
+
if model_args.model_name_or_path and "checkpoint" in model_args.model_name_or_path:
|
| 609 |
+
params, opt_state, saved_step, args, data_collator = restore_checkpoint(model_args.model_name_or_path, state)
|
| 610 |
+
# Create learning rate schedule
|
| 611 |
+
warmup_fn = optax.linear_schedule(
|
| 612 |
+
init_value=0.0, end_value=args.learning_rate, transition_steps=args.warmup_steps
|
| 613 |
+
)
|
| 614 |
+
decay_fn = optax.linear_schedule(
|
| 615 |
+
init_value=args.learning_rate,
|
| 616 |
+
end_value=0,
|
| 617 |
+
transition_steps=data_args.num_train_steps - args.warmup_steps,
|
| 618 |
+
)
|
| 619 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
| 620 |
+
schedules=[warmup_fn, decay_fn], boundaries=[args.warmup_steps]
|
| 621 |
+
)
|
| 622 |
+
# create adam optimizer
|
| 623 |
+
adamw = optax.adamw(
|
| 624 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
| 625 |
+
b1=training_args.adam_beta1,
|
| 626 |
+
b2=training_args.adam_beta2,
|
| 627 |
+
eps=training_args.adam_epsilon,
|
| 628 |
+
weight_decay=args.weight_decay,
|
| 629 |
+
mask=decay_mask_fn,
|
| 630 |
+
)
|
| 631 |
+
state = train_state.TrainState(
|
| 632 |
+
step=saved_step,
|
| 633 |
+
apply_fn=model.__call__,
|
| 634 |
+
params=params,
|
| 635 |
+
tx=adamw,
|
| 636 |
+
opt_state=opt_state,
|
| 637 |
+
)
|
| 638 |
+
# self.args = args
|
| 639 |
+
# data_collator = data_collator
|
| 640 |
+
# scheduler_fn = args.learning_rate
|
| 641 |
+
model.params = params
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
# Define gradient update step fn
|
| 645 |
+
def train_step(state, batch, dropout_rng):
|
| 646 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
| 647 |
+
|
| 648 |
+
def loss_fn(params):
|
| 649 |
+
labels = batch.pop("labels")
|
| 650 |
+
|
| 651 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
| 652 |
+
|
| 653 |
+
# compute loss, ignore padded input tokens
|
| 654 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
| 655 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
| 656 |
+
|
| 657 |
+
# take average
|
| 658 |
+
loss = loss.sum() / label_mask.sum()
|
| 659 |
+
|
| 660 |
+
return loss
|
| 661 |
+
|
| 662 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
| 663 |
+
loss, grad = grad_fn(state.params)
|
| 664 |
+
grad = jax.lax.pmean(grad, "batch")
|
| 665 |
+
new_state = state.apply_gradients(grads=grad)
|
| 666 |
+
|
| 667 |
+
metrics = jax.lax.pmean(
|
| 668 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
return new_state, metrics, new_dropout_rng
|
| 672 |
+
|
| 673 |
+
# Create parallel version of the train step
|
| 674 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
| 675 |
+
|
| 676 |
+
# Define eval fn
|
| 677 |
+
def eval_step(params, batch):
|
| 678 |
+
labels = batch.pop("labels")
|
| 679 |
+
|
| 680 |
+
logits = model(**batch, params=params, train=False)[0]
|
| 681 |
+
|
| 682 |
+
# compute loss, ignore padded input tokens
|
| 683 |
+
label_mask = jnp.where(labels > 0, 1.0, 0.0)
|
| 684 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
|
| 685 |
+
|
| 686 |
+
# compute accuracy
|
| 687 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
|
| 688 |
+
|
| 689 |
+
# summarize metrics
|
| 690 |
+
metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
|
| 691 |
+
metrics = jax.lax.psum(metrics, axis_name="batch")
|
| 692 |
+
|
| 693 |
+
return metrics
|
| 694 |
+
|
| 695 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
| 696 |
+
|
| 697 |
+
# Replicate the train state on each device
|
| 698 |
+
state = jax_utils.replicate(state)
|
| 699 |
+
|
| 700 |
+
train_time = 0
|
| 701 |
+
train_start = time.time()
|
| 702 |
+
train_metrics = []
|
| 703 |
+
eval_metrics = []
|
| 704 |
+
|
| 705 |
+
training_iter = iter(tokenized_datasets)
|
| 706 |
+
|
| 707 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
| 708 |
+
eval_samples = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, max_seq_length)
|
| 709 |
+
|
| 710 |
+
last_desc = ""
|
| 711 |
+
steps = tqdm(range(num_train_steps), desc="Training...", position=0)
|
| 712 |
+
for step in range(num_train_steps):
|
| 713 |
+
if step < saved_step:
|
| 714 |
+
steps.update(1)
|
| 715 |
+
continue
|
| 716 |
+
# ======================== Training ================================
|
| 717 |
+
try:
|
| 718 |
+
samples = advance_iter_and_group_samples(training_iter, train_batch_size, max_seq_length)
|
| 719 |
+
except StopIteration:
|
| 720 |
+
# Once the end of the dataset stream is reached, the training iterator
|
| 721 |
+
# is reinitialized and reshuffled and a new eval dataset is randomely chosen.
|
| 722 |
+
shuffle_seed += 1
|
| 723 |
+
tokenized_datasets.set_epoch(shuffle_seed)
|
| 724 |
+
|
| 725 |
+
training_iter = iter(tokenized_datasets)
|
| 726 |
+
|
| 727 |
+
eval_dataset = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, max_seq_length)
|
| 728 |
+
samples = advance_iter_and_group_samples(training_iter, train_batch_size, max_seq_length)
|
| 729 |
+
|
| 730 |
+
# process input samples
|
| 731 |
+
model_inputs = data_collator(samples, pad_to_multiple_of=16)
|
| 732 |
+
|
| 733 |
+
# Model forward
|
| 734 |
+
model_inputs = shard(model_inputs.data)
|
| 735 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
| 736 |
+
|
| 737 |
+
train_metrics.append(train_metric)
|
| 738 |
+
|
| 739 |
+
if step % training_args.logging_steps == 0 and step > 0:
|
| 740 |
+
steps.write(
|
| 741 |
+
f"Step... ({step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
|
| 742 |
+
)
|
| 743 |
+
train_time += time.time() - train_start
|
| 744 |
+
if has_tensorboard and jax.process_index() == 0:
|
| 745 |
+
write_train_metric(summary_writer, train_metrics, train_time, step)
|
| 746 |
+
train_metrics = []
|
| 747 |
+
|
| 748 |
+
# ======================== Evaluating ==============================
|
| 749 |
+
if step % training_args.eval_steps == 0 and step > 0:
|
| 750 |
+
eval_samples_idx = jnp.arange(data_args.num_eval_samples)
|
| 751 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
| 752 |
+
|
| 753 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=1)):
|
| 754 |
+
# process input samples
|
| 755 |
+
batch_eval_samples = {k: [v[idx] for idx in batch_idx] for k, v in eval_samples.items()}
|
| 756 |
+
model_inputs = data_collator(batch_eval_samples, pad_to_multiple_of=16)
|
| 757 |
+
|
| 758 |
+
# Model forward
|
| 759 |
+
model_inputs = shard(model_inputs.data)
|
| 760 |
+
metrics = p_eval_step(state.params, model_inputs)
|
| 761 |
+
eval_metrics.append(metrics)
|
| 762 |
+
|
| 763 |
+
# normalize eval metrics
|
| 764 |
+
eval_metrics = get_metrics(eval_metrics)
|
| 765 |
+
eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
|
| 766 |
+
eval_normalizer = eval_metrics.pop("normalizer")
|
| 767 |
+
eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
|
| 768 |
+
|
| 769 |
+
# Update progress bar
|
| 770 |
+
steps.desc = f"Step... ({step}/{num_train_steps} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
|
| 771 |
+
last_desc = steps.desc
|
| 772 |
+
|
| 773 |
+
if has_tensorboard and jax.process_index() == 0:
|
| 774 |
+
write_eval_metric(summary_writer, eval_metrics, step)
|
| 775 |
+
eval_metrics = []
|
| 776 |
+
|
| 777 |
+
# save checkpoint after eval_steps
|
| 778 |
+
if step % training_args.save_steps == 0 and step > 0 and jax.process_index() == 0:
|
| 779 |
+
logger.info(f"Saving checkpoint at {step} steps")
|
| 780 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
| 781 |
+
model.save_pretrained(
|
| 782 |
+
training_args.output_dir,
|
| 783 |
+
params=params,
|
| 784 |
+
push_to_hub=False,
|
| 785 |
+
)
|
| 786 |
+
save_checkpoint_files(state, data_collator, training_args, training_args.output_dir)
|
| 787 |
+
checkpoints_dir = Path(training_args.output_dir) / "checkpoints" / f"checkpoint-{step}"
|
| 788 |
+
checkpoints_dir.mkdir(parents=True, exist_ok=True)
|
| 789 |
+
model.save_pretrained(checkpoints_dir, params=params)
|
| 790 |
+
save_checkpoint_files(state, data_collator, training_args, checkpoints_dir)
|
| 791 |
+
rotate_checkpoints(
|
| 792 |
+
Path(training_args.output_dir) / "checkpoints",
|
| 793 |
+
max_checkpoints=training_args.save_total_limit
|
| 794 |
+
)
|
| 795 |
+
convert(training_args.output_dir, "./")
|
| 796 |
+
model.save_pretrained(
|
| 797 |
+
training_args.output_dir,
|
| 798 |
+
params=params,
|
| 799 |
+
push_to_hub=training_args.push_to_hub,
|
| 800 |
+
commit_message=last_desc,
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
# update tqdm bar
|
| 804 |
+
steps.update(1)
|
| 805 |
+
|
| 806 |
+
if jax.process_index() == 0:
|
| 807 |
+
logger.info(f"Saving checkpoint at {step} steps")
|
| 808 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
| 809 |
+
model.save_pretrained(
|
| 810 |
+
training_args.output_dir,
|
| 811 |
+
params=params,
|
| 812 |
+
push_to_hub=False,
|
| 813 |
+
)
|
| 814 |
+
save_checkpoint_files(state, data_collator, training_args, training_args.output_dir)
|
| 815 |
+
checkpoints_dir = Path(training_args.output_dir) / "checkpoints" / f"checkpoint-{step}"
|
| 816 |
+
checkpoints_dir.mkdir(parents=True, exist_ok=True)
|
| 817 |
+
model.save_pretrained(checkpoints_dir, params=params)
|
| 818 |
+
save_checkpoint_files(state, data_collator, training_args, checkpoints_dir)
|
| 819 |
+
convert(training_args.output_dir, "./")
|
| 820 |
+
model.save_pretrained(
|
| 821 |
+
training_args.output_dir,
|
| 822 |
+
params=params,
|
| 823 |
+
push_to_hub=training_args.push_to_hub,
|
| 824 |
+
commit_message=last_desc or "Saving model after training",
|
| 825 |
+
)
|
run_stream.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From https://arxiv.org/pdf/1907.11692.pdf for base model
|
| 2 |
+
python3 -c "import jax; print('TPUs', jax.device_count())"
|
| 3 |
+
python3 ./run_mlm_flax_stream.py \
|
| 4 |
+
--output_dir="./outputs" \
|
| 5 |
+
--model_type="roberta" \
|
| 6 |
+
--config_name="./configs/base" \
|
| 7 |
+
--tokenizer_name="./" \
|
| 8 |
+
--dataset_name="munggok/KoPI" \
|
| 9 |
+
--dataset_config_name="full" \
|
| 10 |
+
--max_seq_length="512" \
|
| 11 |
+
--pad_to_max_length \
|
| 12 |
+
--per_device_train_batch_size="64" \
|
| 13 |
+
--per_device_eval_batch_size="64" \
|
| 14 |
+
--adam_beta1="0.9" \
|
| 15 |
+
--adam_beta2="0.98" \
|
| 16 |
+
--adam_epsilon="1e-6" \
|
| 17 |
+
--learning_rate="6e-4" \
|
| 18 |
+
--weight_decay="0.01" \
|
| 19 |
+
--save_steps="10000" \
|
| 20 |
+
--save_total_limit="5" \
|
| 21 |
+
--warmup_steps="24000" \
|
| 22 |
+
--overwrite_output_dir \
|
| 23 |
+
--num_train_steps="500000" \
|
| 24 |
+
--eval_steps="10000" \
|
| 25 |
+
--dtype="bfloat16" \
|
| 26 |
+
--logging_steps="500" 2>&1 | tee run_stream.log
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"bos_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "eos_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "unk_token": {"content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "sep_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "pad_token": {"content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "cls_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": true}}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"errors": "replace", "bos_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "eos_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "sep_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "cls_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "unk_token": {"content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "pad_token": {"content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "add_prefix_space": false, "trim_offsets": true, "max_len": 512, "special_tokens_map_file": null, "name_or_path": "./", "tokenizer_class": "RobertaTokenizer"}
|
tokens.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datasets import load_dataset
|
| 2 |
+
from tokenizers import ByteLevelBPETokenizer
|
| 3 |
+
|
| 4 |
+
# Load dataset
|
| 5 |
+
kopi = load_dataset("/data/final_train.py", "full",split='train',cache_dir="/data/cache")
|
| 6 |
+
|
| 7 |
+
datasetv2 = kopi.shuffle(seed=42)
|
| 8 |
+
dataset = datasetv2[0:8000000]
|
| 9 |
+
|
| 10 |
+
# Instantiate tokenizer
|
| 11 |
+
tokenizer = ByteLevelBPETokenizer()
|
| 12 |
+
def batch_iterator(batch_size=100_000):
|
| 13 |
+
for i in range(0, len(dataset), batch_size):
|
| 14 |
+
yield dataset["text"][i: i + batch_size]
|
| 15 |
+
|
| 16 |
+
# Customized training
|
| 17 |
+
tokenizer.train_from_iterator(batch_iterator(), vocab_size=50265, min_frequency=2, special_tokens=[
|
| 18 |
+
"<s>",
|
| 19 |
+
"<pad>",
|
| 20 |
+
"</s>",
|
| 21 |
+
"<unk>",
|
| 22 |
+
"<mask>",
|
| 23 |
+
])
|
| 24 |
+
# Save files to disk
|
| 25 |
+
tokenizer.save("./tokenizer.json")
|
training_state.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"step": 100001}
|