




"""simple docstring"""

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
				import tensorflow as tf

				from transformers.models.swin.modeling_tf_swin import (
				    TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFSwinForImageClassification,
				    TFSwinForMaskedImageModeling,
				    TFSwinModel,
				)


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor



class  _snake_case				:

				'''simple docstring'''




				def __init__(							self      :  Optional[int]					,							snake_case      :  List[str]					,							snake_case      :  str=13					,							snake_case      :  int=32					,							snake_case      :  Optional[int]=2					,							snake_case      :  Dict=3					,							snake_case      :  str=16					,							snake_case      :  int=[1, 2, 1]					,							snake_case      :  Tuple=[2, 2, 4]					,							snake_case      :  str=2					,							snake_case      :  Dict=2.0					,							snake_case      :  int=True					,							snake_case      :  str=0.0					,							snake_case      :  Any=0.0					,							snake_case      :  Tuple=0.1					,							snake_case      :  str="gelu"					,							snake_case      :  Optional[Any]=False					,							snake_case      :  List[str]=True					,							snake_case      :  List[Any]=0.02					,							snake_case      :  Union[str, Any]=1e-5					,							snake_case      :  str=True					,							snake_case      :  Dict=None					,							snake_case      :  str=True					,							snake_case      :  List[str]=10					,							snake_case      :  str=8					,							):
								UpperCAmelCase_					:List[str]      			=      parent
								UpperCAmelCase_					:Any      			=      batch_size
								UpperCAmelCase_					:Any      			=      image_size
								UpperCAmelCase_					:Optional[Any]      			=      patch_size
								UpperCAmelCase_					:Dict      			=      num_channels
								UpperCAmelCase_					:Any      			=      embed_dim
								UpperCAmelCase_					:Dict      			=      depths
								UpperCAmelCase_					:Optional[int]      			=      num_heads
								UpperCAmelCase_					:Optional[int]      			=      window_size
								UpperCAmelCase_					:List[str]      			=      mlp_ratio
								UpperCAmelCase_					:List[str]      			=      qkv_bias
								UpperCAmelCase_					:Union[str, Any]      			=      hidden_dropout_prob
								UpperCAmelCase_					:Dict      			=      attention_probs_dropout_prob
								UpperCAmelCase_					:Tuple      			=      drop_path_rate
								UpperCAmelCase_					:Tuple      			=      hidden_act
								UpperCAmelCase_					:List[str]      			=      use_absolute_embeddings
								UpperCAmelCase_					:Optional[Any]      			=      patch_norm
								UpperCAmelCase_					:List[Any]      			=      layer_norm_eps
								UpperCAmelCase_					:Any      			=      initializer_range
								UpperCAmelCase_					:Tuple      			=      is_training
								UpperCAmelCase_					:Dict      			=      scope
								UpperCAmelCase_					:Optional[int]      			=      use_labels
								UpperCAmelCase_					:Tuple      			=      type_sequence_label_size
								UpperCAmelCase_					:Optional[int]      			=      encoder_stride





				def 				snake_case_ (							self      :  str     ):
								UpperCAmelCase_					:Optional[Any]      			=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

								UpperCAmelCase_					:Optional[int]      			=      None
								if self.use_labels:
												UpperCAmelCase_					:Optional[int]      			=      ids_tensor([self.batch_size]					,							self.type_sequence_label_size     )

								UpperCAmelCase_					:str      			=      self.get_config()

								return config, pixel_values, labels





				def 				snake_case_ (							self      :  Optional[Any]     ):
								return SwinConfig(
								    image_size=self.image_size					,							patch_size=self.patch_size					,							num_channels=self.num_channels					,							embed_dim=self.embed_dim					,							depths=self.depths					,							num_heads=self.num_heads					,							window_size=self.window_size					,							mlp_ratio=self.mlp_ratio					,							qkv_bias=self.qkv_bias					,							hidden_dropout_prob=self.hidden_dropout_prob					,							attention_probs_dropout_prob=self.attention_probs_dropout_prob					,							drop_path_rate=self.drop_path_rate					,							hidden_act=self.hidden_act					,							use_absolute_embeddings=self.use_absolute_embeddings					,							path_norm=self.patch_norm					,							layer_norm_eps=self.layer_norm_eps					,							initializer_range=self.initializer_range					,							encoder_stride=self.encoder_stride					,							)





				def 				snake_case_ (							self      :  List[Any]					,							snake_case      :  List[Any]					,							snake_case      :  Dict					,							snake_case      :  List[str]     ):
								UpperCAmelCase_					:List[str]      			=      TFSwinModel(config=UpperCAmelCase_     )
								UpperCAmelCase_					:Any      			=      model(UpperCAmelCase_     )

								UpperCAmelCase_					:List[Any]      			=      ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths     ) - 1))
								UpperCAmelCase_					:Union[str, Any]      			=      int(config.embed_dim * 2 ** (len(config.depths     ) - 1)     )

								self.parent.assertEqual(result.last_hidden_state.shape					,							(self.batch_size, expected_seq_len, expected_dim)     )





				def 				snake_case_ (							self      :  Dict					,							snake_case      :  Optional[Any]					,							snake_case      :  Optional[Any]					,							snake_case      :  List[str]     ):
								UpperCAmelCase_					:str      			=      TFSwinForMaskedImageModeling(config=UpperCAmelCase_     )
								UpperCAmelCase_					:Optional[Any]      			=      model(UpperCAmelCase_     )
								self.parent.assertEqual(
								    result.logits.shape					,							(self.batch_size, self.num_channels, self.image_size, self.image_size)     )

								# test greyscale images
								UpperCAmelCase_					:int      			=      1
								UpperCAmelCase_					:List[Any]      			=      TFSwinForMaskedImageModeling(UpperCAmelCase_     )

								UpperCAmelCase_					:Dict      			=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
								UpperCAmelCase_					:Tuple      			=      model(UpperCAmelCase_     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, 1, self.image_size, self.image_size)     )





				def 				snake_case_ (							self      :  Tuple					,							snake_case      :  str					,							snake_case      :  Optional[Any]					,							snake_case      :  str     ):
								UpperCAmelCase_					:List[Any]      			=      self.type_sequence_label_size
								UpperCAmelCase_					:Optional[Any]      			=      TFSwinForImageClassification(UpperCAmelCase_     )
								UpperCAmelCase_					:List[str]      			=      model(UpperCAmelCase_					,							labels=UpperCAmelCase_     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.type_sequence_label_size)     )

								# test greyscale images
								UpperCAmelCase_					:Any      			=      1
								UpperCAmelCase_					:Optional[int]      			=      TFSwinForImageClassification(UpperCAmelCase_     )
								UpperCAmelCase_					:Optional[Any]      			=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
								UpperCAmelCase_					:Dict      			=      model(UpperCAmelCase_     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.type_sequence_label_size)     )





				def 				snake_case_ (							self      :  Dict     ):
								UpperCAmelCase_					:Union[str, Any]      			=      self.prepare_config_and_inputs()
								UpperCAmelCase_					:List[Any]      			=      config_and_inputs
								UpperCAmelCase_					:Optional[Any]      			=      {'pixel_values': pixel_values}
								return config, inputs_dict



