



import unittest

import numpy as np

from transformers import ElectraConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
						from transformers.models.electra.modeling_flax_electra import (
						    FlaxElectraForCausalLM,
						    FlaxElectraForMaskedLM,
						    FlaxElectraForMultipleChoice,
						    FlaxElectraForPreTraining,
						    FlaxElectraForQuestionAnswering,
						    FlaxElectraForSequenceClassification,
						    FlaxElectraForTokenClassification,
						    FlaxElectraModel,
						)






class 				SCREAMING_SNAKE_CASE     (							unittest.TestCase   ):





							def __init__(				self						:						Union[str, Any] ,			__lowercase						:						Any ,			__lowercase						:						Dict=13 ,			__lowercase						:						Tuple=7 ,			__lowercase						:						Dict=True ,			__lowercase						:						int=True ,			__lowercase						:						Union[str, Any]=True ,			__lowercase						:						Any=True ,			__lowercase						:						Union[str, Any]=99 ,			__lowercase						:						Union[str, Any]=24 ,			__lowercase						:						List[str]=32 ,			__lowercase						:						int=5 ,			__lowercase						:						Tuple=4 ,			__lowercase						:						Union[str, Any]=37 ,			__lowercase						:						Dict="gelu" ,			__lowercase						:						Optional[int]=0.1 ,			__lowercase						:						Dict=0.1 ,			__lowercase						:						Any=512 ,			__lowercase						:						Tuple=16 ,			__lowercase						:						Any=2 ,			__lowercase						:						Union[str, Any]=0.02 ,			__lowercase						:						Any=4 ,			):

											'''simple docstring'''
											__a					       =						parent
											__a					       =						batch_size
											__a					       =						seq_length
											__a					       =						is_training
											__a					       =						use_attention_mask
											__a					       =						use_token_type_ids
											__a					       =						use_labels
											__a					       =						vocab_size
											__a					       =						hidden_size
											__a					       =						embedding_size
											__a					       =						num_hidden_layers
											__a					       =						num_attention_heads
											__a					       =						intermediate_size
											__a					       =						hidden_act
											__a					       =						hidden_dropout_prob
											__a					       =						attention_probs_dropout_prob
											__a					       =						max_position_embeddings
											__a					       =						type_vocab_size
											__a					       =						type_sequence_label_size
											__a					       =						initializer_range
											__a					       =						num_choices





							def   UpperCamelCase_   (				self						:						int		):

											'''simple docstring'''
											__a					       =						ids_tensor([self.batch_size, self.seq_length] ,			self.vocab_size		)

											__a					       =						None
											if self.use_attention_mask:
															__a					       =						random_attention_mask([self.batch_size, self.seq_length]		)

											__a					       =						None
											if self.use_token_type_ids:
															__a					       =						ids_tensor([self.batch_size, self.seq_length] ,			self.type_vocab_size		)

											__a					       =						ElectraConfig(
											    vocab_size=self.vocab_size ,			hidden_size=self.hidden_size ,			embedding_size=self.embedding_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 ,			initializer_range=self.initializer_range ,			)

											return config, input_ids, token_type_ids, attention_mask







							def   UpperCamelCase_   (				self						:						Optional[Any]		):

											'''simple docstring'''
											__a					       =						self.prepare_config_and_inputs()
											__a       ,   __a       ,   __a       ,   __a					       =						config_and_inputs
											__a					       =						{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
											return config, inputs_dict






@require_flax
class 				SCREAMING_SNAKE_CASE     (							lowerCamelCase__     , unittest.TestCase   ):
							__lowerCamelCase		:		Tuple      =True

							__lowerCamelCase		:		str      =(
							    (
							        FlaxElectraModel,
							        FlaxElectraForCausalLM,
							        FlaxElectraForMaskedLM,
							        FlaxElectraForPreTraining,
							        FlaxElectraForTokenClassification,
							        FlaxElectraForQuestionAnswering,
							        FlaxElectraForMultipleChoice,
							        FlaxElectraForSequenceClassification,
							    )
							    if is_flax_available()
							    else ()
							)





							def   UpperCamelCase_   (				self						:						Dict		):

											'''simple docstring'''
											__a					       =						FlaxElectraModelTester(self		)







							@slow
							def   UpperCamelCase_   (				self						:						Optional[int]		):

											'''simple docstring'''
											for model_class_name in self.all_model_classes:
															if model_class_name == FlaxElectraForMaskedLM:
																			__a					       =						model_class_name.from_pretrained("""google/electra-small-generator"""		)
															else:
																			__a					       =						model_class_name.from_pretrained("""google/electra-small-discriminator"""		)
															__a					       =						model(np.ones((1, 1)		)		)
															self.assertIsNotNone(__lowercase		)





#
# Sort large text files in a minimum amount of memory
#
import argparse
import os






class 				SCREAMING_SNAKE_CASE     :
							__lowerCamelCase		:		Tuple      ='block_{0}.dat'





							def __init__(				self						:						int ,			__lowercase						:						Dict		):

											'''simple docstring'''
											__a					       =						filename
											__a					       =						[]





							def   UpperCamelCase_   (				self						:						int ,			__lowercase						:						Dict ,			__lowercase						:						Optional[Any]		):

											'''simple docstring'''
											__a					       =						self.BLOCK_FILENAME_FORMAT.format(__lowercase		)
											with open(__lowercase ,			"""w"""		) as file:
															file.write(__lowercase		)
											self.block_filenames.append(__lowercase		)





							def   UpperCamelCase_   (				self						:						List[str]		):

											'''simple docstring'''
											return self.block_filenames





							def   UpperCamelCase_   (				self						:						Any ,			__lowercase						:						str ,			__lowercase						:						Tuple=None		):

											'''simple docstring'''
											__a					       =						0
											with open(self.filename		) as file:
															while True:
																			__a					       =						file.readlines(__lowercase		)

																			if lines == []:
																							break

																			if sort_key is None:
																							lines.sort()
																			else:
																							lines.sort(key=__lowercase		)

																			self.write_block("""""".join(__lowercase		) ,			__lowercase		)
																			i += 1







							def   UpperCamelCase_   (				self						:						List[Any]		):

											'''simple docstring'''
											map(os.remove ,			self.block_filenames		)






class 				SCREAMING_SNAKE_CASE     :





							def   UpperCamelCase_   (				self						:						Dict ,			__lowercase						:						Optional[Any]		):

											'''simple docstring'''
											__a					       =						-1
											__a					       =						None

											for i in range(len(__lowercase		)		):
															if min_str is None or choices[i] < min_str:
																			__a					       =						i

											return min_index






class 				SCREAMING_SNAKE_CASE     :





							def __init__(				self						:						Optional[int] ,			__lowercase						:						Optional[Any]		):

											'''simple docstring'''
											__a					       =						files
											__a					       =						set()
											__a					       =						len(__lowercase		)
											__a					       =						{i: None for i in range(self.num_buffers		)}





							def   UpperCamelCase_   (				self						:						int		):

											'''simple docstring'''
											return {
											    i: self.buffers[i] for i in range(self.num_buffers		) if i not in self.empty
											}





							def   UpperCamelCase_   (				self						:						List[str]		):

											'''simple docstring'''
											for i in range(self.num_buffers		):
															if self.buffers[i] is None and i not in self.empty:
																			__a					       =						self.files[i].readline()

																			if self.buffers[i] == "":
																							self.empty.add(__lowercase		)
																							self.files[i].close()

											if len(self.empty		) == self.num_buffers:
															return False

											return True







							def   UpperCamelCase_   (				self						:						List[str] ,			__lowercase						:						List[Any]		):

											'''simple docstring'''
											__a					       =						self.buffers[index]
											__a					       =						None

											return value






class 				SCREAMING_SNAKE_CASE     :





							def __init__(				self						:						Optional[int] ,			__lowercase						:						Any		):

											'''simple docstring'''
											__a					       =						merge_strategy





							def   UpperCamelCase_   (				self						:						str ,			__lowercase						:						Union[str, Any] ,			__lowercase						:						List[str] ,			__lowercase						:						Dict		):

											'''simple docstring'''
											__a					       =						FilesArray(self.get_file_handles(__lowercase ,			__lowercase		)		)
											with open(__lowercase ,			"""w""" ,			__lowercase		) as outfile:
															while buffers.refresh():
																			__a					       =						self.merge_strategy.select(buffers.get_dict()		)
																			outfile.write(buffers.unshift(__lowercase		)		)







							def   UpperCamelCase_   (				self						:						List[Any] ,			__lowercase						:						str ,			__lowercase						:						Dict		):

											'''simple docstring'''
											__a					       =						{}

											for i in range(len(__lowercase		)		):
															__a					       =						open(filenames[i] ,			"""r""" ,			__lowercase		)  # noqa: UP015

											return files






class 				SCREAMING_SNAKE_CASE     :





							def __init__(				self						:						str ,			__lowercase						:						Tuple		):

											'''simple docstring'''
											__a					       =						block_size





							def   UpperCamelCase_   (				self						:						Tuple ,			__lowercase						:						str ,			__lowercase						:						Union[str, Any]=None		):

											'''simple docstring'''
											__a					       =						self.get_number_blocks(__lowercase ,			self.block_size		)
											__a					       =						FileSplitter(__lowercase		)
											splitter.split(self.block_size ,			__lowercase		)

											__a					       =						FileMerger(NWayMerge()		)
											__a					       =						self.block_size / (num_blocks + 1)
											merger.merge(splitter.get_block_filenames() ,			filename + """.out""" ,			__lowercase		)

											splitter.cleanup()







							def   UpperCamelCase_   (				self						:						str ,			__lowercase						:						Optional[Any] ,			__lowercase						:						Dict		):

											'''simple docstring'''
											return (os.stat(__lowercase		).st_size / block_size) + 1



def 					lowerCAmelCase__  (							_SCREAMING_SNAKE_CASE    :     Tuple      ):
				"""simple docstring"""







				if string[-1].lower() == "k":
								return int(string[:-1]      ) * 1024
				elif string[-1].lower() == "m":
								return int(string[:-1]      ) * 1024 * 1024
				elif string[-1].lower() == "g":
								return int(string[:-1]      ) * 1024 * 1024 * 1024
				else:
								return int(_SCREAMING_SNAKE_CASE      )

def 					lowerCAmelCase__  (							):
				"""simple docstring"""







				__a					       =						argparse.ArgumentParser()
				parser.add_argument(
				    """-m"""			,       """--mem"""			,       help="""amount of memory to use for sorting"""			,       default="""100M"""      )
				parser.add_argument(
				    """filename"""			,       metavar="""<filename>"""			,       nargs=1			,       help="""name of file to sort"""      )
				__a					       =						parser.parse_args()

				__a					       =						ExternalSort(parse_memory(args.mem      )      )
				sorter.sort(args.filename[0]      )


if __name__ == "__main__":
						main()
