


'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import numpy
					import tensorflow as tf

					from transformers import (
					    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
					    BertConfig,
					    DPRConfig,
					    TFDPRContextEncoder,
					    TFDPRQuestionEncoder,
					    TFDPRReader,
					)



class  lowerCAmelCase				:



	def __init__(					self ,					snake_case__ ,					snake_case__=13 ,					snake_case__=7 ,					snake_case__=True ,					snake_case__=True ,					snake_case__=True ,					snake_case__=True ,					snake_case__=99 ,					snake_case__=32 ,					snake_case__=2 ,					snake_case__=4 ,					snake_case__=37 ,					snake_case__="gelu" ,					snake_case__=0.1 ,					snake_case__=0.1 ,					snake_case__=512 ,					snake_case__=16 ,					snake_case__=2 ,					snake_case__=0.0_2 ,					snake_case__=3 ,					snake_case__=4 ,					snake_case__=None ,					snake_case__=0 ,					):
		lowerCAmelCase					:    Optional[int]      							= parent
		lowerCAmelCase					:    Dict      							= batch_size
		lowerCAmelCase					:    Optional[Any]      							= seq_length
		lowerCAmelCase					:    Union[str, Any]      							= is_training
		lowerCAmelCase					:    Optional[Any]      							= use_input_mask
		lowerCAmelCase					:    List[str]      							= use_token_type_ids
		lowerCAmelCase					:    Tuple      							= use_labels
		lowerCAmelCase					:    int      							= vocab_size
		lowerCAmelCase					:    List[Any]      							= hidden_size
		lowerCAmelCase					:    Tuple      							= num_hidden_layers
		lowerCAmelCase					:    Any      							= num_attention_heads
		lowerCAmelCase					:    int      							= intermediate_size
		lowerCAmelCase					:    int      							= hidden_act
		lowerCAmelCase					:    Optional[int]      							= hidden_dropout_prob
		lowerCAmelCase					:    Optional[int]      							= attention_probs_dropout_prob
		lowerCAmelCase					:    List[Any]      							= max_position_embeddings
		lowerCAmelCase					:    Tuple      							= type_vocab_size
		lowerCAmelCase					:    List[Any]      							= type_sequence_label_size
		lowerCAmelCase					:    List[str]      							= initializer_range
		lowerCAmelCase					:    Optional[Any]      							= num_labels
		lowerCAmelCase					:    Any      							= num_choices
		lowerCAmelCase					:    Optional[int]      							= scope
		lowerCAmelCase					:    Any      							= projection_dim



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size    )

		lowerCAmelCase					:    Optional[Any]      							= None
		if self.use_input_mask:
			# follow test_modeling_tf_ctrl.py
			lowerCAmelCase					:    Union[str, Any]      							= random_attention_mask([self.batch_size, self.seq_length]    )

		lowerCAmelCase					:    Dict      							= None
		if self.use_token_type_ids:
			lowerCAmelCase					:    Optional[int]      							= ids_tensor([self.batch_size, self.seq_length] ,					self.type_vocab_size    )

		lowerCAmelCase					:    Union[str, Any]      							= None
		lowerCAmelCase					:    Tuple      							= None
		lowerCAmelCase					:    Any      							= None
		if self.use_labels:
			lowerCAmelCase					:    Dict      							= ids_tensor([self.batch_size] ,					self.type_sequence_label_size    )
			lowerCAmelCase					:    Any      							= ids_tensor([self.batch_size, self.seq_length] ,					self.num_labels    )
			lowerCAmelCase					:    Dict      							= ids_tensor([self.batch_size] ,					self.num_choices    )

		lowerCAmelCase					:    List[Any]      							= BertConfig(
		    vocab_size=self.vocab_size ,					hidden_size=self.hidden_size ,					num_hidden_layers=self.num_hidden_layers ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					hidden_act=self.hidden_act ,					hidden_dropout_prob=self.hidden_dropout_prob ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob ,					max_position_embeddings=self.max_position_embeddings ,					type_vocab_size=self.type_vocab_size ,					is_decoder=snake_case__ ,					initializer_range=self.initializer_range ,					)
		lowerCAmelCase					:    int      							= DPRConfig(projection_dim=self.projection_dim ,					**config.to_dict()    )

		return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__    ):
		lowerCAmelCase					:    str      							= TFDPRContextEncoder(config=snake_case__    )
		lowerCAmelCase					:    str      							= model(snake_case__ ,					attention_mask=snake_case__ ,					token_type_ids=snake_case__    )
		lowerCAmelCase					:    Union[str, Any]      							= model(snake_case__ ,					token_type_ids=snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= model(snake_case__    )
		self.parent.assertEqual(result.pooler_output.shape ,					(self.batch_size, self.projection_dim or self.hidden_size)    )



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__    ):
		lowerCAmelCase					:    int      							= TFDPRQuestionEncoder(config=snake_case__    )
		lowerCAmelCase					:    List[Any]      							= model(snake_case__ ,					attention_mask=snake_case__ ,					token_type_ids=snake_case__    )
		lowerCAmelCase					:    str      							= model(snake_case__ ,					token_type_ids=snake_case__    )
		lowerCAmelCase					:    Tuple      							= model(snake_case__    )
		self.parent.assertEqual(result.pooler_output.shape ,					(self.batch_size, self.projection_dim or self.hidden_size)    )



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__ ,					snake_case__    ):
		lowerCAmelCase					:    List[str]      							= TFDPRReader(config=snake_case__    )
		lowerCAmelCase					:    Tuple      							= model(snake_case__ ,					attention_mask=snake_case__    )

		self.parent.assertEqual(result.start_logits.shape ,					(self.batch_size, self.seq_length)    )
		self.parent.assertEqual(result.end_logits.shape ,					(self.batch_size, self.seq_length)    )
		self.parent.assertEqual(result.relevance_logits.shape ,					(self.batch_size,)    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= self.prepare_config_and_inputs()
		(
		    lowerCAmelCase	
		)					:    Tuple      							= config_and_inputs
		lowerCAmelCase					:    Optional[Any]      							= {'''input_ids''': input_ids}
		return config, inputs_dict



@require_tf
class  lowerCAmelCase				(				UpperCamelCase_      ,				UpperCamelCase_      ,				unittest.TestCase							):
	_lowerCamelCase   :					Any			      = (
	    (
	        TFDPRContextEncoder,
	        TFDPRQuestionEncoder,
	        TFDPRReader,
	    )
	    if is_tf_available()
	    else ()
	)
	_lowerCamelCase   :					Any			      = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

	_lowerCamelCase   :					Optional[Any]			      = False
	_lowerCamelCase   :					List[str]			      = False
	_lowerCamelCase   :					Optional[Any]			      = False
	_lowerCamelCase   :					str			      = False
	_lowerCamelCase   :					Optional[int]			      = False



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= TFDPRModelTester(self    )
		lowerCAmelCase					:    List[str]      							= ConfigTester(self ,					config_class=snake_case__ ,					hidden_size=37    )



	def 				lowercase     (					self    ):
		self.config_tester.run_common_tests()



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_dpr_context_encoder(*snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    int      							= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_dpr_question_encoder(*snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[Any]      							= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_dpr_reader(*snake_case__    )



	@slow
	def 				lowercase     (					self    ):
		for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			lowerCAmelCase					:    List[str]      							= TFDPRContextEncoder.from_pretrained(snake_case__    )
			self.assertIsNotNone(snake_case__    )

		for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			lowerCAmelCase					:    Dict      							= TFDPRContextEncoder.from_pretrained(snake_case__    )
			self.assertIsNotNone(snake_case__    )

		for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			lowerCAmelCase					:    List[str]      							= TFDPRQuestionEncoder.from_pretrained(snake_case__    )
			self.assertIsNotNone(snake_case__    )

		for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			lowerCAmelCase					:    Union[str, Any]      							= TFDPRReader.from_pretrained(snake_case__    )
			self.assertIsNotNone(snake_case__    )



@require_tf
class  lowerCAmelCase				(				unittest.TestCase							):



	@slow
	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'    )

		lowerCAmelCase					:    List[Any]      							= tf.constant(
		    [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]    )  # [CLS] hello, is my dog cute? [SEP]
		lowerCAmelCase					:    Tuple      							= model(snake_case__    )[0]  # embedding shape = (1, 768)
		# compare the actual values for a slice.
		lowerCAmelCase					:    Any      							= tf.constant(
		    [
		        [
		            0.0_3_2_3_6_2_5_3,
		            0.1_2_7_5_3_3_3_5,
		            0.1_6_8_1_8_5_0_9,
		            0.0_0_2_7_9_7_8_6,
		            0.3_8_9_6_9_3_3,
		            0.2_4_2_6_4_9_4_5,
		            0.2_1_7_8_9_7_1,
		            -0.0_2_3_3_5_2_2_7,
		            -0.0_8_4_8_1_9_5_9,
		            -0.1_4_3_2_4_1_1_7,
		        ]
		    ]    )
		self.assertTrue(numpy.allclose(output[:, :10].numpy() ,					expected_slice.numpy() ,					atol=1e-4    )    )




'''simple docstring'''




import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


_lowerCAmelCase  :		List[Any]		     =	logging.getLogger(__name__)

def 			__UpperCamelCase    (    )    ->      Any:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= argparse.ArgumentParser(
	    description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.'				)
	parser.add_argument(
	    '--dataset_name'					,   type=_A					,   default='wikitext'					,   help='Name of the training. Explore datasets at: hf.co/datasets.'					,   )
	parser.add_argument(
	    '--dataset_config'					,   type=_A					,   default='wikitext-103-raw-v1'					,   help='Configuration name of the dataset.'				)
	parser.add_argument(
	    '--tokenizer_name_or_path'					,   type=_A					,   default='sayakpaul/unigram-tokenizer-wikitext'					,   help='Tokenizer identifier. Can be a local filepath or a Hub identifier.'					,   )
	parser.add_argument(
	    '--shard_size'					,   type=_A					,   default=10_00					,   help='Number of entries to go in a single shard.'					,   )
	parser.add_argument('--split'					,   type=_A					,   default='train'					,   choices=['train', 'test', 'validation']				)
	parser.add_argument(
	    '--limit'					,   default=_A					,   type=_A					,   help='Limit the number of shards (used for debugging).'					,   )
	parser.add_argument(
	    '--max_length'					,   type=_A					,   default=5_12					,   help='Maximum sequence length. For training on TPUs, it helps to have a maximum'
	    ' sequence length that is a multiple of 8.'					,   )
	parser.add_argument(
	    '--output_dir'					,   default='tf-tpu'					,   type=_A					,   help='Output directory where the TFRecord shards will be saved. If the'
	    ' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord'
	    ' shards will be directly saved to a Google Cloud Storage bucket.'					,   )

	lowerCAmelCase					:    Any      							= parser.parse_args()
	return args

def 			__UpperCamelCase    (    _A    :				Optional[int]				)    ->      int:




	"""simple docstring"""





	def fn(_A    :				Tuple				):
		return tokenizer(examples['text']				)

	return fn

def 			__UpperCamelCase    (    _A    :				int				)    ->      int:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= []
	for i in range(len(tokenized_data['input_ids']				)				):
		lowerCAmelCase					:    Optional[Any]      							= {
		    'input_ids': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['input_ids'][i]				)				),
		    'attention_mask': tf.train.Feature(
		        intaa_list=tf.train.IntaaList(value=tokenized_data['attention_mask'][i]				)				),
		}
		lowerCAmelCase					:    Any      							= tf.train.Features(feature=_A				)
		lowerCAmelCase					:    List[str]      							= tf.train.Example(features=_A				)
		lowerCAmelCase					:    Tuple      							= example.SerializeToString()
		records.append(_A				)
	return records

def 			__UpperCamelCase    (    _A    :				int				)    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Union[str, Any]      							= datasets.load_dataset(args.dataset_name					,   args.dataset_config					,   split=args.split				)

	if args.limit is not None:
		lowerCAmelCase					:    Optional[Any]      							= min(len(_A				)					,   args.limit				)
		lowerCAmelCase					:    Dict      							= dataset.select(range(_A				)				)
		print(F"Limiting the dataset to {args.limit} entries."				)

	lowerCAmelCase					:    str      							= AutoTokenizer.from_pretrained(args.tokenizer_name_or_path				)

	# Handle output directory creation.
	# For serializing into a Google Cloud Storage Bucket, one needs to first
	# create a bucket.
	if "gs" not in args.output_dir:
		if not os.path.exists(args.output_dir				):
			os.makedirs(args.output_dir				)
		lowerCAmelCase					:    Any      							= os.path.join(args.output_dir					,   args.split				)
		if not os.path.exists(_A				):
			os.makedirs(_A				)
	else:
		lowerCAmelCase					:    List[Any]      							= os.path.join(args.output_dir					,   args.split				)

	# Tokenize the whole dataset at once.
	lowerCAmelCase					:    Any      							= tokenize_function(_A				)
	lowerCAmelCase					:    Optional[int]      							= dataset.map(_A					,   batched=_A					,   num_proc=4					,   remove_columns=['text']				)

	# We need to concatenate all our texts together, and then split the result
	# into chunks of a fixed size, which we will call block_size. To do this, we
	# will use the map method again, with the option batched=True. When we use batched=True,
	# the function we pass to map() will be passed multiple inputs at once, allowing us
	# to group them into more or fewer examples than we had in the input.
	# This allows us to create our new fixed-length samples. The advantage of this
	# method is that we don't lose a whole lot of content from the dataset compared to the
	# case where we simply tokenize with a pre-defined max_length.

	def group_texts(_A    :				str				):
		# Concatenate all texts.
		lowerCAmelCase					:    Optional[int]      							= {k: sum(examples[k]					,   []				) for k in examples.keys()}
		lowerCAmelCase					:    str      							= len(concatenated_examples[list(examples.keys()				)[0]]				)
		# We drop the small remainder, though you could add padding instead if the model supports it
		# In this, as in all things, we advise you to follow your heart 🫀
		lowerCAmelCase					:    List[Any]      							= (total_length // args.max_length) * args.max_length
		# Split by chunks of max_len.
		lowerCAmelCase					:    str      							= {
		    k: [t[i : i + args.max_length] for i in range(0					,   _A					,   args.max_length				)]
		    for k, t in concatenated_examples.items()
		}
		return result

	lowerCAmelCase					:    List[Any]      							= dataset_tokenized.map(_A					,   batched=_A					,   batch_size=10_00					,   num_proc=4				)

	lowerCAmelCase					:    Union[str, Any]      							= 0
	lowerCAmelCase					:    Tuple      							= 0
	for shard in range(0					,   len(_A				)					,   args.shard_size				):
		lowerCAmelCase					:    Optional[Any]      							= grouped_dataset[shard : shard + args.shard_size]
		lowerCAmelCase					:    List[str]      							= len(dataset_snapshot['input_ids']				)
		lowerCAmelCase					:    Union[str, Any]      							= os.path.join(_A					,   F"dataset-{shard_count}-{records_containing}.tfrecord"				)
		lowerCAmelCase					:    List[Any]      							= get_serialized_examples(_A				)

		with tf.io.TFRecordWriter(_A				) as out_file:
			for i in range(len(_A				)				):
				lowerCAmelCase					:    Union[str, Any]      							= serialized_examples[i]
				out_file.write(_A				)
			print('Wrote file {} containing {} records'.format(_A					,   _A				)				)

		shard_count += 1
		total_records += records_containing

	with open(F"split-{args.split}-records-count.txt"					,   'w'				) as f:
		print(F"Total {args.split} records: {total_records}"					,   file=_A				)


if __name__ == "__main__":
				_lowerCAmelCase  :		List[Any]		     =	parse_args()
				main(args)