@require_tf
class  _snake_case				(							A__							,						A__							,						unittest.TestCase       ):

				'''simple docstring'''




				UpperCamelCase__		     =(
				    (
				        TFSwinModel,
				        TFSwinForImageClassification,
				        TFSwinForMaskedImageModeling,
				    )
				    if is_tf_available()
				    else ()
				)
				UpperCamelCase__		     =(
				    {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification}
				    if is_tf_available()
				    else {}
				)

				UpperCamelCase__		     =False
				UpperCamelCase__		     =False
				UpperCamelCase__		     =False
				UpperCamelCase__		     =False





				def 				snake_case_ (							self      :  List[str]     ):
								UpperCAmelCase_					:Optional[int]      			=      TFSwinModelTester(self     )
								UpperCAmelCase_					:Any      			=      ConfigTester(self					,							config_class=UpperCAmelCase_					,							embed_dim=37     )





				def 				snake_case_ (							self      :  Union[str, Any]     ):
								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()





				def 				snake_case_ (							self      :  Tuple     ):
								return





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*UpperCAmelCase_     )





				def 				snake_case_ (							self      :  Union[str, Any]     ):
								UpperCAmelCase_					:str      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase_     )





				def 				snake_case_ (							self      :  int     ):
								UpperCAmelCase_					:int      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_     )





				@unittest.skip(reason='''Swin does not use inputs_embeds'''     )
				def 				snake_case_ (							self      :  List[Any]     ):
								pass





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:Any      			=      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												UpperCAmelCase_					:int      			=      model_class(UpperCAmelCase_     )
												self.assertIsInstance(model.get_input_embeddings()					,							tf.keras.layers.Layer     )
												UpperCAmelCase_					:Tuple      			=      model.get_output_embeddings()
												self.assertTrue(x is None or isinstance(UpperCAmelCase_					,							tf.keras.layers.Dense     )     )





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												UpperCAmelCase_					:List[str]      			=      model_class(UpperCAmelCase_     )
												UpperCAmelCase_					:Union[str, Any]      			=      inspect.signature(model.call     )
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												UpperCAmelCase_					:List[str]      			=      [*signature.parameters.keys()]

												UpperCAmelCase_					:Optional[Any]      			=      ['pixel_values']
												self.assertListEqual(arg_names[:1]					,							UpperCAmelCase_     )





				def 				snake_case_ (							self      :  Dict     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase_					:str      			=      True

								for model_class in self.all_model_classes:
												UpperCAmelCase_					:str      			=      True
												UpperCAmelCase_					:str      			=      False
												UpperCAmelCase_					:Optional[int]      			=      True
												UpperCAmelCase_					:List[Any]      			=      model_class(UpperCAmelCase_     )
												UpperCAmelCase_					:Optional[Any]      			=      model(**self._prepare_for_class(UpperCAmelCase_					,							UpperCAmelCase_     )     )
												UpperCAmelCase_					:List[str]      			=      outputs.attentions
												UpperCAmelCase_					:Optional[Any]      			=      len(self.model_tester.depths     )
												self.assertEqual(len(UpperCAmelCase_     )					,							UpperCAmelCase_     )

												# check that output_attentions also work using config
												del inputs_dict["output_attentions"]
												UpperCAmelCase_					:Dict      			=      True
												UpperCAmelCase_					:int      			=      config.window_size**2
												UpperCAmelCase_					:List[Any]      			=      model_class(UpperCAmelCase_     )
												UpperCAmelCase_					:Tuple      			=      model(**self._prepare_for_class(UpperCAmelCase_					,							UpperCAmelCase_     )     )
												UpperCAmelCase_					:int      			=      outputs.attentions
												self.assertEqual(len(UpperCAmelCase_     )					,							UpperCAmelCase_     )

												self.assertListEqual(
												    list(attentions[0].shape[-3:]     )					,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,							)
												UpperCAmelCase_					:int      			=      len(UpperCAmelCase_     )

												# Check attention is always last and order is fine
												UpperCAmelCase_					:Union[str, Any]      			=      True
												UpperCAmelCase_					:str      			=      True
												UpperCAmelCase_					:int      			=      model_class(UpperCAmelCase_     )
												UpperCAmelCase_					:Optional[int]      			=      model(**self._prepare_for_class(UpperCAmelCase_					,							UpperCAmelCase_     )     )

												if hasattr(self.model_tester					,							'''num_hidden_states_types'''     ):
																UpperCAmelCase_					:int      			=      self.model_tester.num_hidden_states_types
												else:
																# also another +1 for reshaped_hidden_states
																UpperCAmelCase_					:Optional[int]      			=      2
												self.assertEqual(out_len + added_hidden_states					,							len(UpperCAmelCase_     )     )

												UpperCAmelCase_					:List[Any]      			=      outputs.attentions

												self.assertEqual(len(UpperCAmelCase_     )					,							UpperCAmelCase_     )

												self.assertListEqual(
												    list(self_attentions[0].shape[-3:]     )					,							[self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,							)





				def 				snake_case_ (							self      :  Optional[Any]					,							snake_case      :  int					,							snake_case      :  Tuple					,							snake_case      :  Optional[Any]					,							snake_case      :  Union[str, Any]     ):
								UpperCAmelCase_					:List[str]      			=      model_class(UpperCAmelCase_     )
								UpperCAmelCase_					:Optional[Any]      			=      model(**self._prepare_for_class(UpperCAmelCase_					,							UpperCAmelCase_     )     )
								UpperCAmelCase_					:Tuple      			=      outputs.hidden_states

								UpperCAmelCase_					:List[str]      			=      getattr(
								    self.model_tester					,							'''expected_num_hidden_layers'''					,							len(self.model_tester.depths     ) + 1     )
								self.assertEqual(len(UpperCAmelCase_     )					,							UpperCAmelCase_     )

								# Swin has a different seq_length
								UpperCAmelCase_					:str      			=      to_atuple(config.patch_size     )

								UpperCAmelCase_					:Tuple      			=      (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]     )					,							[num_patches, self.model_tester.embed_dim]					,							)

								UpperCAmelCase_					:List[Any]      			=      outputs.reshaped_hidden_states
								self.assertEqual(len(UpperCAmelCase_     )					,							UpperCAmelCase_     )

								UpperCAmelCase_					:Tuple      			=      reshaped_hidden_states[0].shape

								UpperCAmelCase_					:Optional[Any]      			=      tf.reshape(reshaped_hidden_states[0]					,							(batch_size, num_channels, height * width)     )
								UpperCAmelCase_					:Tuple      			=      tf.transpose(UpperCAmelCase_					,							(0, 2, 1)     )

								self.assertListEqual(
								    list(reshaped_hidden_states.shape[-2:]     )					,							[num_patches, self.model_tester.embed_dim]					,							)





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:List[Any]      			=      self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase_					:Any      			=      to_atuple(self.model_tester.image_size     )

								for model_class in self.all_model_classes:
												UpperCAmelCase_					:Union[str, Any]      			=      True
												self.check_hidden_states_output(UpperCAmelCase_					,							UpperCAmelCase_					,							UpperCAmelCase_					,							UpperCAmelCase_     )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												UpperCAmelCase_					:Tuple      			=      True

												self.check_hidden_states_output(UpperCAmelCase_					,							UpperCAmelCase_					,							UpperCAmelCase_					,							UpperCAmelCase_     )





				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase_					:List[Any]      			=      3

								UpperCAmelCase_					:List[str]      			=      to_atuple(self.model_tester.image_size     )
								UpperCAmelCase_					:List[Any]      			=      to_atuple(config.patch_size     )

								UpperCAmelCase_					:str      			=      image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
								UpperCAmelCase_					:Any      			=      image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

								for model_class in self.all_model_classes:
												UpperCAmelCase_					:Optional[int]      			=      True
												self.check_hidden_states_output(UpperCAmelCase_					,							UpperCAmelCase_					,							UpperCAmelCase_					,							(padded_height, padded_width)     )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												UpperCAmelCase_					:int      			=      True
												self.check_hidden_states_output(UpperCAmelCase_					,							UpperCAmelCase_					,							UpperCAmelCase_					,							(padded_height, padded_width)     )





				@slow
				def 				snake_case_ (							self      :  Any     ):
								for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase_					:List[str]      			=      TFSwinModel.from_pretrained(UpperCAmelCase_     )
												self.assertIsNotNone(UpperCAmelCase_     )



