
"""simple docstring"""




import json
import os
import tempfile

import datasets
from utils import generate_example_dataset, get_duration


snake_case			       =		5_0_0_0_0_0

snake_case       ,      snake_case			       =		os.path.split(__file__)
snake_case			       =		os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json'))

@get_duration
def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_      ):
					SCREAMING_SNAKE_CASE           =     dataset.select(range(0,					len(SCREAMING_SNAKE_CASE_      ),					2      )      )

@get_duration
def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_      ):
					SCREAMING_SNAKE_CASE           =     dataset.sort('numbers'      )

@get_duration
def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_      ):
					SCREAMING_SNAKE_CASE           =     dataset.shuffle()

@get_duration
def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_      ):
					SCREAMING_SNAKE_CASE           =     dataset.train_test_split(0.1      )

@get_duration
def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_=1_0      ):
					for shard_id in range(SCREAMING_SNAKE_CASE_      ):
										SCREAMING_SNAKE_CASE           =     dataset.shard(SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_      )

def   UpperCamelCase_  (		):
					SCREAMING_SNAKE_CASE           =     {'num examples': SPEED_TEST_N_EXAMPLES}
					SCREAMING_SNAKE_CASE           =     (select, sort, shuffle, train_test_split, shard)
					with tempfile.TemporaryDirectory() as tmp_dir:
										print('generating dataset'      )
										SCREAMING_SNAKE_CASE           =     datasets.Features({'text': datasets.Value('string'      ), 'numbers': datasets.Value('float32'      )}      )
										SCREAMING_SNAKE_CASE           =     generate_example_dataset(
										    os.path.join(SCREAMING_SNAKE_CASE_,					'dataset.arrow'      ),					SCREAMING_SNAKE_CASE_,					num_examples=SCREAMING_SNAKE_CASE_      )
										print('Functions'      )
										for func in functions:
															print(func.__name__      )
															SCREAMING_SNAKE_CASE           =     func(SCREAMING_SNAKE_CASE_      )

					with open(SCREAMING_SNAKE_CASE_,					'wb'      ) as f:
										f.write(json.dumps(SCREAMING_SNAKE_CASE_      ).encode('utf-8'      )      )


if __name__ == "__main__":  # useful to run the profiler
	benchmark_indices_mapping()


"""simple docstring"""




import argparse
import logging

import datasets
from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
from tokenizers.models import Unigram
from tokenizers.trainers import UnigramTrainer

from transformers import AlbertTokenizerFast


snake_case			       =		logging.getLogger(__name__)

def   UpperCamelCase_  (		):
					SCREAMING_SNAKE_CASE           =     argparse.ArgumentParser(description='Train a unigram tokenizer on the wikitext dataset.'      )
					parser.add_argument(
					    '--dataset_name',					type=SCREAMING_SNAKE_CASE_,					default='wikitext',					help='Name of the training. Explore datasets at: hf.co/datasets.',					)
					parser.add_argument(
					    '--dataset_config',					type=SCREAMING_SNAKE_CASE_,					default='wikitext-103-raw-v1',					help='Configuration name of the dataset.'      )
					parser.add_argument(
					    '--batch_size',					type=SCREAMING_SNAKE_CASE_,					default=1_0_0_0,					help='Batch size during training.',					)
					parser.add_argument(
					    '--vocab_size',					type=SCREAMING_SNAKE_CASE_,					default=1_0_0_4_8,					help='Size of the desired vocabulary.',					)
					parser.add_argument(
					    '--limit',					default=SCREAMING_SNAKE_CASE_,					type=SCREAMING_SNAKE_CASE_,					help='Limit the number of shards (used for debugging).',					)
					parser.add_argument(
					    '--export_to_hub',					action='store_true',					)

					SCREAMING_SNAKE_CASE           =     parser.parse_args()
					return args

def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_      ):
					SCREAMING_SNAKE_CASE           =     datasets.load_dataset(args.dataset_name,					args.dataset_config,					split='train'      )

					if args.limit is not None:
										SCREAMING_SNAKE_CASE           =     min(len(SCREAMING_SNAKE_CASE_      ),					args.limit      )
										SCREAMING_SNAKE_CASE           =     dataset.select(range(SCREAMING_SNAKE_CASE_      )      )
										logger.info(f'''Limiting the dataset to {args.limit} entries.'''      )

					def batch_iterator():
										for i in range(0,					len(SCREAMING_SNAKE_CASE_      ),					args.batch_size      ):
															yield dataset[i : i + args.batch_size]["text"]

    # Prepare the tokenizer.
					SCREAMING_SNAKE_CASE           =     Tokenizer(Unigram()      )
					SCREAMING_SNAKE_CASE           =     normalizers.Sequence([normalizers.Replace('``',					'"'      ), normalizers.Replace('\'\'',					'"'      )]      )
					SCREAMING_SNAKE_CASE           =     pre_tokenizers.Metaspace()

					# Prepare the trainer.
					SCREAMING_SNAKE_CASE           =     UnigramTrainer(
					    unk_token='<unk>',					special_tokens=['[CLS]', '[SEP]', '<unk>', '<pad>', '[MASK]'],					vocab_size=args.vocab_size,					)

					logger.info('Training the tokenizer.'      )
					tokenizer.train_from_iterator(batch_iterator(),					trainer=SCREAMING_SNAKE_CASE_      )
					logger.info('Tokenizer training complete!'      )

					SCREAMING_SNAKE_CASE           =     tokenizer.token_to_id('[CLS]'      )
					SCREAMING_SNAKE_CASE           =     tokenizer.token_to_id('[SEP]'      )
					SCREAMING_SNAKE_CASE           =     processors.TemplateProcessing(
					    single='[CLS]:0 $A:0 [SEP]:0',					pair='[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1',					special_tokens=[
					        ('[CLS]', cls_token_id),
					        ('[SEP]', sep_token_id),
					    ],					)
					SCREAMING_SNAKE_CASE           =     decoders.Metaspace()

					if args.export_to_hub:
										logger.info('Exporting the trained tokenzier to Hub.'      )
										SCREAMING_SNAKE_CASE           =     AlbertTokenizerFast(tokenizer_object=SCREAMING_SNAKE_CASE_      )
										new_tokenizer.push_to_hub('unigram-tokenizer-dataset'      )


if __name__ == "__main__":
	snake_case			       =		parse_args()
	main(args)
