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