@require_vision
@require_tf
class  _snake_case				(							unittest.TestCase       ):

				'''simple docstring'''




				@cached_property
				def 				snake_case_ (							self      :  Dict     ):
								return (
								    AutoImageProcessor.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''     )
								    if is_vision_available()
								    else None
								)





				@slow
				def 				snake_case_ (							self      :  Union[str, Any]     ):
								UpperCAmelCase_					:List[str]      			=      TFSwinForImageClassification.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''     )
								UpperCAmelCase_					:Optional[Any]      			=      self.default_image_processor

								UpperCAmelCase_					:Tuple      			=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
								UpperCAmelCase_					:List[Any]      			=      image_processor(images=UpperCAmelCase_					,							return_tensors='''tf'''     )

								# forward pass
								UpperCAmelCase_					:List[Any]      			=      model(UpperCAmelCase_     )

								# verify the logits
								UpperCAmelCase_					:Optional[Any]      			=      tf.TensorShape((1, 1_000)     )
								self.assertEqual(outputs.logits.shape					,							UpperCAmelCase_     )
								UpperCAmelCase_					:Any      			=      tf.constant([-0.0_948, -0.6_454, -0.0_921]     )
								self.assertTrue(np.allclose(outputs.logits[0, :3]					,							UpperCAmelCase_					,							atol=1e-4     )     )








"""simple docstring"""

import unittest

from transformers import ElectraConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_FOR_PRETRAINING_MAPPING,
						    ElectraForCausalLM,
						    ElectraForMaskedLM,
						    ElectraForMultipleChoice,
						    ElectraForPreTraining,
						    ElectraForQuestionAnswering,
						    ElectraForSequenceClassification,
						    ElectraForTokenClassification,
						    ElectraModel,
						)
						from transformers.models.electra.modeling_electra import ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST



class  _snake_case				:

				'''simple docstring'''




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





				def 				snake_case_ (							self      :  Tuple     ):
								UpperCAmelCase_					:str      			=      ids_tensor([self.batch_size, self.seq_length]					,							self.vocab_size     )

								UpperCAmelCase_					:Optional[int]      			=      None
								if self.use_input_mask:
												UpperCAmelCase_					:Any      			=      random_attention_mask([self.batch_size, self.seq_length]     )

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

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

								UpperCAmelCase_					:Dict      			=      self.get_config()

								return (
								    config,
								    input_ids,
								    token_type_ids,
								    input_mask,
								    sequence_labels,
								    token_labels,
								    choice_labels,
								    fake_token_labels,
								)





				def 				snake_case_ (							self      :  str     ):
								return ElectraConfig(
								    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					,							)





				def 				snake_case_ (							self      :  List[Any]     ):
								(
								    (
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,
								)					:str      			=      self.prepare_config_and_inputs()

								UpperCAmelCase_					:Union[str, Any]      			=      True
								UpperCAmelCase_					:Any      			=      floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
								UpperCAmelCase_					:str      			=      ids_tensor([self.batch_size, self.seq_length]					,							vocab_size=2     )

								return (
								    config,
								    input_ids,
								    token_type_ids,
								    input_mask,
								    sequence_labels,
								    token_labels,
								    choice_labels,
								    encoder_hidden_states,
								    encoder_attention_mask,
								)





				def 				snake_case_ (							self      :  Union[str, Any]					,							snake_case      :  Tuple					,							snake_case      :  Tuple					,							snake_case      :  List[str]					,							snake_case      :  int					,							snake_case      :  str					,							snake_case      :  Dict					,							snake_case      :  Any					,							snake_case      :  Union[str, Any]					,							):
								UpperCAmelCase_					:str      			=      ElectraModel(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:Dict      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case     )
								UpperCAmelCase_					:Tuple      			=      model(snake_case					,							token_type_ids=snake_case     )
								UpperCAmelCase_					:List[str]      			=      model(snake_case     )
								self.parent.assertEqual(result.last_hidden_state.shape					,							(self.batch_size, self.seq_length, self.hidden_size)     )





				def 				snake_case_ (							self      :  int					,							snake_case      :  Any					,							snake_case      :  Optional[Any]					,							snake_case      :  List[Any]					,							snake_case      :  Union[str, Any]					,							snake_case      :  Optional[Any]					,							snake_case      :  Optional[Any]					,							snake_case      :  List[Any]					,							snake_case      :  str					,							snake_case      :  Any					,							):
								UpperCAmelCase_					:Union[str, Any]      			=      True
								UpperCAmelCase_					:Optional[int]      			=      ElectraModel(snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:int      			=      model(
								    snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							encoder_hidden_states=snake_case					,							encoder_attention_mask=snake_case					,							)
								UpperCAmelCase_					:int      			=      model(
								    snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							encoder_hidden_states=snake_case					,							)
								UpperCAmelCase_					:List[str]      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case     )
								self.parent.assertEqual(result.last_hidden_state.shape					,							(self.batch_size, self.seq_length, self.hidden_size)     )





				def 				snake_case_ (							self      :  str					,							snake_case      :  Any					,							snake_case      :  Dict					,							snake_case      :  Optional[int]					,							snake_case      :  Optional[int]					,							snake_case      :  int					,							snake_case      :  List[str]					,							snake_case      :  List[Any]					,							snake_case      :  List[str]					,							):
								UpperCAmelCase_					:Tuple      			=      ElectraForMaskedLM(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:str      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.seq_length, self.vocab_size)     )





				def 				snake_case_ (							self      :  List[str]					,							snake_case      :  Dict					,							snake_case      :  Union[str, Any]					,							snake_case      :  Union[str, Any]					,							snake_case      :  Optional[Any]					,							snake_case      :  List[str]					,							snake_case      :  Optional[int]					,							snake_case      :  Union[str, Any]					,							snake_case      :  int					,							snake_case      :  Tuple					,							):
								UpperCAmelCase_					:str      			=      ElectraForCausalLM(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:Optional[Any]      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.seq_length, self.vocab_size)     )





				def 				snake_case_ (							self      :  int					,							snake_case      :  List[Any]					,							snake_case      :  List[str]					,							snake_case      :  Dict					,							snake_case      :  Optional[Any]					,							snake_case      :  Union[str, Any]					,							snake_case      :  Optional[Any]					,							snake_case      :  List[Any]					,							snake_case      :  List[str]					,							):
								UpperCAmelCase_					:Union[str, Any]      			=      self.num_labels
								UpperCAmelCase_					:Optional[int]      			=      ElectraForTokenClassification(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:List[str]      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.seq_length, self.num_labels)     )





				def 				snake_case_ (							self      :  Tuple					,							snake_case      :  Tuple					,							snake_case      :  int					,							snake_case      :  int					,							snake_case      :  Optional[Any]					,							snake_case      :  Optional[int]					,							snake_case      :  Union[str, Any]					,							snake_case      :  List[str]					,							snake_case      :  List[Any]					,							):
								UpperCAmelCase_					:List[str]      			=      self.num_labels
								UpperCAmelCase_					:Union[str, Any]      			=      ElectraForPreTraining(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:int      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.seq_length)     )





				def 				snake_case_ (							self      :  Dict					,							snake_case      :  Any					,							snake_case      :  List[Any]					,							snake_case      :  Optional[int]					,							snake_case      :  Optional[Any]					,							snake_case      :  Optional[int]					,							snake_case      :  Dict					,							snake_case      :  int					,							snake_case      :  int					,							):
								UpperCAmelCase_					:Optional[Any]      			=      self.num_labels
								UpperCAmelCase_					:Optional[int]      			=      ElectraForSequenceClassification(snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:Any      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.num_labels)     )





				def 				snake_case_ (							self      :  Optional[int]					,							snake_case      :  Union[str, Any]					,							snake_case      :  List[str]					,							snake_case      :  Optional[int]					,							snake_case      :  List[Any]					,							snake_case      :  List[str]					,							snake_case      :  str					,							snake_case      :  str					,							snake_case      :  List[Any]					,							):
								UpperCAmelCase_					:Union[str, Any]      			=      ElectraForQuestionAnswering(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:Optional[Any]      			=      model(
								    snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							start_positions=snake_case					,							end_positions=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)     )





				def 				snake_case_ (							self      :  Union[str, Any]					,							snake_case      :  Optional[int]					,							snake_case      :  List[str]					,							snake_case      :  str					,							snake_case      :  Any					,							snake_case      :  str					,							snake_case      :  Optional[int]					,							snake_case      :  Optional[int]					,							snake_case      :  Optional[int]					,							):
								UpperCAmelCase_					:Union[str, Any]      			=      self.num_choices
								UpperCAmelCase_					:Dict      			=      ElectraForMultipleChoice(config=snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:List[Any]      			=      input_ids.unsqueeze(1     ).expand(-1					,							self.num_choices					,							-1     ).contiguous()
								UpperCAmelCase_					:Dict      			=      token_type_ids.unsqueeze(1     ).expand(-1					,							self.num_choices					,							-1     ).contiguous()
								UpperCAmelCase_					:int      			=      input_mask.unsqueeze(1     ).expand(-1					,							self.num_choices					,							-1     ).contiguous()
								UpperCAmelCase_					:Optional[int]      			=      model(
								    snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case					,							)
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.num_choices)     )





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:List[Any]      			=      self.prepare_config_and_inputs()
								(
								    (
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,
								)					:List[str]      			=      config_and_inputs
								UpperCAmelCase_					:Dict      			=      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
								return config, inputs_dict



@require_torch
class  _snake_case				(							A__							,						A__							,						unittest.TestCase       ):

				'''simple docstring'''




				UpperCamelCase__		     =(
				    (
				        ElectraModel,
				        ElectraForPreTraining,
				        ElectraForMaskedLM,
				        ElectraForCausalLM,
				        ElectraForMultipleChoice,
				        ElectraForTokenClassification,
				        ElectraForSequenceClassification,
				        ElectraForQuestionAnswering,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCamelCase__		     =(
				    {
				        """feature-extraction""": ElectraModel,
				        """fill-mask""": ElectraForMaskedLM,
				        """question-answering""": ElectraForQuestionAnswering,
				        """text-classification""": ElectraForSequenceClassification,
				        """text-generation""": ElectraForCausalLM,
				        """token-classification""": ElectraForTokenClassification,
				        """zero-shot""": ElectraForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				UpperCamelCase__		     =True





				def 				snake_case_ (							self      :  List[str]					,							snake_case      :  List[str]					,							snake_case      :  Tuple					,							snake_case      :  List[Any]=False     ):
								UpperCAmelCase_					:Optional[int]      			=      super()._prepare_for_class(snake_case					,							snake_case					,							return_labels=snake_case     )

								if return_labels:
												if model_class in get_values(snake_case     ):
																UpperCAmelCase_					:Dict      			=      torch.zeros(
																    (self.model_tester.batch_size, self.model_tester.seq_length)					,							dtype=torch.long					,							device=snake_case     )
								return inputs_dict





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:int      			=      ElectraModelTester(self     )
								UpperCAmelCase_					:List[str]      			=      ConfigTester(self					,							config_class=snake_case					,							hidden_size=37     )





				def 				snake_case_ (							self      :  List[Any]     ):
								self.config_tester.run_common_tests()





				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Union[str, Any]      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_model(*snake_case     )





				def 				snake_case_ (							self      :  List[str]     ):
								UpperCAmelCase_					:str      			=      self.model_tester.prepare_config_and_inputs_for_decoder()
								self.model_tester.create_and_check_electra_model_as_decoder(*snake_case     )





				def 				snake_case_ (							self      :  Union[str, Any]     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
												UpperCAmelCase_					:Dict      			=      type
												self.model_tester.create_and_check_electra_model(*snake_case     )





				def 				snake_case_ (							self      :  str     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_masked_lm(*snake_case     )





				def 				snake_case_ (							self      :  Tuple     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_token_classification(*snake_case     )





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:Optional[int]      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_pretraining(*snake_case     )





				def 				snake_case_ (							self      :  Dict     ):
								UpperCAmelCase_					:Any      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_sequence_classification(*snake_case     )





				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Union[str, Any]      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_question_answering(*snake_case     )





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:int      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_multiple_choice(*snake_case     )





				@slow
				def 				snake_case_ (							self      :  Dict     ):
								for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase_					:Optional[int]      			=      ElectraModel.from_pretrained(snake_case     )
												self.assertIsNotNone(snake_case     )





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:Any      			=      self.model_tester.prepare_config_and_inputs_for_decoder()
								self.model_tester.create_and_check_electra_for_causal_lm(*snake_case     )



@require_torch
class  _snake_case				(							unittest.TestCase       ):

				'''simple docstring'''




				@slow
				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Optional[int]      			=      ElectraModel.from_pretrained('''google/electra-small-discriminator'''     )
								UpperCAmelCase_					:Dict      			=      torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]     )
								UpperCAmelCase_					:int      			=      torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]     )
								UpperCAmelCase_					:Optional[int]      			=      model(snake_case					,							attention_mask=snake_case     )[0]
								UpperCAmelCase_					:Optional[Any]      			=      torch.Size((1, 11, 256)     )
								self.assertEqual(output.shape					,							snake_case     )
								UpperCAmelCase_					:Optional[int]      			=      torch.tensor(
								    [[[0.4_471, 0.6_821, -0.3_265], [0.4_627, 0.5_255, -0.3_668], [0.4_532, 0.3_313, -0.4_344]]]     )

								self.assertTrue(torch.allclose(output[:, 1:4, 1:4]					,							snake_case					,							atol=1e-4     )     )


