nipunsadvilkar commited on
Commit
8a23870
·
1 Parent(s): 546de11

Marathi t5 model trained mc4 mr

Browse files
.gitattributes CHANGED
@@ -15,3 +15,4 @@
15
  *.pt filter=lfs diff=lfs merge=lfs -text
16
  *.pth filter=lfs diff=lfs merge=lfs -text
17
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
15
  *.pt filter=lfs diff=lfs merge=lfs -text
16
  *.pth filter=lfs diff=lfs merge=lfs -text
17
  *tfevents* filter=lfs diff=lfs merge=lfs -text
18
+ flax_model.msgpack filter=lfs diff=lfs merge=lfs -text
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/patrick/hugging_face/t5/t5-v1_1-base",
3
+ "architectures": [
4
+ "T5ForConditionalGeneration"
5
+ ],
6
+ "d_ff": 2048,
7
+ "d_kv": 64,
8
+ "d_model": 768,
9
+ "decoder_start_token_id": 0,
10
+ "dropout_rate": 0.1,
11
+ "eos_token_id": 1,
12
+ "feed_forward_proj": "gated-gelu",
13
+ "gradient_checkpointing": false,
14
+ "initializer_factor": 1.0,
15
+ "is_encoder_decoder": true,
16
+ "layer_norm_epsilon": 1e-06,
17
+ "model_type": "t5",
18
+ "num_decoder_layers": 12,
19
+ "num_heads": 12,
20
+ "num_layers": 12,
21
+ "output_past": true,
22
+ "pad_token_id": 0,
23
+ "relative_attention_num_buckets": 32,
24
+ "tie_word_embeddings": false,
25
+ "transformers_version": "4.9.0.dev0",
26
+ "use_cache": true,
27
+ "vocab_size": 32103
28
+ }
events.out.tfevents.1626448038.t1v-n-112df4a9-w-0.28742.3.v2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0ad15dbbceed74e386e4acc5c77ab569c6e77de6e35e78421508905768106b5
3
+ size 2484467
flax_model.msgpack ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e689ecab3bd26f857b63137a97a60a52b4b2c1c5d42331014bc1a8a465537ce
3
+ size 990170015
run.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_t5_mlm_flax.py \
2
+ --output_dir="./marathi-t5-base" \
3
+ --model_type="t5" \
4
+ --config_name="./marathi-t5-base" \
5
+ --tokenizer_name="./marathi-t5-base" \
6
+ --train_file="/home/nipunsadvilkar/mr_data/mr_train_punctrm.csv" \
7
+ --validation_split_percentage=7 \
8
+ --max_seq_length="512" \
9
+ --per_device_train_batch_size="32" \
10
+ --per_device_eval_batch_size="32" \
11
+ --adafactor \
12
+ --learning_rate="0.005" \
13
+ --weight_decay="0.001" \
14
+ --warmup_steps="2000" \
15
+ --overwrite_output_dir \
16
+ --logging_steps="100" \
17
+ --save_steps="1000" \
18
+ --eval_steps="1000"
run_t5_mlm_flax.py ADDED
@@ -0,0 +1,803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Pretraining the library models for T5-like span-masked language modeling on a text file or a dataset.
18
+
19
+ Here is the full list of checkpoints on the hub that can be pretrained by this script:
20
+ https://huggingface.co/models?filter=t5
21
+ """
22
+ # You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
23
+ import logging
24
+ import os
25
+ import sys
26
+ import time
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+ from typing import Dict, List, Optional
30
+
31
+ import numpy as np
32
+ from datasets import load_dataset
33
+ from tqdm import tqdm
34
+
35
+ import flax
36
+ import jax
37
+ import jax.numpy as jnp
38
+ import optax
39
+ from flax import jax_utils, traverse_util
40
+ from flax.training import train_state
41
+ from flax.training.common_utils import get_metrics, onehot, shard
42
+ from transformers import (
43
+ CONFIG_MAPPING,
44
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
45
+ AutoTokenizer,
46
+ BatchEncoding,
47
+ FlaxT5ForConditionalGeneration,
48
+ HfArgumentParser,
49
+ PreTrainedTokenizerBase,
50
+ T5Config,
51
+ TrainingArguments,
52
+ is_tensorboard_available,
53
+ set_seed,
54
+ )
55
+ from transformers.models.t5.modeling_flax_t5 import shift_tokens_right
56
+
57
+
58
+ import wandb
59
+ wandb.init(
60
+ entity='nipunsadvilkar',
61
+ project='marathi-t5-base',
62
+ sync_tensorboard=True
63
+ )
64
+
65
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
66
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
67
+
68
+
69
+ @dataclass
70
+ class ModelArguments:
71
+ """
72
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
73
+ """
74
+
75
+ model_name_or_path: Optional[str] = field(
76
+ default=None,
77
+ metadata={
78
+ "help": "The model checkpoint for weights initialization."
79
+ "Don't set if you want to train a model from scratch."
80
+ },
81
+ )
82
+ model_type: Optional[str] = field(
83
+ default=None,
84
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
85
+ )
86
+ config_name: Optional[str] = field(
87
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
88
+ )
89
+ tokenizer_name: Optional[str] = field(
90
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
91
+ )
92
+ cache_dir: Optional[str] = field(
93
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
94
+ )
95
+ use_fast_tokenizer: bool = field(
96
+ default=True,
97
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
98
+ )
99
+ dtype: Optional[str] = field(
100
+ default="float32",
101
+ metadata={
102
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
103
+ },
104
+ )
105
+
106
+
107
+ @dataclass
108
+ class DataTrainingArguments:
109
+ """
110
+ Arguments pertaining to what data we are going to input our model for training and eval.
111
+ """
112
+
113
+ dataset_name: Optional[str] = field(
114
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
115
+ )
116
+ dataset_config_name: Optional[str] = field(
117
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
118
+ )
119
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
120
+ validation_file: Optional[str] = field(
121
+ default=None,
122
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
123
+ )
124
+ train_ref_file: Optional[str] = field(
125
+ default=None,
126
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
127
+ )
128
+ validation_ref_file: Optional[str] = field(
129
+ default=None,
130
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
131
+ )
132
+ overwrite_cache: bool = field(
133
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
134
+ )
135
+ validation_split_percentage: Optional[int] = field(
136
+ default=5,
137
+ metadata={
138
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
139
+ },
140
+ )
141
+ max_seq_length: Optional[int] = field(
142
+ default=None,
143
+ metadata={
144
+ "help": "The maximum total input sequence length after tokenization and masking. Sequences longer than this will be truncated. Default to the max input length of the model."
145
+ },
146
+ )
147
+ preprocessing_num_workers: Optional[int] = field(
148
+ default=None,
149
+ metadata={"help": "The number of processes to use for the preprocessing."},
150
+ )
151
+ mlm_probability: float = field(
152
+ default=0.15, metadata={"help": "Ratio of tokens to mask for span masked language modeling loss"}
153
+ )
154
+ mean_noise_span_length: float = field(
155
+ default=3.0,
156
+ metadata={"help": "Mean span length of masked tokens"},
157
+ )
158
+
159
+ def __post_init__(self):
160
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
161
+ raise ValueError("Need either a dataset name or a training/validation file.")
162
+ else:
163
+ if self.train_file is not None:
164
+ extension = self.train_file.split(".")[-1]
165
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
166
+ if self.validation_file is not None:
167
+ extension = self.validation_file.split(".")[-1]
168
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
169
+
170
+
171
+ def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length):
172
+ """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2466>`__ .
173
+
174
+ Training parameters to avoid padding with random_spans_noise_mask.
175
+ When training a model with random_spans_noise_mask, we would like to set the other
176
+ training hyperparmeters in a way that avoids padding.
177
+ This function helps us compute these hyperparameters.
178
+ We assume that each noise span in the input is replaced by extra_tokens_per_span_inputs sentinel tokens,
179
+ and each non-noise span in the targets is replaced by extra_tokens_per_span_targets sentinel tokens.
180
+ This function tells us the required number of tokens in the raw example (for split_tokens())
181
+ as well as the length of the encoded targets. Note that this function assumes
182
+ the inputs and targets will have EOS appended and includes that in the reported length.
183
+
184
+ Args:
185
+ inputs_length: an integer - desired length of the tokenized inputs sequence
186
+ noise_density: a float
187
+ mean_noise_span_length: a float
188
+ Returns:
189
+ tokens_length: length of original text in tokens
190
+ targets_length: an integer - length in tokens of encoded targets sequence
191
+ """
192
+
193
+ def _tokens_length_to_inputs_length_targets_length(tokens_length):
194
+ num_noise_tokens = int(round(tokens_length * noise_density))
195
+ num_nonnoise_tokens = tokens_length - num_noise_tokens
196
+ num_noise_spans = int(round(num_noise_tokens / mean_noise_span_length))
197
+ # inputs contain all nonnoise tokens, sentinels for all noise spans
198
+ # and one EOS token.
199
+ _input_length = num_nonnoise_tokens + num_noise_spans + 1
200
+ _output_length = num_noise_tokens + num_noise_spans + 1
201
+ return _input_length, _output_length
202
+
203
+ tokens_length = inputs_length
204
+
205
+ while _tokens_length_to_inputs_length_targets_length(tokens_length + 1)[0] <= inputs_length:
206
+ tokens_length += 1
207
+
208
+ inputs_length, targets_length = _tokens_length_to_inputs_length_targets_length(tokens_length)
209
+
210
+ # minor hack to get the targets length to be equal to inputs length
211
+ # which is more likely to have been set to a nice round number.
212
+ if noise_density == 0.5 and targets_length > inputs_length:
213
+ tokens_length -= 1
214
+ targets_length -= 1
215
+ return tokens_length, targets_length
216
+
217
+
218
+ @flax.struct.dataclass
219
+ class FlaxDataCollatorForT5MLM:
220
+ """
221
+ Data collator used for T5 span-masked language modeling.
222
+ It is made sure that after masking the inputs are of length `data_args.max_seq_length` and targets are also of fixed length.
223
+ For more information on how T5 span-masked language modeling works, one can take a look
224
+ at the `official paper <https://arxiv.org/pdf/1910.10683.pdf>`__
225
+ or the `official code for preprocessing <https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/data/preprocessors.py>`__ .
226
+
227
+ Args:
228
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
229
+ The tokenizer used for encoding the data.
230
+ noise_density (:obj:`float`):
231
+ The probability with which to (randomly) mask tokens in the input.
232
+ mean_noise_span_length (:obj:`float`):
233
+ The average span length of the masked tokens.
234
+ input_length (:obj:`int`):
235
+ The expected input length after masking.
236
+ target_length (:obj:`int`):
237
+ The expected target length after masking.
238
+ pad_token_id: (:obj:`int`):
239
+ The pad token id of the model
240
+ decoder_start_token_id: (:obj:`int):
241
+ The decoder start token id of the model
242
+ """
243
+
244
+ tokenizer: PreTrainedTokenizerBase
245
+ noise_density: float
246
+ mean_noise_span_length: float
247
+ input_length: int
248
+ target_length: int
249
+ pad_token_id: int
250
+ decoder_start_token_id: int
251
+
252
+ def __call__(self, examples: List[Dict[str, np.ndarray]]) -> Dict[str, np.ndarray]:
253
+
254
+ # convert list to dict and tensorize input
255
+ batch = BatchEncoding(
256
+ {k: np.array([examples[i][k] for i in range(len(examples))]) for k, v in examples[0].items()}
257
+ )
258
+
259
+ input_ids = batch["input_ids"]
260
+ batch_size, expandend_input_length = input_ids.shape
261
+
262
+ mask_indices = np.asarray([self.random_spans_noise_mask(expandend_input_length) for i in range(batch_size)])
263
+ labels_mask = ~mask_indices
264
+
265
+ input_ids_sentinel = self.create_sentinel_ids(mask_indices.astype(np.int8))
266
+ labels_sentinel = self.create_sentinel_ids(labels_mask.astype(np.int8))
267
+
268
+ batch["input_ids"] = self.filter_input_ids(input_ids, input_ids_sentinel)
269
+ batch["labels"] = self.filter_input_ids(input_ids, labels_sentinel)
270
+
271
+ if batch["input_ids"].shape[-1] != self.input_length:
272
+ raise ValueError(
273
+ f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but should be {self.target_length}."
274
+ )
275
+
276
+ if batch["labels"].shape[-1] != self.target_length:
277
+ raise ValueError(
278
+ f"`labels` are incorrectly preprocessed. `labels` length is {batch['labels'].shape[-1]}, but should be {self.target_length}."
279
+ )
280
+
281
+ # to check that tokens are correctly proprocessed, one can run `self.tokenizer.batch_decode(input_ids)` and `self.tokenizer.batch_decode(labels)` here...
282
+ batch["decoder_input_ids"] = shift_tokens_right(
283
+ batch["labels"], self.pad_token_id, self.decoder_start_token_id
284
+ )
285
+
286
+ return batch
287
+
288
+ def create_sentinel_ids(self, mask_indices):
289
+ """
290
+ Sentinel ids creation given the indices that should be masked.
291
+ The start indices of each mask are replaced by the sentinel ids in increasing
292
+ order. Consecutive mask indices to be deleted are replaced with `-1`.
293
+ """
294
+ start_indices = mask_indices - np.roll(mask_indices, 1, axis=-1) * mask_indices
295
+ start_indices[:, 0] = mask_indices[:, 0]
296
+
297
+ sentinel_ids = np.where(start_indices != 0, np.cumsum(start_indices, axis=-1), start_indices)
298
+ sentinel_ids = np.where(sentinel_ids != 0, (sentinel_ids + self.tokenizer.vocab_size - 1), 0)
299
+ sentinel_ids -= mask_indices - start_indices
300
+
301
+ return sentinel_ids
302
+
303
+ def filter_input_ids(self, input_ids, sentinel_ids):
304
+ """
305
+ Puts sentinel mask on `input_ids` and fuse consecutive mask tokens into a single mask token by deleting.
306
+ This will reduce the sequence length from `expanded_inputs_length` to `input_length`.
307
+ """
308
+ batch_size = input_ids.shape[0]
309
+
310
+ input_ids_full = np.where(sentinel_ids != 0, sentinel_ids, input_ids)
311
+ input_ids = input_ids_full[input_ids_full > 0].reshape((batch_size, -1))
312
+ input_ids = np.concatenate(
313
+ [input_ids, np.full((batch_size, 1), self.tokenizer.eos_token_id, dtype=np.int32)], axis=-1
314
+ )
315
+ return input_ids
316
+
317
+ def random_spans_noise_mask(self, length):
318
+
319
+ """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2682>`__ .
320
+
321
+ Noise mask consisting of random spans of noise tokens.
322
+ The number of noise tokens and the number of noise spans and non-noise spans
323
+ are determined deterministically as follows:
324
+ num_noise_tokens = round(length * noise_density)
325
+ num_nonnoise_spans = num_noise_spans = round(num_noise_tokens / mean_noise_span_length)
326
+ Spans alternate between non-noise and noise, beginning with non-noise.
327
+ Subject to the above restrictions, all masks are equally likely.
328
+
329
+ Args:
330
+ length: an int32 scalar (length of the incoming token sequence)
331
+ noise_density: a float - approximate density of output mask
332
+ mean_noise_span_length: a number
333
+
334
+ Returns:
335
+ a boolean tensor with shape [length]
336
+ """
337
+
338
+ orig_length = length
339
+
340
+ num_noise_tokens = int(np.round(length * self.noise_density))
341
+ # avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
342
+ num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
343
+ num_noise_spans = int(np.round(num_noise_tokens / self.mean_noise_span_length))
344
+
345
+ # avoid degeneracy by ensuring positive number of noise spans
346
+ num_noise_spans = max(num_noise_spans, 1)
347
+ num_nonnoise_tokens = length - num_noise_tokens
348
+
349
+ # pick the lengths of the noise spans and the non-noise spans
350
+ def _random_segmentation(num_items, num_segments):
351
+ """Partition a sequence of items randomly into non-empty segments.
352
+ Args:
353
+ num_items: an integer scalar > 0
354
+ num_segments: an integer scalar in [1, num_items]
355
+ Returns:
356
+ a Tensor with shape [num_segments] containing positive integers that add
357
+ up to num_items
358
+ """
359
+ mask_indices = np.arange(num_items - 1) < (num_segments - 1)
360
+ np.random.shuffle(mask_indices)
361
+ first_in_segment = np.pad(mask_indices, [[1, 0]])
362
+ segment_id = np.cumsum(first_in_segment)
363
+ segment_length = np.asarray(jax.ops.segment_sum(np.ones_like(segment_id), segment_id))
364
+ return segment_length
365
+
366
+ noise_span_lengths = _random_segmentation(num_noise_tokens, num_noise_spans)
367
+ nonnoise_span_lengths = _random_segmentation(num_nonnoise_tokens, num_noise_spans)
368
+
369
+ interleaved_span_lengths = np.reshape(
370
+ np.stack([nonnoise_span_lengths, noise_span_lengths], axis=1), [num_noise_spans * 2]
371
+ )
372
+ span_starts = np.cumsum(interleaved_span_lengths)[:-1]
373
+ span_start_indicator = np.zeros((length,), dtype=np.int8)
374
+ span_start_indicator[span_starts] = True
375
+ span_num = np.cumsum(span_start_indicator)
376
+ is_noise = np.equal(span_num % 2, 1)
377
+
378
+ return is_noise[:orig_length]
379
+
380
+
381
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
382
+ num_samples = len(samples_idx)
383
+ samples_to_remove = num_samples % batch_size
384
+
385
+ if samples_to_remove != 0:
386
+ samples_idx = samples_idx[:-samples_to_remove]
387
+ sections_split = num_samples // batch_size
388
+ batch_idx = np.split(samples_idx, sections_split)
389
+ return batch_idx
390
+
391
+
392
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
393
+ summary_writer.scalar("train_time", train_time, step)
394
+
395
+ train_metrics = get_metrics(train_metrics)
396
+ for key, vals in train_metrics.items():
397
+ tag = f"train_{key}"
398
+ for i, val in enumerate(vals):
399
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
400
+
401
+
402
+ def write_eval_metric(summary_writer, eval_metrics, step):
403
+ for metric_name, value in eval_metrics.items():
404
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
405
+
406
+
407
+ if __name__ == "__main__":
408
+ # See all possible arguments in src/transformers/training_args.py
409
+ # or by passing the --help flag to this script.
410
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
411
+
412
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
413
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
414
+ # If we pass only one argument to the script and it's the path to a json file,
415
+ # let's parse it to get our arguments.
416
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
417
+ else:
418
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
419
+
420
+ if (
421
+ os.path.exists(training_args.output_dir)
422
+ and os.listdir(training_args.output_dir)
423
+ and training_args.do_train
424
+ and not training_args.overwrite_output_dir
425
+ ):
426
+ raise ValueError(
427
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
428
+ "Use --overwrite_output_dir to overcome."
429
+ )
430
+
431
+ # Setup logging
432
+ logging.basicConfig(
433
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
434
+ level="NOTSET",
435
+ datefmt="[%X]",
436
+ )
437
+
438
+ # Log on each process the small summary:
439
+ logger = logging.getLogger(__name__)
440
+
441
+ # Set the verbosity to info of the Transformers logger (on main process only):
442
+ logger.info(f"Training/evaluation parameters {training_args}")
443
+
444
+ # Set seed before initializing model.
445
+ set_seed(training_args.seed)
446
+
447
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
448
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
449
+ # (the dataset will be downloaded automatically from the datasets Hub).
450
+ #
451
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
452
+ # 'text' is found. You can easily tweak this behavior (see below).
453
+ if data_args.dataset_name is not None:
454
+ # Downloading and loading a dataset from the hub.
455
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
456
+
457
+ if "validation" not in datasets.keys():
458
+ datasets["validation"] = load_dataset(
459
+ data_args.dataset_name,
460
+ data_args.dataset_config_name,
461
+ split=f"train[:{data_args.validation_split_percentage}%]",
462
+ cache_dir=model_args.cache_dir,
463
+ )
464
+ datasets["train"] = load_dataset(
465
+ data_args.dataset_name,
466
+ data_args.dataset_config_name,
467
+ split=f"train[{data_args.validation_split_percentage}%:]",
468
+ cache_dir=model_args.cache_dir,
469
+ )
470
+ else:
471
+ data_files = {}
472
+ if data_args.train_file is not None:
473
+ data_files["train"] = data_args.train_file
474
+ if data_args.validation_file is not None:
475
+ data_files["validation"] = data_args.validation_file
476
+ extension = data_args.train_file.split(".")[-1]
477
+ if extension == "txt":
478
+ extension = "text"
479
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
480
+ if data_args.validation_file is None:
481
+ datasets["validation"] = load_dataset(
482
+ extension, data_files=data_files,
483
+ split=f"train[:{data_args.validation_split_percentage}%]",
484
+ cache_dir=model_args.cache_dir,
485
+ )
486
+ datasets["train"] = load_dataset(
487
+ extension, data_files=data_files,
488
+ split=f"train[{data_args.validation_split_percentage}%:]",
489
+ cache_dir=model_args.cache_dir,
490
+ )
491
+ print(datasets)
492
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
493
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
494
+
495
+ # Load pretrained model and tokenizer
496
+
497
+ if model_args.tokenizer_name:
498
+ tokenizer = AutoTokenizer.from_pretrained(
499
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
500
+ )
501
+ elif model_args.model_name_or_path:
502
+ tokenizer = AutoTokenizer.from_pretrained(
503
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
504
+ )
505
+ else:
506
+ raise ValueError(
507
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
508
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
509
+ )
510
+
511
+ if model_args.config_name:
512
+ config = T5Config.from_pretrained(
513
+ model_args.config_name, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
514
+ )
515
+ elif model_args.model_name_or_path:
516
+ config = T5Config.from_pretrained(
517
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
518
+ )
519
+ else:
520
+ config = CONFIG_MAPPING[model_args.model_type]()
521
+ logger.warning("You are instantiating a new config instance from scratch.")
522
+
523
+ # Preprocessing the datasets.
524
+ # First we tokenize all the texts.
525
+ if training_args.do_train:
526
+ column_names = datasets["train"].column_names
527
+ else:
528
+ column_names = datasets["validation"].column_names
529
+ text_column_name = "text" if "text" in column_names else column_names[0]
530
+
531
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
532
+
533
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
534
+ # Since we make sure that all sequences are of the same length, no attention_mask is needed.
535
+ def tokenize_function(examples):
536
+ return tokenizer(examples[text_column_name], return_attention_mask=False)
537
+
538
+ tokenized_datasets = datasets.map(
539
+ tokenize_function,
540
+ batched=True,
541
+ num_proc=data_args.preprocessing_num_workers,
542
+ remove_columns=column_names,
543
+ load_from_cache_file=not data_args.overwrite_cache,
544
+ )
545
+
546
+ # T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token.
547
+ # To ensure that the input length is `max_seq_length`, we need to increase the maximum length
548
+ # according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly.
549
+ expanded_inputs_length, targets_length = compute_input_and_target_lengths(
550
+ inputs_length=max_seq_length,
551
+ noise_density=data_args.mlm_probability,
552
+ mean_noise_span_length=data_args.mean_noise_span_length,
553
+ )
554
+
555
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of expanded_inputs_length.
556
+ def group_texts(examples):
557
+ # Concatenate all texts.
558
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
559
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
560
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
561
+ # customize this part to your needs.
562
+ if total_length >= expanded_inputs_length:
563
+ total_length = (total_length // expanded_inputs_length) * expanded_inputs_length
564
+ # Split by chunks of max_len.
565
+ result = {
566
+ k: [t[i : i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)]
567
+ for k, t in concatenated_examples.items()
568
+ }
569
+ return result
570
+
571
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
572
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
573
+ # might be slower to preprocess.
574
+ #
575
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
576
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
577
+ tokenized_datasets = tokenized_datasets.map(
578
+ group_texts,
579
+ batched=True,
580
+ num_proc=data_args.preprocessing_num_workers,
581
+ load_from_cache_file=not data_args.overwrite_cache,
582
+ )
583
+
584
+ # Enable tensorboard only on the master node
585
+ has_tensorboard = is_tensorboard_available()
586
+ if has_tensorboard and jax.process_index() == 0:
587
+ try:
588
+ from flax.metrics.tensorboard import SummaryWriter
589
+
590
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
591
+ except ImportError as ie:
592
+ has_tensorboard = False
593
+ logger.warning(
594
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
595
+ )
596
+ else:
597
+ logger.warning(
598
+ "Unable to display metrics through TensorBoard because the package is not installed: "
599
+ "Please run pip install tensorboard to enable."
600
+ )
601
+
602
+ # Initialize our training
603
+ rng = jax.random.PRNGKey(training_args.seed)
604
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
605
+
606
+ if model_args.model_name_or_path:
607
+ model = FlaxT5ForConditionalGeneration.from_pretrained(
608
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
609
+ )
610
+ else:
611
+ model = FlaxT5ForConditionalGeneration(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
612
+
613
+ # Data collator
614
+ # This one will take care of randomly masking the tokens.
615
+ data_collator = FlaxDataCollatorForT5MLM(
616
+ tokenizer=tokenizer,
617
+ noise_density=data_args.mlm_probability,
618
+ mean_noise_span_length=data_args.mean_noise_span_length,
619
+ input_length=max_seq_length,
620
+ target_length=targets_length,
621
+ pad_token_id=model.config.pad_token_id,
622
+ decoder_start_token_id=model.config.decoder_start_token_id,
623
+ )
624
+
625
+ # Store some constant
626
+ num_epochs = int(training_args.num_train_epochs)
627
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
628
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
629
+
630
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
631
+
632
+ # Create learning rate schedule
633
+ warmup_fn = optax.linear_schedule(
634
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
635
+ )
636
+ decay_fn = optax.linear_schedule(
637
+ init_value=training_args.learning_rate,
638
+ end_value=0,
639
+ transition_steps=num_train_steps - training_args.warmup_steps,
640
+ )
641
+ linear_decay_lr_schedule_fn = optax.join_schedules(
642
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
643
+ )
644
+
645
+ # We use Optax's "masking" functionality to not apply weight decay
646
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
647
+ # mask boolean with the same structure as the parameters.
648
+ # The mask is True for parameters that should be decayed.
649
+ def decay_mask_fn(params):
650
+ flat_params = traverse_util.flatten_dict(params)
651
+ flat_mask = {
652
+ path: (path[-1] != "bias" and path[-2:] not in [("layer_norm", "scale"), ("final_layer_norm", "scale")])
653
+ for path in flat_params
654
+ }
655
+ return traverse_util.unflatten_dict(flat_mask)
656
+
657
+ # create adam optimizer
658
+ if training_args.adafactor:
659
+ # We use the default parameters here to initialize adafactor,
660
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
661
+ optimizer = optax.adafactor(
662
+ learning_rate=linear_decay_lr_schedule_fn,
663
+ )
664
+ else:
665
+ optimizer = optax.adamw(
666
+ learning_rate=linear_decay_lr_schedule_fn,
667
+ b1=training_args.adam_beta1,
668
+ b2=training_args.adam_beta2,
669
+ weight_decay=training_args.weight_decay,
670
+ mask=decay_mask_fn,
671
+ )
672
+
673
+ # Setup train state
674
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
675
+
676
+ # Define gradient update step fn
677
+ def train_step(state, batch, dropout_rng):
678
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
679
+
680
+ def loss_fn(params):
681
+ labels = batch.pop("labels")
682
+
683
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
684
+
685
+ # compute loss
686
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean()
687
+
688
+ return loss
689
+
690
+ grad_fn = jax.value_and_grad(loss_fn)
691
+ loss, grad = grad_fn(state.params)
692
+ grad = jax.lax.pmean(grad, "batch")
693
+ new_state = state.apply_gradients(grads=grad)
694
+
695
+ metrics = jax.lax.pmean(
696
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
697
+ )
698
+
699
+ return new_state, metrics, new_dropout_rng
700
+
701
+ # Create parallel version of the train step
702
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
703
+
704
+ # Define eval fn
705
+ def eval_step(params, batch):
706
+ labels = batch.pop("labels")
707
+
708
+ logits = model(**batch, params=params, train=False)[0]
709
+
710
+ # compute loss
711
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1]))
712
+
713
+ # compute accuracy
714
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels)
715
+
716
+ # summarize metrics
717
+ metrics = {"loss": loss.mean(), "accuracy": accuracy.mean()}
718
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
719
+
720
+ return metrics
721
+
722
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
723
+
724
+ # Replicate the train state on each device
725
+ state = jax_utils.replicate(state)
726
+
727
+ train_time = 0
728
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
729
+ for epoch in epochs:
730
+ # ======================== Training ================================
731
+ train_start = time.time()
732
+ train_metrics = []
733
+
734
+ # Create sampling rng
735
+ rng, input_rng = jax.random.split(rng)
736
+
737
+ # Generate an epoch by shuffling sampling indices from the train dataset
738
+ num_train_samples = len(tokenized_datasets["train"])
739
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
740
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
741
+
742
+ # Gather the indexes for creating the batch and do a training step
743
+ for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
744
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
745
+ model_inputs = data_collator(samples)
746
+
747
+ # Model forward
748
+ model_inputs = shard(model_inputs.data)
749
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
750
+ train_metrics.append(train_metric)
751
+
752
+ cur_step = epoch * (num_train_samples // train_batch_size) + step
753
+
754
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
755
+ # Save metrics
756
+ train_metric = jax_utils.unreplicate(train_metric)
757
+ train_time += time.time() - train_start
758
+ if has_tensorboard and jax.process_index() == 0:
759
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
760
+
761
+ epochs.write(
762
+ f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
763
+ )
764
+
765
+ train_metrics = []
766
+
767
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
768
+ # ======================== Evaluating ==============================
769
+ num_eval_samples = len(tokenized_datasets["validation"])
770
+ eval_samples_idx = jnp.arange(num_eval_samples)
771
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
772
+
773
+ eval_metrics = []
774
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
775
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
776
+ model_inputs = data_collator(samples)
777
+
778
+ # Model forward
779
+ model_inputs = shard(model_inputs.data)
780
+ metrics = p_eval_step(state.params, model_inputs)
781
+ eval_metrics.append(metrics)
782
+
783
+ # get eval metrics
784
+ eval_metrics = get_metrics(eval_metrics)
785
+ eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
786
+
787
+ # Update progress bar
788
+ epochs.write(f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})")
789
+
790
+ # Save metrics
791
+ if has_tensorboard and jax.process_index() == 0:
792
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
793
+
794
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
795
+ # save checkpoint after each epoch and push checkpoint to the hub
796
+ if jax.process_index() == 0:
797
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
798
+ model.save_pretrained(
799
+ training_args.output_dir,
800
+ params=params,
801
+ push_to_hub=training_args.push_to_hub,
802
+ commit_message=f"Saving weights and logs of step {cur_step}",
803
+ )
t5_tokenizer_model.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import json
3
+ from typing import Iterator, List, Union
4
+
5
+ from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers
6
+ from tokenizers.implementations.base_tokenizer import BaseTokenizer
7
+ from tokenizers.models import Unigram
8
+ from tokenizers.processors import TemplateProcessing
9
+
10
+ import wandb
11
+ wandb.init(
12
+ entity='nipunsadvilkar',
13
+ project='marathi-t5-base',
14
+ sync_tensorboard=True
15
+ )
16
+
17
+ class SentencePieceUnigramTokenizer(BaseTokenizer):
18
+ """
19
+ This class is a copy of `DeDLOC's tokenizer implementation <https://github.com/yandex-research/DeDLOC/blob/main/sahajbert/tokenizer/tokenizer_model.py>`__ .
20
+
21
+ Custom SentencePiece Unigram Tokenizer with NMT, NKFC, spaces and lower-casing characters normalization
22
+ Represents the Unigram algorithm, with the pretokenization used by SentencePiece
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ replacement: str = "▁",
28
+ add_prefix_space: bool = True,
29
+ unk_token: Union[str, AddedToken] = "<unk>",
30
+ eos_token: Union[str, AddedToken] = "</s>",
31
+ pad_token: Union[str, AddedToken] = "<pad>",
32
+ ):
33
+ self.special_tokens = {
34
+ "pad": {"id": 0, "token": pad_token},
35
+ "eos": {"id": 1, "token": eos_token},
36
+ "unk": {"id": 2, "token": unk_token},
37
+ }
38
+
39
+ self.special_tokens_list = [None] * len(self.special_tokens)
40
+ for token_dict in self.special_tokens.values():
41
+ self.special_tokens_list[token_dict["id"]] = token_dict["token"]
42
+
43
+ tokenizer = Tokenizer(Unigram())
44
+
45
+ tokenizer.normalizer = normalizers.Sequence(
46
+ [
47
+ normalizers.Nmt(),
48
+ normalizers.NFKC(),
49
+ normalizers.Replace(Regex(" {2,}"), " "),
50
+ normalizers.Lowercase(),
51
+ ]
52
+ )
53
+ tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
54
+ [
55
+ pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space),
56
+ pre_tokenizers.Digits(individual_digits=True),
57
+ pre_tokenizers.Punctuation(),
58
+ ]
59
+ )
60
+ tokenizer.decoder = decoders.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space)
61
+
62
+ tokenizer.post_processor = TemplateProcessing(
63
+ single=f"$A {self.special_tokens['eos']['token']}",
64
+ special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])],
65
+ )
66
+
67
+ parameters = {
68
+ "model": "SentencePieceUnigram",
69
+ "replacement": replacement,
70
+ "add_prefix_space": add_prefix_space,
71
+ }
72
+
73
+ super().__init__(tokenizer, parameters)
74
+
75
+ def train(
76
+ self,
77
+ files: Union[str, List[str]],
78
+ vocab_size: int = 8000,
79
+ show_progress: bool = True,
80
+ ):
81
+ """Train the model using the given files"""
82
+
83
+ trainer = trainers.UnigramTrainer(
84
+ vocab_size=vocab_size,
85
+ special_tokens=self.special_tokens_list,
86
+ show_progress=show_progress,
87
+ )
88
+
89
+ if isinstance(files, str):
90
+ files = [files]
91
+ self._tokenizer.train(files, trainer=trainer)
92
+
93
+ self.add_unk_id()
94
+
95
+ def train_from_iterator(
96
+ self,
97
+ iterator: Union[Iterator[str], Iterator[Iterator[str]]],
98
+ vocab_size: int = 8000,
99
+ show_progress: bool = True,
100
+ ):
101
+ """Train the model using the given iterator"""
102
+
103
+ trainer = trainers.UnigramTrainer(
104
+ vocab_size=vocab_size,
105
+ special_tokens=self.special_tokens_list,
106
+ show_progress=show_progress,
107
+ )
108
+
109
+ self._tokenizer.train_from_iterator(iterator, trainer=trainer)
110
+
111
+ self.add_unk_id()
112
+
113
+ def add_unk_id(self):
114
+ tokenizer_json = json.loads(self._tokenizer.to_str())
115
+
116
+ tokenizer_json["model"]["unk_id"] = self.special_tokens["unk"]["id"]
117
+
118
+ self._tokenizer = Tokenizer.from_str(json.dumps(tokenizer_json))
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff